@unbrained/pm-cli 2026.10.20 → 2026.10.22
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 +142 -77
- package/dist/cli/error-guidance.d.ts +8 -0
- package/dist/cli/error-guidance.js +2 -2
- package/dist/cli/main.js +1 -1
- package/dist/cli/register-list-query.js +2 -2
- package/dist/cli/register-operations.js +1 -1
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/{chunk-QMZ73FCW.js → chunk-2B5HAZFK.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-35ISFIPC.js +113 -0
- package/dist/cli-bundle/chunks/chunk-4D25HF3V.js +2 -0
- package/dist/cli-bundle/chunks/chunk-5LSN7K4N.js +2 -0
- package/dist/cli-bundle/chunks/chunk-7OTYULIJ.js +30 -0
- package/dist/cli-bundle/chunks/{chunk-GHJOMRSF.js → chunk-AOAQDCXX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-ZA3XXHEE.js → chunk-BAIVTLJM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-LS55VKRK.js → chunk-C37RDYZI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YT2Z3JPC.js → chunk-E3JC3WQL.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-YECCKB4E.js → chunk-GWIGZDRS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YTHI5DTH.js → chunk-HC2DCGFA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +2 -0
- package/dist/cli-bundle/chunks/chunk-J444ZX23.js +126 -0
- package/dist/cli-bundle/chunks/{chunk-VLJLWZBO.js → chunk-LIC5EUQS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KU4Q3MSI.js → chunk-MV3KYY2A.js} +6 -6
- package/dist/cli-bundle/chunks/chunk-O67N62DT.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TZU6U5ZE.js → chunk-PCPOTFJP.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-TNU3XVPC.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-7ZOIZ2AZ.js → chunk-URV4VHQ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-YW6SIKYP.js → chunk-UYYTV2TX.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-VO3KDIU7.js +9 -0
- package/dist/cli-bundle/chunks/{indexed-receipt-blobs-U7VGKIYC.js → indexed-receipt-blobs-L3BOTMZN.js} +2 -2
- package/dist/cli-bundle/chunks/mutation-admission-TATOFEXF.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-NNDV6F6I.js → register-list-query-GULR2IYO.js} +5 -5
- package/dist/cli-bundle/chunks/{register-mutation-3GCBSNQS.js → register-mutation-HLSQ4WVW.js} +4 -4
- package/dist/cli-bundle/chunks/register-operations-FE3GGA7O.js +2 -0
- package/dist/cli-bundle/chunks/register-setup-XUIKAIZA.js +2 -0
- package/dist/cli-bundle/chunks/{settlement-hook-CLRGA6O7.js → settlement-hook-UVFYSBMU.js} +2 -2
- package/dist/cli-bundle/chunks/stage-QCPZBZRC.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25L3L2PF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-25NQRZ7J.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-2GFTVXKZ.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-HUZAXSIJ.js → chunk-3LWH2RJC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-46HBJC6J.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-A52W6GLA.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-CB7TSZ7P.js +3 -0
- package/dist/cli-bundle/focused-chunks/{chunk-VLSER3XW.js → chunk-CX5FNEFC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-DVNUHTVK.js +9 -0
- package/dist/cli-bundle/focused-chunks/{chunk-LJPUJ2KK.js → chunk-EHPRSWJE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-GC4VMLXL.js +20 -0
- package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KKRFSI2N.js → chunk-GVKYTDOH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-NI6NS44Q.js → chunk-KM77WU5U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-QGDKWULS.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QWKCQ5PW.js +91 -0
- package/dist/cli-bundle/focused-chunks/chunk-SOVXHW6Z.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SXVJRLLP.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-E4II2D2B.js → chunk-TMN3RAXZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-F7FD25TG.js → chunk-UQ5JPBY2.js} +11 -11
- package/dist/cli-bundle/focused-chunks/chunk-UUPJ6OZL.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-VYAZND5Q.js +78 -0
- package/dist/cli-bundle/focused-chunks/chunk-W2CND3BD.js +65 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZGEK57KD.js → chunk-XX5JQCLF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-H2G6CCGO.js → indexed-receipt-blobs-AAQOKO5B.js} +2 -2
- package/dist/cli-bundle/focused-chunks/mutation-admission-TBKR4KRM.js +2 -0
- package/dist/cli-bundle/focused-chunks/{settlement-hook-5SNBBT7C.js → settlement-hook-MNCHFCAX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/stage-RM6MJIMT.js +2 -0
- 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 +23 -23
- 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 +58 -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 +7 -7
- package/dist/core/item/actionability.js +1 -1
- package/dist/core/lock/lock-gc.d.ts +12 -5
- package/dist/core/lock/lock-gc.js +1 -1
- package/dist/core/lock/lock-owner.d.ts +33 -0
- package/dist/core/lock/lock-owner.js +2 -0
- package/dist/core/lock/lock.d.ts +11 -22
- package/dist/core/lock/lock.js +4 -3
- package/dist/core/output/output.js +3 -3
- package/dist/core/shared/errors.d.ts +2 -0
- package/dist/core/shared/errors.js +1 -1
- package/dist/mcp/server.d.ts +2 -2
- package/dist/mcp/server.js +1 -1
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +1 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-option-contracts.d.ts +6 -0
- package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
- package/dist/sdk/cli-contracts/tool-schema.js +1 -1
- package/dist/sdk/context-intent-contracts.d.ts +13 -0
- package/dist/sdk/context-intent-contracts.js +1 -1
- package/dist/sdk/contracts.d.ts +1 -1
- package/dist/sdk/contracts.js +1 -1
- package/dist/sdk/core.d.ts +2 -2
- package/dist/sdk/core.js +1 -1
- package/dist/sdk/define.d.ts +15 -16
- package/dist/sdk/define.js +1 -1
- package/dist/sdk/dependencies.js +1 -1
- package/dist/sdk/extension-command-context.js +2 -2
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
- package/dist/sdk/governance/assurance-action.js +1 -1
- package/dist/sdk/governance/assurance.js +1 -1
- package/dist/sdk/governance/health.js +2 -2
- package/dist/sdk/merge/install.js +2 -2
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/pagination.d.ts +3 -3
- package/dist/sdk/pagination.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/context.d.ts +5 -0
- package/dist/sdk/query/context.js +2 -2
- package/dist/sdk/query/list.d.ts +2 -0
- package/dist/sdk/query/list.js +1 -1
- package/dist/sdk/query/projection-contracts.d.ts +1 -1
- package/dist/sdk/query/projection-contracts.js +1 -1
- package/dist/sdk/read-output/session-result.d.ts +39 -0
- package/dist/sdk/read-output/session-result.js +2 -0
- package/dist/sdk/read-output-contracts.d.ts +18 -5
- package/dist/sdk/read-output-contracts.js +1 -1
- package/dist/sdk/read-output-session.d.ts +2 -0
- package/dist/sdk/read-output-session.js +1 -1
- package/dist/sdk/relationship-context.js +1 -1
- package/dist/sdk/runtime/mutation-admission.d.ts +2 -0
- package/dist/sdk/runtime/mutation-admission.js +2 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +1 -1
- package/dist/sdk/runtime-primitives.d.ts +6 -0
- package/dist/sdk/runtime-primitives.js +1 -1
- package/dist/sdk/runtime.d.ts +10 -8
- package/dist/sdk/runtime.js +1 -1
- package/dist/sdk/test/execution.d.ts +1 -0
- package/dist/sdk/test/execution.js +2 -2
- package/dist/sdk/workspace.d.ts +3 -1
- package/dist/sdk/workspace.js +8 -5
- package/docs/AGENT_RUNTIME_PRIMITIVES.md +9 -0
- package/docs/ASSURANCE.md +17 -2
- package/docs/COMMANDS.md +17 -3
- package/docs/CONFIGURATION.md +38 -0
- package/docs/CONTEXT_RELEVANCE.md +15 -0
- package/docs/DEVELOPMENT_DEPENDENCY_SECURITY.md +56 -3
- package/docs/MCP_OPTION_CONFORMANCE.md +27 -1
- package/docs/MERGE_SAFETY.md +8 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +79 -0
- package/docs/RELATIONSHIP_GRAPH.md +15 -0
- package/docs/RELEASING.md +8 -0
- package/docs/SDK.md +104 -7
- package/docs/TESTING.md +23 -0
- package/docs/agent-task-token-baseline.json +1 -1
- 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-2GGGOD7P.js +0 -30
- package/dist/cli-bundle/chunks/chunk-7NHA5K77.js +0 -126
- package/dist/cli-bundle/chunks/chunk-PNPE2OVJ.js +0 -112
- package/dist/cli-bundle/chunks/chunk-PTL3TBT6.js +0 -20
- package/dist/cli-bundle/chunks/chunk-QETMESEB.js +0 -6
- package/dist/cli-bundle/chunks/chunk-QQYCB2LO.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-YKDGNKUL.js +0 -2
- package/dist/cli-bundle/chunks/register-setup-AOUZQQWB.js +0 -2
- package/dist/cli-bundle/chunks/stage-6QXYRMSU.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-37SU7BZI.js +0 -3
- package/dist/cli-bundle/focused-chunks/chunk-6IU7BESB.js +0 -65
- package/dist/cli-bundle/focused-chunks/chunk-AS3MOBO3.js +0 -25
- package/dist/cli-bundle/focused-chunks/chunk-AW35RDKA.js +0 -78
- package/dist/cli-bundle/focused-chunks/chunk-GYHZ7W6O.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-H5Q2HUU6.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-J6EYUGAR.js +0 -6
- package/dist/cli-bundle/focused-chunks/chunk-JEXZEIAX.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-KDGUIIRU.js +0 -20
- package/dist/cli-bundle/focused-chunks/chunk-MQ42BFGX.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VAYS754X.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-VS6VTWTZ.js +0 -8
- package/dist/cli-bundle/focused-chunks/stage-EMTISXR7.js +0 -2
|
@@ -1,112 +0,0 @@
|
|
|
1
|
-
import{A as h,C as g,E as ft,F as Se,G as le,H as ge,I as Xc,J as Ri,K as mt,L as Jc,a as Re,b as Ci,c as Vc,e as xn,f as Nn,g as Dn,h as Bc,i as Pn,j as qt,k as Wc,m as we,n as Gc,o as Kc,p as Mn,q as $n,u as Tr,v as Yc,y as S,z as Cr}from"./chunk-YECCKB4E.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 N_=[["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"})),D_=[...["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"})),P_=[["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"})),M_=[...D_,...P_,...["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}))],xi=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...N_,...M_,...["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 UI(e){let t;for(let r of xi)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 $_(e){let t=e.trim().replace(/\s+/gu," ");return xi.find(r=>r.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function Rr(e){return $_(e)}var jn=[...xi,...[["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"}))],HI=Object.fromEntries(jn.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function qI(e){let t=e.trim().toLowerCase();return jn.find(r=>r.alias===t)}function VI(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 Ni=[{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 zn(e){return e.trim().toLowerCase().replaceAll("-","_")}function j_(e){if(e===void 0)return;let t=zn(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function Pi(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)Pi(r,t);return Object.freeze(e)}for(let r of Object.values(e))Pi(r,t);return Object.freeze(e)}function L_(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 F_(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 z_(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 U_(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=zn(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 H_(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 q_(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 V_(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Mi=class{#e=new Map;#r=new Map;constructor(t=Ni){for(let r of t)this.register(r)}register(t){let r=U_(t);if(H_(t,r),q_(t,r),L_(t,r),F_(t,r),z_(t,r),this.#e.has(r)||this.#r.has(r))throw new TypeError(`Relationship kind already registered: ${r}`);let n=j_(t.inverse),o=[...new Set((t.aliases??[]).map(zn))].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:V_(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:n,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?Pi(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=zn(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 $i(){return new Mi}var pt=$i();function YI(e){return pt.require(e).kind}function XI(e){return pt.resolve(e)?.kind}function JI(e,t=pt){return t.resolve(e)?.ordering===!0}function B_(e,t,r,n=pt){let o=xr(e),i=xr(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 Ln(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function W_(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=B_(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 Fn(e,t,r){let n=e.get(t);n?n.push(r):e.set(t,[r])}function xr(e){return typeof e=="string"?e.trim():""}function Di(e,t){let r=xr(e);return r&&t.has(r)?r:void 0}function G_(e,t,r){let n=[t],o=t;for(;o!==e;)o=r.get(o),n.push(o);return n.reverse()}var Zc=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}=W_(i,this.#r,n);o.set(a,s)}this.#n=Object.freeze([...o.values()].sort(Ln));for(let i of this.#n)Fn(this.#s,i.source,i),Fn(this.#a,i.target,i),n.require(i.kind).direction==="undirected"&&(Fn(this.#s,i.target,i),Fn(this.#a,i.source,i))}static fromItems(t,r=pt){let n=new Set(t.map(i=>xr(i.id)).filter(Boolean)),o=[];for(let i of t){let s=xr(i.id);if(!s)continue;let a=Di(i.parent,n);a&&o.push({source:s,target:a,kind:"parent"});let c=Di(i.blocked_by,n);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Di(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||Ln(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)||Ln(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:G_(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(Ln)},meta:n.meta}}};function ZI(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 K_="__pm_suppress_host_output",ji="@unbrained/pm-cli:suppress-host-output:v1";function Qc(e){return e===void 0?{__pm_suppress_host_output:ji}:{__pm_suppress_host_output:ji,result:e}}function Un(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[K_]===ji}import Vt from"node:fs";import xe from"node:path";import{fileURLToPath as Y_}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 X_="@unbrained/pm-cli";function J_(e){try{return JSON.parse(Vt.readFileSync(e,"utf8")).name===X_}catch{return!1}}function Z_(e){let t=Vt.existsSync(e)&&Vt.statSync(e).isDirectory()?xe.resolve(e):xe.dirname(xe.resolve(e));for(;;){let r=xe.join(t,"package.json");if(Vt.existsSync(r)&&J_(r))return t;let n=xe.dirname(t);if(n===t)return;t=n}}function Hn(e,t=[]){let r=Y_(e);return Z_(r)||xe.resolve(xe.dirname(r),...t)}function oT(e,t=[]){try{let r=xe.join(Hn(e,t),"package.json");if(!Vt.existsSync(r))return;let n=JSON.parse(Vt.readFileSync(r,"utf8"));return typeof n.version=="string"&&n.version.trim().length>0?n.version:void 0}catch{return}}function iT(e=process.env,t="PM_CLI_PACKAGE_ROOT",r,n=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?xe.resolve(o.trim()):r?Hn(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 Q_(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function aT(e){return Q_(e)??void 0}function cT(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 dT(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function td(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function qn(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 lT(e){let t=qn(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function uT(e,t,r){let n=qn(e);return n===null||n<t||n>r?null:n}function fT(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function Ue(e){return typeof e!="object"||e===null?null:e}function ed(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function rd(e){let t=ed(e);if(!t)return null;if(typeof t.activate=="function")return t;let r=ed(t.default);return typeof r?.activate=="function"?r:null}function mT(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 ey=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],nd=ey,Bt=["draft","open","in_progress","blocked","closed","canceled"],Vn=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Wt=["string","number","boolean","string_array","array","object"],Bn=["create","update","update_many","list","search","calendar","context"],Wn=["allow","warn","reject"],_T=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],yT=["project","global"],hT=["low","medium","high","critical"],Gn=["low","medium","high","critical"],Kn=["low","medium","high"];var od=["minimal","default","strict","custom"],gT=["none","warn","strict"],bT=["progressive","strict"],wT=["off","warn","strict"],vT=["off","warn","strict"];var Yn=["daily","weekly","monthly","yearly"],Nr=["mon","tue","wed","thu","fri","sat","sun"];function Li(e){return Nr.indexOf(e)}var ET=["draft","research","review","approved","executing","paused","completed","superseded"],id=["pending","in_progress","completed","blocked","skipped","superseded"],kT=["codex","claude-code","cursor","generic"],ST=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],OT=["brief","standard","deep","full"],AT=["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 iy 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 He(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function ty(e){let t=e.key.trim();if(t.length===0)return null;let r=He(e.aliases),n=e.description?.trim();return{key:t,values:He(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 ry=e=>e,ad=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function ny(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 oy(e,t){let r=new Map;for(let n of e??[]){let o=ny(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 sd(e,t){return t?He(e):void 0}function Fi(e){let t=e?.trim();return t&&t.length>0?t:void 0}function zi(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 Xn(e,t={}){let r=t.resolvePolicyCommand??ry,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=He(e.aliases),d=(e.options??[]).map(u=>ty(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=oy(e.command_option_policies,r);return{name:n,description:Fi(e.description),default_status:Fi(e.default_status),...e.execution_role===void 0?{}:{execution_role:zi(e.execution_role)},folder:Fi(e.folder),aliases:c.length>0?c:void 0,required_create_fields:sd(e.required_create_fields,o),required_create_repeatables:sd(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 sy=Object.freeze({decision:"human",milestone:"gate"}),ay=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],cy=["dep","comment","note","learning","file","test","doc"],dd=["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"],dy=["title","description","type","status","priority","tags","body",...dd,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ly=["title","description","body","status","closeReason","priority","type","tags",...dd,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],ld={"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"},uy={...ld},fy={...ld},ud=[["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"]],fd=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function md(e){return Object.fromEntries(e)}var my=md([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...ud,["author","--author"],["message","--message"],["dep","--dep"],...fd]),py=md([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...ud,...fd,["author","--author"],["message","--message"],["force","--force"]]);function _y(e){return e.trim().replace(/^--+/,"").toLowerCase()}function yy(e){return e==="create"?dy:ly}function hy(e){return e==="create"?uy:fy}function pd(e,t){let r=_y(t);return r.length===0?void 0:hy(e)[r]||yy(e).find(n=>n.toLowerCase()===r)}function MT(e,t){return(e==="create"?my:py)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Hi(e){let t=by(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function gy(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),n=iy.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 by(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 wy(e){return Xn(e,{resolvePolicyCommand:ad})}function Dr(e,t){let r=e[t];return Array.isArray(r)?r.filter(n=>typeof n=="string"):void 0}function vy(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:Dr(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Dr(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Ey(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 ky(e){if(Array.isArray(e.options))return e.options.map(t=>vy(t)).filter(t=>t!==null)}function Sy(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Ey(t)).filter(t=>t!==null)}function Oy(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:zi(t.execution_role),folder:n,aliases:Dr(t,"aliases"),required_create_fields:Dr(t,"required_create_fields"),required_create_repeatables:Dr(t,"required_create_repeatables"),options:ky(t),command_option_policies:Sy(t)}}function Ay(e,t){return e.required_create_fields?He(e.required_create_fields):t?.required_create_fields??[]}function Iy(e,t){return e.required_create_repeatables?He(e.required_create_repeatables):t?.required_create_repeatables??[]}function Ty(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Cy(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Ry(e,t){let r=t?.name??e.name,n=e.description??t?.description,o=e.default_status??t?.default_status,i=gy(e.folder??t?.folder??Hi(r)),s={name:r,execution_role:e.execution_role,folder:i,aliases:He([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Ay(e,t),required_create_repeatables:Iy(e,t),options:Ty(e,t),command_option_policies:Cy(e,t)};return n&&(s.description=n),o&&(s.default_status=o),s}function cd(e,t){for(let r of e){let n=wy(r);if(!n)continue;let o=n.name.toLowerCase(),i=t.get(o);t.set(o,Ry({...n,execution_role:n.execution_role??i?.execution_role},i))}}function xy(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=Oy(o);i&&t.push(i)}}return t}function $T(e,t=null){let r=new Map;for(let c of nd)r.set(c.toLowerCase(),{name:c,execution_role:sy[c.toLowerCase()]??"agent",folder:Tr[c],aliases:[],required_create_fields:[...ay],required_create_repeatables:[...cy],options:[],command_option_policies:[]});cd(e.item_types?.definitions??[],r),cd(xy(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 Ny(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Dy(e,t){let r=Ny(e,t);if(r)return t.by_type[r]}function Py(e,t,r,n){for(let o of n){let i=pd(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 Ui(e,t,r){if(r){e.add(t);return}e.delete(t)}function My(e,t,r,n){let o=pd(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&&Ui(e.required,o,n.required),n.visible!==void 0&&Ui(e.hidden,o,!n.visible),n.enabled!==void 0&&Ui(e.disabled,o,!n.enabled)}function $y(e,t,r){for(let n of t.command_option_policies)n.command===r&&My(e,t,r,n)}function jy(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 jT(e,t,r){let n=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:n};return Py(a,e,t,r),$y(a,e,t),jy(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:n}}function Ly(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 Fy(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 LT(e,t,r){let n=Dy(e,r);if(!n)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Ly(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=Fy(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 zy,readdirSync as Uy,realpathSync as _d,statSync as yd}from"node:fs";import Hy from"node:os";import T 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 qy={json_markdown:".md",toon:".toon"},Vy={".md":"json_markdown",".toon":"toon"},By=new Set([".git","coverage","dist","node_modules"]),GT=[".md",".toon"];function Pr(e){try{return yd(e),!0}catch{return!1}}function Wy(e){let t=T.resolve(e),r=[];for(;T.dirname(t)!==t;)try{return T.join(_d(t),...r)}catch(n){if(!Se(n))throw n;r.unshift(T.basename(t)),t=T.dirname(t)}return T.join(_d(t),...r)}function Gy(e){try{return yd(e),!0}catch(t){if(Se(t))return!1;throw t}}function hd(e){try{let t=JSON.parse(zy(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Ky(e){let t=Wy(e);for(;;){let r=T.join(t,Mn),n=T.join(r,$n);if(Pr(n))return r;let o=T.join(t,$n);if(Pr(o)&&hd(o))return t;if(Gy(T.join(t,".git")))return r;let i=T.dirname(t);if(i===t)return;t=i}}function Yy(e){return Ky(e)??T.resolve(e,Mn)}function KT(e,t){let r=t?T.resolve(t):void 0;try{return Uy(T.resolve(e),{withFileTypes:!0}).filter(n=>n.isDirectory()&&!By.has(n.name)).map(n=>T.join(T.resolve(e),n.name)).filter(n=>n!==r).filter(n=>Pr(Oe(n))).filter(n=>hd(Oe(n))).sort((n,o)=>n.localeCompare(o))[0]}catch{return}}function YT(e,t){let r=process.env.PM_PATH,n=t?.trim()||r?.trim();if(n){let o=T.resolve(e,n);if(!Pr(Oe(o))){let i=T.join(o,Mn);if(Pr(Oe(i)))return i}return o}return Yy(e)}function XT(e){let t=T.resolve(e),r=T.dirname(t);return T.basename(t)==="pm"&&T.basename(r)===".agents"?T.dirname(r):t}function gd(e){let t=process.env.PM_GLOBAL_PATH?.trim(),r=t&&t.length>0?t:T.join(Hy.homedir(),".pm-cli");return T.resolve(e,r)}function Oe(e){return T.join(e,$n)}function Xy(e,t,r=Tr){let n=r[t]??Hi(t);return T.join(e,n)}function JT(e,t,r,n="toon",o=Tr){return T.join(Xy(e,t,o),`${r}${qy[n]}`)}function ZT(e){let t=e.replaceAll("\\","/"),r=T.posix.extname(t).toLowerCase();return Vy[r]??null}function QT(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return T.join(e,"history",`${t}.jsonl`)}function qi(e,t){return T.join(e,"locks",`${t}.lock`)}function Vi(e){return T.join(e,"runtime")}function Jn(e){return T.join(Vi(e),"test-runs")}function Jy(e){return T.join(Jn(e),"runs")}function eC(e,t){return T.join(Jy(e),`${t}.json`)}function Zy(e){return T.join(Jn(e),"stdout")}function Qy(e){return T.join(Jn(e),"stderr")}function tC(e,t){return T.join(Zy(e),`${t}.log`)}function rC(e,t){return T.join(Qy(e),`${t}.log`)}function eh(e){return T.join(Jn(e),"results")}function nC(e,t){return T.join(eh(e),`${t}.json`)}import th 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 rh(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 nh(e){let t=Object.keys(e).sort(),r={};for(let n of t){let o=e[n];o!==void 0&&(r[n]=Zn(o))}return r}function Zn(e){let t=rh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(n=>Zn(n));if(e instanceof Date)return e.toISOString();let r=e;if(typeof r.toJSON=="function"){let n=r.toJSON();if(n!==e)return Zn(n)}return nh(e)}function R(e){return JSON.stringify(Zn(e))}function bd(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 oh(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function ih(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function sh(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(!bd(o,r,n,B))return!1;return!0}function ah(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(!bd([o,i],r,n,([s,a],[c,d])=>B(s,c)&&B(a,d)))return!1;return!0}function ch(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)=>B(r,t[n]))}function dh(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]||!B(e[i],t[i]))return!1}return!0}var lh=[oh,ih,sh,ah,ch];function B(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 lh){let n=r(e,t);if(n!==void 0)return n}return dh(e,t)}function Qn(e){return th.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 vd}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 uh=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],wd=256,Bi=64;function se(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 Ne(e,t,r){if(typeof e!="object"||e===null||Array.isArray(e))return se(`${r} must be an object`);let n=e;return Object.keys(n).some(o=>!t.includes(o))?se(`${r} contains an unknown key`):n}function _t(e,t,r=128){return typeof e!="string"||!e.trim()||e.length>r?se(`${t} must be nonempty text of at most ${r} characters`):e.trim()}function Mr(e,t){if(!Array.isArray(e)||e.length===0||e.length>Bi)return se(`${t} requires 1-${Bi} 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)))?se("fields must be safe metadata paths of at most eight segments"):[...new Set(r)]}function fh(e){let t=Ne(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(Ne(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>Bi?se("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(r=>!Array.isArray(r)||r.length!==2?se("transition pairs need two statuses"):[_t(r[0],"from"),_t(r[1],"to")])}):t.kind==="authors"?(Ne(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Mr(t.authors,"authors")}):t.kind==="require_fields"?(Ne(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Mr(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(Ne(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Mr(t.fields,"fields"),authors:Mr(t.authors,"authors")}):se("unknown rule kind")}function mh(e){let t={},r=Ne(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let n of["types","tags","statuses","operations","parents"])r[n]!==void 0&&(t[n]=Mr(r[n],n));if(r.dependency!==void 0){let n=Ne(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 ph(e){let t=Ne(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))?se("effect must be advise, warn, or refuse"):{id:r,rule:fh(t.rule),...t.subject===void 0?{}:{subject:mh(t.subject)},...t.description===void 0?{}:{description:_t(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:se("id must be a stable token")}function _h(e){let t=Ne(e,["version","enforcement","policies"],"document");if(t.version!==1)return se("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return se("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>wd)return se(`policies must contain at most ${wd} declarations`);let r=t.policies.map(ph);return new Set(r.map(n=>n.id)).size!==r.length?se("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:r}}function eo(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 yh(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 Ed(e){return vd("sha256").update(R(e)).digest("hex")}function hh(e,t){let r=e.rule.kind==="approval"?e.rule.fields:[];return vd("sha256").update(R({id:t.id,fields:r.map(n=>[n,eo(t,n)])})).digest("hex")}function gh(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 bh(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&&!gh(e.dependency,t.dependencies))}function wh(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&&bh(r,{...o,status:n},t.operation))}function vh(e,t,r,n){let o=["type","tags","parent","dependencies"].some(i=>!B(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||r||n||o)?e.filter(i=>!yh(eo(t.after,i))):[]}function Eh(e,t,r,n){let o=t.after??t.before,i=hh(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 kh(e,t,r){let n=e.rule,o=t.before?.status!==t.after?.status,i="fields"in n&&n.fields.some(s=>!B(eo(t.before,s),eo(t.after,s)));switch(n.kind){case"require_fields":{let s=vh(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||Eh(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 kd(e,t,r){let n=e.policies.filter(o=>wh(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,...kh(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 uC(e,t){return kd(e,t,Ed)}function fC(e){let t=_h(e),r=new Map(t.policies.map(n=>[n,Ed(n)]));return n=>kd(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 Sh=[...Re],Oh=[...qt],Ah=[...xn],hC=[...Nn],gC=[...Dn],Ih=[...Pn],to=["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"],bC=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],wC=["install","reconcile","report","driver"],Th=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Ch=["upgrade"],Rh=["reopen"],Sd={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Gt=Object.freeze(to.flatMap(e=>e in Sd?[]:e==="extension"||e==="package"?[...Th.map(t=>`${e}-${t}`),...e==="package"?Ch.map(t=>`package-${t}`):[],e]:e==="item"?Rh.map(t=>`item-${t}`):[e])),xh=Object.freeze(jn.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Gt.includes(e.alias)).map(e=>e.alias)),vC=Object.freeze(Gt.filter(e=>!xh.includes(e)));function EC(e=to,t=Gt,r=Sd){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 kC(e){return Gt.includes(e)}function SC(e){return Sh.includes(e)}function OC(e){return Oh.includes(e)}function AC(e){return Ah.includes(e)}function IC(e){return Ih.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 ro={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},no=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Kt=["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 Nh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function ue(e){return e?D(e):{}}function fe(e){return e?D(e):Nh()}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 Dh=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),Ph=["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 Mh(e,t){for(let r of Ph){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=>Dh.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 $h(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 jh(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 oo(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(!Mh(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=$h(o);if(s===null)return null;r.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=jh(i);if(s===null)return null;r.preflight_ownership=s}return r}function NC(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 io(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 $r(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function qe(e){return Re.includes(e)}function Od(e){let t=e.trim().toLowerCase();return qe(t)?t:null}function Ad(e){return e.filter(t=>!qe(t))}function Wi(e){let t=e.trim().toLowerCase();return t.length===0?null:Vc[t]??null}function Id(e){let t=$r([...e].map(i=>i.toLowerCase())),r=[],n=[];for(let i of t){let s=Wi(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:$r(r),legacy_aliases:o}}function Lh(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let r=Wi(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 Re){let a=io(t,s,n);a!==null&&a<i&&(i=a,o=s)}return o}function Td(e,t,r){let n=Re.join(","),o=Lh(r)??"none";return`extension_capability_unknown:${e}:${t}:${r}:allowed=${n}:suggested=${o}`}function Cd(e,t,r){let n=r.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${n}`}function Fh(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=Wi(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:n,capability:o,allowed_capabilities:c,capability_contract_version:Ci,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function zh(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,r,n,o]=t,i=r,s=[...Re],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!qe(f)||a.push({layer:i,name:n,capability:u,allowed_capabilities:s,capability_contract_version:Ci,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 jr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Gi(){return{overrides:[],handlers:[]}}function Ki(){return{overrides:[]}}function Yi(){return{overrides:[]}}function Xi(){return{overrides:[]}}function Ji(){return{overrides:[]}}function Zi(){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 Uh=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 Hh(e){return{unknownKeys:Object.keys(e).filter(t=>!Uh.has(t)).sort((t,r)=>t>r?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function qh(e){let t=Hh(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 Rd(e,t,r){return qh(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 Ve}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 xd=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"}]]),Vh=/^[a-z][a-z0-9_]{0,63}$/u,Bh=new Map([[Ve.errno.EACCES,"EACCES"],[Ve.errno.EDQUOT,"EDQUOT"],[Ve.errno.EMFILE,"EMFILE"],[Ve.errno.ENFILE,"ENFILE"],[Ve.errno.ENOMEM,"ENOMEM"],[Ve.errno.ENOSPC,"ENOSPC"],[Ve.errno.EPERM,"EPERM"],[Ve.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),Wh={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function Gh(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&xd.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Bh.get(Math.abs(t.errno))??null}function Kh(e,t,r={}){let n=Gh(e);if(n===null)return null;if(!Vh.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=xd.get(n);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:r.codes?.[o.category]??Wh[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 Nd(e,t,r={}){try{return await t()}catch(n){throw Kh(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 Yh=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"}]),Qi=new Set(Yh.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 Dd=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function es(e){if(typeof e!="string")return null;let t=Dd.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 WC(e){let t=es(e);return t?t.name:typeof e=="string"&&e.trim()||null}function Xh(e){if(typeof e!="string")return null;let t=e.trim(),r=t.split(/[ =]/,1)[0];return Qi.has(r)?"host_owned_flag_collision":Dd.test(t)?null:"malformed_long_flag"}function Pd(e,t){let r=[e,t].find(i=>typeof i=="string"&&Qi.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=Xh(n);return o===null?null:{token:n,failure:o}}function Md(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 $d=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function so(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn($d,t)?$d[t]:null}function Jh(e,t,r){return!!(e.value_name?.trim()||t||r||e.required===!0||e.list===!0||e.repeatable===!0)}function Zh(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function YC(e){let t=Zh(e),r=so(t),n=es(e.long),o=e.value_name?.trim()||null,i=!(r==="boolean"&&t!=="bool")&&Jh(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 jd(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 Ld(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 XC(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 Qh=5e3;async function Lr(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 eg(e,t){return Lr(e.beforeCommand,"beforeCommand",t)}function tg(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 ts(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."]}))},Qh),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)}tg(n,r,t.operation)}}async function rg(e,t){return Lr(e.afterCommand,"afterCommand",t)}async function rs(e,t){return Lr(e.onWrite,"onWrite",t)}async function ns(e,t){return Lr(e.onRead,"onRead",t)}async function os(e,t){return Lr(e.onIndex,"onIndex",t)}function ng(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 ao(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 og(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 is(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",og(o)],["errorCode",ao(o,"code")],["remediation",ao(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:ng(o),...Object.fromEntries([["errorCode",ao(o,"code")],["remediation",ao(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function ss(e,t){let r=F(t.command);if(r.length===0)return{overridden:!1,context:{command:r,args:D(t.args),options:ue(t.options),global:fe(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:ue(t.options),global:fe(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:ue(t.options),global:fe(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?ue(o.options):ue(t.options),a=o.global?fe(o.global):fe(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:ue(t.options),global:fe(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 as(e,t){let r={command:F(t.command),args:D(t.args),options:ue(t.options),global:fe(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:ue(r.options),global:fe(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?ue(i.options):r.options,global:i.global?fe(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 Fd(e){return{handled:!1,result:e.payload,warnings:[]}}function zd(e,t){return[...e.overrides].reverse().filter(r=>r.service===t)}function Ud(e){return{service:e.service,command:e.command?F(e.command):void 0,args:e.args?D(e.args):void 0,options:e.options?ue(e.options):void 0,global:e.global?fe(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 ig(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 Hd(e,t){return ig(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 qd(e,t,r){return t.service==="output_format"&&typeof e=="object"&&e!==null&&B(e,r.payload)}function Vd(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 cs(e,t){let r=zd(e,t.service);if(r.length===0)return Fd(t);let n=[];for(let o of r)try{let i=Ud(t),s=o.run(i);if(s instanceof Promise){n.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(qd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Vd(o,Hd(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 ds(e,t){let r=zd(e,t.service);if(r.length===0)return Fd(t);let n=[];for(let o of r)try{let i=Ud(t),s=await Promise.resolve(o.run(i));if(qd(s,t,i)){n.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Vd(o,Hd(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 ls(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=ue(t.options),i=fe(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 sg(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 us(e,t){let r=typeof t.command=="string"?F(t.command):"",n=[...e.overrides].reverse().find(o=>o.format===t.format&&sg(o,r,t.result));if(!n)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?D(t.args):[],i=ue(t.options),s=fe(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 Hg}from"node:url";import Bd 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 fs(e,t){let r=Bd.relative(e,t);return r.length===0?!0:!r.startsWith("..")&&!Bd.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 Wd(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 G(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function Z(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function H(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 Gd(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 Fr(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 ms=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 ag=new Set(ms);function cg(e){if(e!==void 0&&!ag.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${ms.join(", ")}`)}function Kd(e){H("registerCommand definition.action",e.action),H("registerCommand definition.family",e.family),H("registerCommand definition.description",e.description),H("registerCommand definition.intent",e.intent),H("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");cg(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 Yd(e,t="",r=""){if(e===void 0)return;if(Yt(t)||Yt(r))throw new TypeError("Native pm commands and actions cannot declare read_output");let n=G("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 Yt(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return Gt.includes(t)||Kt.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 dg(e){let t=G("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 H("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 Xd(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=dg(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 ps(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 Jd(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 be(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 lg(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 Xt(e){return new Set((e??[]).map(t=>lg(t)).filter(t=>t.length>0))}function Zd(e){let t=be(e);return xn.includes(t)?t:"off"}function Qd(e){let t=be(e);return Nn.includes(t)?t:"off"}function zr(e){let t=be(e);return Dn.includes(t)?t:"none"}function _s(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Bc.includes(t)?t:void 0}function el(e){if(typeof e=="string"){let t=_s(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:_s(e.global)??"block",project:_s(e.project)??"block"}:{global:"block",project:"block"}}function ug(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 fg(e){let t=be(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?zr(e.sandbox_profile):void 0,allowedCapabilities:P(e.allowed_capabilities),blockedCapabilities:P(e.blocked_capabilities),allowedSurfaces:Xt(e.allowed_surfaces),blockedSurfaces:Xt(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 tl(e){let t=new Map;for(let r of e??[]){let n=fg(r);n&&t.set(n.name,n.normalized)}return t}function mg(e){let t=[],r=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of $([...e.allowedCapabilities,...e.blockedCapabilities]))qe(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of r)for(let i of $([...o.allowedCapabilities,...o.blockedCapabilities]))qe(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let n=new Set(Pn);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 rl(e){let t=e.extensions?.policy??{},r=P(t.allowed_capabilities),n=P(t.blocked_capabilities),o=Xt(t.allowed_surfaces),i=Xt(t.blocked_surfaces),s=tl(t.extension_overrides);return{mode:Zd(t.mode),trustMode:Qd(t.trust_mode),pmMaxVersionExceededMode:el(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:P(t.trusted_extensions),defaultSandboxProfile:zr(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:mg({allowedCapabilities:r,blockedCapabilities:n,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function nl(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:ug(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 ol(e){let t=tl(e.extension_overrides);return{mode:Zd(e.mode),trustMode:Qd(e.trust_mode),pmMaxVersionExceededMode:el(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:P(e.trusted_extensions),defaultSandboxProfile:zr(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:Xt(e.allowed_surfaces),blockedSurfaces:Xt(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 Be(e,t){return e.overridesByName.get(be(t))??null}function Jt(e,t,r,n,o){return t.has(r)?o:e.size>0&&!e.has(r)?n:null}function il(e,t,r){let n=r.trim().toLowerCase(),o=Be(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return Jt(i,s,n,"capability_not_allowlisted","capability_blocked")}function pg(e,t,r){let n=Be(e,t.name),o=n&&n.allowedSurfaces.size>0?n.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...n?n.blockedSurfaces:[]]);return Jt(o,i,r,"surface_not_allowlisted","surface_blocked")}function _g(e,t,r){let n=F(r);if(n.length===0)return null;let o=Be(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return Jt(i,s,n,"command_not_allowlisted","command_blocked")}function yg(e,t,r){let n=be(r).replace(/\s+/g,"-");if(n.length===0)return null;let o=Be(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return Jt(i,s,n,"action_not_allowlisted","action_blocked")}function hg(e,t,r){let n=be(r);if(n.length===0)return null;let o=Be(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return Jt(i,s,n,"service_not_allowlisted","service_blocked")}function gg(e,t){let r=be(t.name);return Be(e,t.name)?.disabled===!0?"extension_override_disabled":Jt(e.allowedExtensions,e.blockedExtensions,r,"extension_not_allowlisted","extension_blocked")}function bg(e,t){if(e.trustMode==="off")return null;let r=Be(e,t.name),n=be(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 wg(e,t){if(e.mode==="off")return null;let r=Be(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 co(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 sl(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let r=[],n=gg(e,t);n&&r.push({reason:n,scope:"extension",mode:e.mode});let o=bg(e,t);o&&r.push({reason:o,scope:"trust",mode:e.trustMode});let i=wg(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:co("blocked",s.scope,t,s.reason)};let a=r.find(c=>c.mode==="warn");return a?{allowed:!0,warning:co("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function al(e,t,r){if(e.mode==="off")return{allowed:!0,warning:null};let n=il(e,t,r);return n?{allowed:e.mode==="warn",warning:co(e.mode==="warn"?"violation":"blocked","capability",t,n,{capability:r.trim().toLowerCase()})}:{allowed:!0,warning:null}}function vg(e,t,r,n,o){let i=typeof n=="string"?il(e,t,n):null,s=pg(e,t,r),a=o.command?_g(e,t,o.command):null,c=o.action?yg(e,t,o.action):null,d=o.service?hg(e,t,o.service):null;return i??s??a??c??d}function Eg(e,t,r,n){let o={method:be(e).replace(/\s+/g,"_"),surface:t};return r&&(o.capability=r),n.command&&(o.command=F(n.command)),n.action&&(o.action=be(n.action).replace(/\s+/g,"-")),n.service&&(o.service=be(n.service)),o}function cl(e,t,r,n,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=vg(e,t,r,o,s);if(!a)return{allowed:!0,warning:null};let c=co(e.mode==="warn"?"violation":"blocked","registration",t,a,Eg(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 ll=100;function dl(e,t){let r=e[t];if(r!=null)return typeof r!="string"||r.trim().length===0?null:r.trim()}function kg(e){if(e==null)return;let t=Ue(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 ys(e,t){let r=e[t];return typeof r!="string"||r.trim().length===0?null:r.trim()}function ul(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 Sg(e){let t=ul(e.priority);return t===void 0?ll:t}function Og(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let r=zr(t);return r!==t.trim().toLowerCase()?null:r}function hs(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Ag(e){if(e==null)return;let t=Ue(e);if(!t)return null;let r=hs(t.source),n=hs(t.signature),o=hs(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 Ig(e){if(e==null)return;let t=Ue(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 Tg(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(r=>typeof r!="string"))return null;let t=Id(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function Cg(e){if(e==null)return;let t=Ue(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 Rg(e){let t=ul(e.manifest_version);if(t===null)return null;let r=dl(e,"pm_min_version");if(r===null)return null;let n=dl(e,"pm_max_version");if(n===null)return null;let o=kg(e.engines);if(o===null)return null;let i=ht(e.trusted);if(i===null)return null;let s=Og(e);if(s===null)return null;let a=Ag(e.provenance);if(a===null)return null;let c=Ig(e.permissions);if(c===null)return null;let d=Tg(e.capabilities);if(d===null)return null;let l=Cg(e.activation);if(l===null)return null;let u=oo(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 gs(e){if(typeof e!="object"||e===null)return null;let t=e,r=ys(t,"name");if(r===null)return null;let n=ys(t,"version");if(n===null)return null;let o=ys(t,"entry");if(o===null)return null;let i=Sg(t);if(i===null)return null;let s=Rg(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 xg from"node:fs/promises";import Ur 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 fl(e,t){let r=Ur.dirname(t.manifest_path),n=Ur.relative(r,t.entry_path);if(n.startsWith("..")||Ur.isAbsolute(n))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Ur.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Nd("extension_module_graph_snapshot",()=>xg.cp(r,o,{recursive:!0,force:!0})),Ur.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 ml(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 pl(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 lo=Wt;function _l(e){let t=e.trim().toLowerCase();return lo.includes(t)?t:null}function yl(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 lo)if(io(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 hl(e){return e==="toon"||e==="json"}function gl(e){return qt.includes(e)}function gt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var bl=Symbol("extension_registration_trace");function De(e,t){let r=new TypeError(e);return Object.defineProperty(r,bl,{value:t,enumerable:!1,configurable:!1,writable:!1}),r}function wl(e){return e instanceof Error?e[bl]:void 0}function Hr(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Hr(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]=Hr(t[n]);return r}return e}function qr(e){if(Array.isArray(e))return e.map(t=>qr(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]=qr(t[n]);return r}return e}function Zt(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Hr(t)}function Vr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return qr(t)}function Br(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(r=>Zt(e,r))}function ee(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Wr(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function bs(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ws(e,t){return F(`${e} ${t}`)}function Gr(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var Ng=new Set(["low","medium","high"]),Dg=new Set(["number","string_set"]),Pg=new Set(["string","number","boolean"]);function vl(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Mg(e,t,r){let n=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=G(n,r);if(!Dg.has(String(o.value_type)))throw new TypeError(`${n}.value_type must be number or string_set`);if(H(`${n}.description`,o.description),o.parameters===void 0)return;let i=G(`${n}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${n}.parameters.${s}`;vl(`${c}.name`,s);let d=G(c,a);if(!Pg.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);Z(`${c}.required`,d.required),H(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function El(e){let t=G("registerAssuranceMeasurementProvider provider",e),r=vl("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(!Ng.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=G("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`);Mg(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 $g=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function uo(e,t){return Br(e,t).map(r=>(r.repeatable===!0&&(r.list=!0),r))}function jg(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function vs(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=jg(t);if(r.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return r}function Es(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=G(`registerCommand definition.arguments[${n}]`,o),s=ee(`registerCommand definition.arguments[${n}].name`,i.name);if(Z(`registerCommand definition.arguments[${n}].required`,i.required),Z(`registerCommand definition.arguments[${n}].variadic`,i.variadic),H(`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 fo(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=G(`registerFlags flags[${t}]`,r),o=Object.keys(n).filter(c=>!$g.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`);H(`registerFlags flags[${t}].long`,i),H(`registerFlags flags[${t}].short`,s);let a=Pd(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${Md(a.token,a.failure)}`);if(H(`registerFlags flags[${t}].value_name`,n.value_name),H(`registerFlags flags[${t}].description`,n.description),Z(`registerFlags flags[${t}].required`,n.required),Z(`registerFlags flags[${t}].enabled`,n.enabled),Z(`registerFlags flags[${t}].visible`,n.visible),Z(`registerFlags flags[${t}].list`,n.list),Z(`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(Gd(`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.`);kl(`registerFlags flags[${t}]`,n),Lg(`registerFlags flags[${t}]`,n)}}function Lg(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:so(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 kl(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=so(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?jd(t.default):[t.default];for(let[i,s]of o.entries())if(!Ld(s,n)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${n}.`)}}function Sl(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=G(`registerItemFields fields[${t}]`,r);ee(`registerItemFields fields[${t}].name`,n.name);let o=ee(`registerItemFields fields[${t}].type`,n.type);if(_l(o)===null){let i=yl(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${lo.join(", ")}).${s}`)}Z(`registerItemFields fields[${t}].optional`,n.optional)}}function Fg(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=G(i,o);ee(`${i}.command`,s.command),ee(`${i}.option`,s.option),Z(`${i}.enabled`,s.enabled),Z(`${i}.required`,s.required),Z(`${i}.visible`,s.visible)}}function zg(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=G(i,o);ee(`${i}.key`,s.key),yt(`${i}.values`,s.values),Z(`${i}.required`,s.required),yt(`${i}.aliases`,s.aliases)}}function Ol(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=G(n,r);ee(`${n}.name`,o.name),H(`${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),Fg(t,o.command_option_policies),zg(t,o.options)}}function Al(e){let t=G("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(Z("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 Il=["types","statuses","fields","workflows","config","templates","packages"],Ug={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 Tl(e){let t=G("registerProfile profile",e);if(ee("registerProfile profile.name",t.name),ee("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 Il){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`);Ug[r]?.(`registerProfile profile.${r}[${o}]`,i)}}}}function Cl(e){e.summary===void 0&&(e.summary="");for(let t of Il)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 Rl(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 xl(e){return typeof e=="string"?e:String(e)}function Kr(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 ks(e,t){let r=Kr(e),n=Kr(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 Nl(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let r=xl(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:r,current:t};if(!Kr(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=ks(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 Dl(e,t,r){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let n=xl(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())||!Kr(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=ks(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]="187f03b7-1a62-500c-9ebf-4d5a053afa74")}catch{}})();var Pl=null,qg=Object.freeze(Wc()),Ml=0;function Vg(e=Date.now()){return Ml+=1,`${Ml}-${e}`}function Bg(e,t,r){return r.has(e)?!1:t.size===0?!0:t.has(e)}async function Wg(e,t){let[r,n]=await Promise.all([wt.realpath(e),wt.realpath(t)]);return fs(r,n)}function Gg(e,t=process.cwd()){return{global:bt.join(gd(t),"extensions"),project:bt.join(e,"extensions")}}async function Kg(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 Yg(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 $l(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function Xg(e){let t=new Map;try{let r=JSON.parse(await wt.readFile(bt.join(e,".managed-extensions.json"),"utf8")),n=Ue(r)?.entries;if(!Array.isArray(n))return t;for(let o of n){if(typeof o!="object"||o===null)continue;let i=o,s=$l(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>$l(l)).filter(l=>l!==void 0),c=oo(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 jl(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 Jg(e,t){let r=[...jl(e),...jl(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 Ll(e,t,r,n,o){let i=[],s=[],a=[],c=await Kg(t),d=await Xg(t);for(let l of c){let u=await eb(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 Zg(){return{diagnostics:[],warnings:[],candidates:[]}}function Fl(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 Qg(e,t,r,n,o,i,s){let a=Rd(e,t,r);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&a.push(Cd(e,t.name,t.legacy_capability_aliases));for(let c of Ad(t.capabilities))a.push(Td(e,t.name,c));return n?o||a.push(`extension_entry_missing:${e}:${t.name}`):a.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&a.push(i.warning),s.warning&&a.push(s.warning),a}async function eb(e,t,r,n,o,i,s){let a=bt.join(t,r),c=bt.join(a,"manifest.json");if(!await ft(c))return Fl(e,r,c,`extension_manifest_missing:${e}:${r}`);let d,l;try{let ke=JSON.parse(await wt.readFile(c,"utf8"));l=Ue(ke),d=gs(ke)}catch{l=null,d=null}if(!d||!l)return Fl(e,r,c,`extension_manifest_invalid:${e}:${r}`);let u=bt.resolve(a,d.entry),f=fs(a,u),m=f?await ft(u):!1,_=f&&m?await Wg(a,u):f,y=Bg(d.name,n,o),w=await nb(e,d),v=await ob(e,d,s),C=Qg(e,d,l,_,m,w,v),K=_&&m&&w.allowed&&v.allowed,Ee=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:K?"ok":"warn"},warnings:C,candidate:Jd({layer:e,directory:r,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:Ee,extensionReady:K,enabledForLoad:y})}}async function tb(e){let t=Gg(e.pmRoot,e.cwd??process.cwd()),r=$r(e.settings.extensions.enabled),n=$r(e.settings.extensions.disabled),o=rl(e.settings),i=nl(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?Zg():await Ll("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Ll("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=Jg(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=sl(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let w of m.manifest.capabilities){let v=al(o,_,w);v.warning&&l.push(v.warning)}f.push(Yg(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 mo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function rb(){try{let e=Hn(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 Hl(){return Pl??=rb(),Pl}function ql(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 nb(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let r=Nl(t.pm_min_version,await Hl()),n=ql(e,t,r);return n?{allowed:r.allowed,warning:n}:{allowed:r.allowed}}async function ob(e,t,r){if(t.pm_max_version===void 0)return{allowed:!0};let n=Dl(t.pm_max_version,await Hl(),r),o=ql(e,t,n);return o?{allowed:n.allowed,warning:o}:{allowed:n.allowed}}async function zl(e){try{let t=await wt.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function ib(e,t){let r=e.entry_path;t.module_graph_snapshot_root&&(r=await fl(t.module_graph_snapshot_root,e));let n=new URL(Hg(r).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return n.href;let[o,i]=await Promise.all([zl(e.entry_path),zl(e.manifest_path)]),s=t.reload_token??Vg();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 Rx(e){let t=await tb(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 ib(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:mo(a)})}return{...t,warnings:o,loaded:r,failed:n}}var Ul=5e3,sb=2147483647;function ab(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 Vl(e){let t=rd(e);return t?ab(t):null}async function xx(e,t,r={}){let n=cb(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=Vl(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 db(u,n),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:mo(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 cb(e){return typeof e!="number"||e<0?Ul:e===0||e===1/0?0:Number.isFinite(e)?Math.min(sb,Math.max(1,Math.floor(e))):Ul}async function db(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 lb(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let r of e.capabilities){let n=r.trim().toLowerCase();qe(n)&&t.add(n)}return t}function z(e,t,r){let n=lb(e);if(n!==null&&!n.has(t))throw De(`${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 ub(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>Re.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function fb(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 Ss=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=ub(t),this.#r=fb(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=cl(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:Hr(o),hint:i}}registerCommandOverride(t,r){let n=F(t);if(n.length===0)throw De("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 De(`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 De("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 De("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 De("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 De(`registerCommand requires a command definition run handler (command="${r}", registration_index=${o.registration_index})`,o)}try{Kd(t);let o=vs(r,t.action),i=Yd(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=Fr("registerCommand definition.examples",t.examples),d=Fr("registerCommand definition.failure_hints",t.failure_hints),l=Es(t.arguments);t.flags!==void 0&&(z(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(fo(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:uo("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=mo(o),s=this.registerCommandTrace("definition",r,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=De(`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(z(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,r);return}this.registerCommandDefinition(t)}registerParser(t,r){if(z(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let n=F(ee("registerParser command",t));Wr("registerParser override",r),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerPreflight(t){if(z(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let r=ml(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...r})}registerService(t,r,n={}){z(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!gl(o))throw new TypeError(`registerService service must be one of: ${qt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(Wr("registerService override",r),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:r,...Rl(n)?{passThrough:!0}:{}}))}registerRenderer(t,r,n={}){if(z(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(!hl(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(z(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let n=F(ee("registerFlags targetCommand",t));fo(r);let o=uo("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(z(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Sl(t);let r=Br("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(z(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Ol(t);let r=Br("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(z(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=$i();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(z(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Al(t);let r=Vr("registerMigration definition",t);this.#t.migrations.push(Gr({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerMigration definition",t)},r))}registerProfile(t){if(z(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let r=qr(t);Tl(r),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Cl(r)})}registerImportExportCommandFlags(t,r,n){n.flags!==void 0&&(z(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(fo(n.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:uo(`${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=Xd(t,s,n?.description!==void 0);H(`${t} options.action`,s.action),H(`${t} options.description`,s.description),H(`${t} options.intent`,s.intent);let c=vs(r,s.action),d=Fr(`${t} options.examples`,s.examples),l=Fr(`${t} options.failure_hints`,s.failure_hints),u=Es(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(z(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=bs(ee("registerImporter name",t));Wr("registerImporter importer",r);let i=ws(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(ps(s,o,"import"))})}registerExporter(t,r,n){if(z(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=bs(ee("registerExporter name",t));Wr("registerExporter exporter",r);let i=ws(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(ps(a,o,"export"));return s?.receipt==="suppress"&&!Un(c)?Qc(c):c}})}registerSearchProvider(t){if(z(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let r=Vr("registerSearchProvider provider",t);this.#t.search_providers.push(Gr({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerSearchProvider provider",t)},r))}registerVectorStoreAdapter(t){if(z(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let r=Vr("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(Gr({layer:this.#e.layer,name:this.#e.name,definition:Zt("registerVectorStoreAdapter adapter",t)},r))}registerAssuranceMeasurementProvider(t){if(z(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(El(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let r=Vr("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(Gr({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:Zt("registerAssuranceMeasurementProvider provider",t)},r))}registerBeforeCommand(t){z(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){z(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){z(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){z(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){z(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){z(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 mb(e,t,r,n,o,i,s,a,c,d,l){return new Ss(e,t,r,n,o,i,s,a,c,d,l)}function pb(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 _b(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 yb(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 hb(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 gb=new Set(["output_format"]);function bb(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||gb.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 Nx(e){let t=ol(e.policy??qg),r=jr(),n=Gi(),o=Ki(),i=Yi(),s=Xi(),a=Ji(),c=Zi(),d=[],l=[];for(let m of e.loaded){let _=Vl(m.module);if(!_)continue;let y=d.length,w=Wd({hooks:r,commands:n,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(mb(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 C=wl(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:mo(v),trace:C})}}let u=[..._b(n),...hb(o),...pl(i),...bb(s),...yb(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:pb(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 $x(e){return{...e,hooks:jr(),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 Lx(){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 wb(){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 vb={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"]},Bl=":";function Wl(e,t){return`${e}${Bl}${Os(t)}`}function Eb(e){return e.slice(e.indexOf(Bl)+1)}function Os(e){return e.trim().toLowerCase()}function kb(e){if(!Array.isArray(e))return[];let t=new Set;for(let r of e){let n=Od(r);n!==null&&t.add(n)}return[...t].sort((r,n)=>r.localeCompare(n))}function Gl(e){let t=new Map,r=(l,u)=>{for(let f of l){let m=Wl(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 Sb(e,t={}){let r=Gl(e),n=new Set;t.extensionName!==void 0&&n.add(Os(t.extensionName));for(let i of t.extensionNames??[])n.add(Os(i));let o=new Set;for(let[i,s]of r)if(!(n.size>0&&!n.has(Eb(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function Ob(e,t){let r=Gl(t),n=[];for(let o of e){let i=kb(o.capabilities);if(i.length===0)continue;let s=r.get(Wl(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 Ab}from"node:fs";import{AsyncLocalStorage as Ib}from"node:async_hooks";import Pe 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 Me=null,Qt=null,Yr=null,Xr=null,er=null,Jr=null,Zr=null,We=null,_o,po=[],Yl=new Ib;function M(){return Yl.getStore()}function Wx(e){return Yl.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var Tb=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Kl(e){let t=Pe.resolve(e);for(;;){if(Ab(Pe.join(t,".git")))return t;let r=Pe.dirname(t);if(r===t)return;t=r}}function yo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),r=Kl(t)??Pe.resolve(t),n=Kl(r);if(!e)return{source_workspace_root:r,...n?{repo_root:n}:{}};let o=Pe.relative(r,Pe.resolve(e)),i=o.length>0&&!o.startsWith(`..${Pe.sep}`)&&o!==".."&&!Pe.isAbsolute(o);return{source_workspace_root:r,...n?{repo_root:n}:{},...i?{pm_root_rel:o.split(Pe.sep).join("/")}:{}}}function Gx(e){let t=M();if(t){t.hooks=e;return}Me=e}function Kx(e){let t=M();if(t){t.commands=e;return}Qt=e}function Yx(e){let t=M();if(t){t.parsers=e;return}Yr=e}function Xx(e){let t=M();if(t){t.preflight=e;return}Xr=e}function Jx(e){let t=M();if(t){t.services=e;return}er=e}function Zx(e){let t=M();if(t){t.renderers=e;return}Jr=e}function Qx(e){let t=M();if(t){t.registrations=e;return}Zr=e}function Xl(){let e=M();return e?e.registrations:Zr}function eN(){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}Me=null,Qt=null,Yr=null,Xr=null,er=null,Jr=null,Zr=null,We=null,_o=null}function tN(e){let t=e?{...e,...yo(e.pm_root)}:null,r=M();if(r){r.commandContext=t;return}We=t}function Jl(){let e=M(),t=e?e.commandContext:We;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function rN(e){let t=M()??{commandContext:We,hooks:Me,commands:Qt,parsers:Yr,preflight:Xr,services:er,renderers:Jr,registrations:Zr};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 ho(e){let t=M();if(t){t.commandResult=e;return}_o=e}function nN(){let e=M();return e?e.commandResult:_o}function oN(e){if(!e)return;let t=M();t?t.affectedItems.push(e):po.push(e)}function iN(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"||Tb.has(i)||Object.hasOwn(n,i)&&n[i]!==void 0&&(r[i]=n[i])}return r}function sN(){let e=M(),t=e?.affectedItems??po;if(t.length===0)return;let r=t;return e?e.affectedItems=[]:po=[],r}function aN(){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}Me=null,Qt=null,Yr=null,Xr=null,er=null,Jr=null,Zr=null,We=null,_o=void 0,po=[]}async function go(e){let t=M(),r=t?t.hooks:Me;return r?rs(r,e):[]}async function cN(e){let t=M(),r=t?t.hooks:Me;r&&await ts(r,e)}async function tr(e){let t=M(),r=t?t.hooks:Me;return r?ns(r,e):[]}function dN(){let e=M();return((e?e.hooks:Me)?.onRead?.length??0)>0}async function lN(e){let t=M(),r=t?t.hooks:Me;return r?os(r,e):[]}function Zl(e){let t=M(),r=t?t.commands:Qt,n=t?t.commandContext:We;return!r||!n?{overridden:!1,result:e,warnings:[]}:ls(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 uN(e){let t=M(),r=t?t.commands:Qt;return r?is(r,{...e,...yo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function fN(e){let t=M(),r=t?t.parsers:Yr;return r?ss(r,{...e,...yo(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 mN(e){let t=M(),r=t?t.preflight:Xr;return r?as(r,{...e,...yo(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 Ql(e,t){let r=M(),n=r?r.renderers:Jr,o=r?r.commandContext:We;return n?us(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 eu(e,t){let r=M(),n=r?r.commandContext:We;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 rr(e,t){let r=M(),n=r?r.services:er;return n?ds(n,eu(e,t)):{handled:!1,result:t,warnings:[]}}function As(e,t){let r=M(),n=r?r.services:er;return n?cs(n,eu(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 Cb(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ge(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 bN(e){return Cb(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function wN(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 nu=new WeakMap;function SN(e,t){nu.set(e,new Set(t))}var bo='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',Rb={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"}},xb=[{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 ON(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 AN(e,t){let r=xb.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 Nb=[{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 te(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Db=new Set([void 0,"tabular_when_uniform"]),Pb=new Set(["collection","none"]),Mb=new Set(["supported","unsupported"]);function tu(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 $b(e){return te(e)&&typeof e.command=="string"&&e.command.trim().length>0&&Pb.has(e.row_kind)&&tu(e.row_keys,!0)&&(e.continuation_row_keys===void 0||tu(e.continuation_row_keys,!1))&&Mb.has(e.fields)&&Db.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 jb={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"]},Lb={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 Fb(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=jb[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||te(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:bo}:{},toon_encoding:"tabular_when_uniform"}}let o=Rb[n],i=Lb[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)=>te(d)?d[l]:void 0,t);return Array.isArray(c)||te(c)});return{command:n,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:bo}:{},toon_encoding:"tabular_when_uniform"}})()}function zb(e){if(!te(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=>te(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 Ub(e){if(!Array.isArray(e.sections_included))return;let t=Ae(Nb,new Set(e.sections_included.filter(r=>typeof r=="string")));return te(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function Hb(e,t,r){return e==="dependency_provenance"?!1:Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&te(r.schedule)&&Object.hasOwn(r.schedule,e)||["files","tests","docs"].includes(e)&&te(r.linked)&&Array.isArray(r.linked[e])&&r.linked[e].length>0}function qb(e){if(!te(e.item))return;let t=e.item,r=["comments","notes","learnings","files","tests","docs","reminders","events"],n=["body","children","claim_state","linked","schedule"],o=nu.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})=>Hb(a,i(a),e)?[a]:[])))}function ru(e){if(te(e.projection))return Ae([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Vb(e){if(!te(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 Bb(e){if(!(!te(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 Wb(e,t){let r=zb(t);if(r!==void 0)return r;let[n]=e.split(/\s+/u,1);if(n==="context")return Ub(t);if(n==="get")return qb(t);if(n==="list"||n.startsWith("list-"))return ru(t);if(n==="search")return ru(t)??Ae([{name:"projection_metadata",restore_with:"--full"}]);if(n==="health")return Vb(t);if(n==="contracts")return Bb(t)}function ou(e,t){if(e===void 0||!te(t))return t;let r=Wb(e,t),n=t.row_contract,o=$b(n)?n:Fb(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 te(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 iu=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)}"`},su=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?iu(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,nr=(e,t=process.platform)=>{let r=e.map(n=>su(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 au=new Set(["--pm-path","--path","--author","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),Gb=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function Kb(e){let t=e.indexOf("=");return t>0&&au.has(e.slice(0,t))}function Yb(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function wo(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(r==="--")return;if(au.has(r)){t+=Yb(r,e[t+1])?1:0;continue}if(!(Kb(r)||Gb.has(r)||r==="--profile"||r==="--id-only"||r==="--explain")&&!r.startsWith("-"))return t}}function CN(e){let t=wo(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 Xb=new Set(["--literal","--regex","--replacement"]);function Jb(e){let t=wo(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=wo(r);return n!==void 0&&r[n]==="redact"}function DN(e){if(!Jb(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(!Xb.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 Zb=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 X(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function cu(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(!X(r))return;r=r[n]}return r}function Is(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 du(e,t,r){let n=or(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=Is(e,t,o);return X(i.summary)&&X(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)}}),tn(i),i}function Eo(e){let t=e.row_contract;return X(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 Qb(e){let t=e.row_contract;return X(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(r=>typeof r=="string"&&r.trim().length>0):Eo(e)}function Ke(e){return Eo(e).flatMap(t=>{let r=cu(e,t);return Array.isArray(r)||X(r)?[{path:t,value:r}]:[]})}function or(e){return Qb(e).flatMap(t=>{let r=cu(e,t);return Array.isArray(r)||X(r)?[{path:t,value:r}]:[]})}function Qr(e){let t=Ke(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(X(o))for(let[s,a]of Object.entries(o))i.length===0&&Zb.has(s)||n(a,i.length===0?s:`${i}.${s}`)};return n(e,""),t}function ko(e){return Ke(e).reduce((t,r)=>t+(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length),0)}function en(e,t){let r=e;for(let n of Ke(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=Is(r,n.path,o)}return r}function lu(e,t){let r=e,n=!1;for(let o of Ke(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=Is(r,o.path,s)}return{result:r,truncated:n}}var uu=["high_level","low_level","blocked_fallback"];function vo(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function MN(e,t){if(!X(e.summary)||!X(e.summary.returned_focus))return;let r=new Map(t.map(n=>[n.id,n]));e.summary={...e.summary,focus_row_states:Object.fromEntries(uu.map(n=>[n,Array.isArray(e[n])?e[n].filter(X).map(o=>vo(r.get(o.id)??o)).join(""):""]))}}function ew(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 tw(e,t,r,n){let o=Array.isArray(t[r])?t[r].filter(X):[],i=ew(n[r],o.length)??o.map(vo).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[r])?e[r].filter(X):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??vo(d);return u!==vo(d)&&(c=!0),u}).join(""),needsStates:c}}function rw(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 tn(e,t=e){if(rw(e,t),!X(e.summary)||!X(e.summary.returned_focus))return;let r={...e.summary},n=X(t.summary)&&X(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=uu.map(c=>({key:c,...tw(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]="9bdf8ad1-8d1e-5e3e-a23a-ba1d4293402b")}catch{}})();var So="changed_fields",nw="changed_field_count",Ts="rows",ow=new Set(["apply","rollback"]),_u=new Set(["deleted","would_delete"]),fu=256,mu={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function iw(e,t){if(!re(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let r=Object.hasOwn(mu,e.action)?mu[e.action]:void 0;if(!r||!r.every(i=>{let s=e[i];return re(s)&&re(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=hu(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,rn(e[i],t)]))}}function pu(e){return typeof e!="string"||e.length<=fu?e:`${Ge(e,fu-1)}\u2026`}function sw(e){if(!re(e))return null;let t={...e};return t.reason=pu(t.reason),re(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([r,n])=>[r,pu(n)]))),t}function re(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function yu(e){let t=e[So];if(!Array.isArray(t))return null;let r=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[n,o]of Object.entries(e))n!==So&&(r[n]=o);return r[nw]=t.length,r}function aw(e){return"item"in e&&Array.isArray(e[So])}function cw(e){return typeof e.mode=="string"&&ow.has(e.mode)&&Array.isArray(e[Ts])}function dw(e,t){let r=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(r,e),r[Ts]=t,r}function hu(e){if(!re(e))return null;let t=re(e.item)?e.item:re(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"&&_u.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 lw(e,t){if(!re(e))return null;if(re(e.plan)&&re(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||!re(e.item)||typeof e.item.id!="string")return null;let r=e[So];if(!Array.isArray(r))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&_u.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 uw(e,e.item,n),n}function uw(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=sw(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"])re(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 fw(e){let t=cw(e)?e[Ts]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let r=!1,n=t.map(o=>{if(!re(o))return o;let i=yu(o);return i?(r=!0,i):o});return r?{projected:dw(e,n),changed:!0}:{projected:e,changed:!1}}function rn(e,t={}){let r=iw(e,t);if(r!==null)return r;if(t.idOnly===!0){let a=hu(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=lw(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!re(e))return e;let n=!1,o=e,i=aw(e)?yu(e):null;i!==null&&(o=i,n=!0);let s=fw(o);return s.changed&&(o=s.projected,n=!0),n?o:e}import{AsyncLocalStorage as TE}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 Cs(e){let t=e.trim().toLowerCase().startsWith("extension:"),r=e.trim().toLowerCase().replace(/^extension:/u,"");if(Yt(r))return;let n=Xl()?.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||Yt(i.command)||Yt(i.action)?void 0:i}function mw(e){let t=Cs(e);return t?.read_output===void 0?void 0:t}function gu(e,t){let r=mw(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:bo}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as Ev}from"node:crypto";import{createHash as hv}from"node:crypto";import{stripVTControlCharacters as pw}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]="c8a91fc2-57b4-5738-9428-9847ef7afadc")}catch{}})();var _w=["full","compact","brief","summary","counts"],YN=["mutation","read","discovery","governance"],wu=["error","warning","validation_summary","recovery_bundle"],yw=["full","omit_explanation","limit_collections","compact_recovery","action_only"],hw=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"]),gw=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),bw=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),ww={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},vw=3,Ew=2,kw=192,Sw={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Ow=wu.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:Sw[e],minimum_max_estimated_tokens:kw,degradation_ladder:yw,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),Aw=new Map(Ow.map(e=>[e.diagnostic_class,e]));function Iw(e){let[t=""]=Rr(e).split(/\s+/u);return hw.has(t)?"mutation":gw.has(t)?"discovery":bw.has(t)?"governance":"read"}function vu(e,t=Iw(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=ww[t];return Tw({command:r,budget_class:t,default_max_estimated_tokens:n,default_max_estimated_tokens_by_format:{toon:n,json:Math.ceil(n*vw/Ew)},degradation_ladder:_w,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Tw(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 Cw=to.map(e=>vu(e)),Rw=new Map(Cw.map(e=>[e.command,e]));function Eu(e,t={}){let r=e.trim().replace(/\s+/gu," "),[n]=Rr(r).split(" "),o=Rw.get(n);return o?{...o,command:r}:t.generateFallback?vu(r):null}function Et(e){return Math.ceil(Math.max(0,e)/4)}function ku(e){let t=Aw.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${wu.join(", ")}`);return t}function Ye(e){return Et(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function xw(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rs(e){if(!xw(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"]){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 Nw(e,t){return typeof e!="string"||e.length<=t?e:`${Ge(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 Su(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 Dw=new Set(["limit_collections","compact_recovery","action_only"]),Pw=new Set(["compact_recovery","action_only"]);function Mw(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:Nw(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},r=Rs(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 $w(e,t){let r=structuredClone(e);if(t!=="full"&&(delete r.why,delete r.examples),Dw.has(t))for(let[n,o]of Object.entries(r))Array.isArray(o)&&(r[n]=o.slice(0,3));if(Pw.has(t)){let n=Rs(r.recovery);n?r.recovery=n:delete r.recovery}return t!=="action_only"?Su(r):Mw(r)}function ir(e,t){let r={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let n=0;n<4;n+=1){let o=Ye(r),i=r.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return r}function jw(e,t,r){let n=ir(e,t);for(let i of["recovery","exit_code"])Ye(n)<=r||e[i]===void 0||(delete e[i],n=ir(e,t));let o=40;for(;Ye(n)>r&&o>4;)o-=4,e.code=vt(String(e.code),o),e.required=vt(String(e.required),o),n=ir(e,t);return n}function Lw(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=Rs(e.recovery),c=a&&Ye(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=ir(d,s);for(;Ye(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=ir(d,s);return l=jw(d,s,t),l}function XN(e,t={}){let r=e,n=t.diagnosticClass??"error",o=ku(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=Ye(r),c=Object.keys(r);if(a<=s)return Su(structuredClone(r));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=$w(r,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=ir(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=_,Ye(_)<=s)break}return Ye(d)>s&&(d=Lw(d,s)),d}function bu(e){return pw(e).replace(/\r\n/gu,`
|
|
2
|
-
`).replace(/[^\P{Cc}\n]/gu," ")}function JN(e,t,r={}){let n=r.diagnosticClass??"error",o=ku(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=bu(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=bu(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]="f7d00f9c-6e95-5426-971d-9b30e2ec1652")}catch{}})();var xs=256,Ns=1e4,Fw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,Ou=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,zw=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),Uw=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&Fw.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=xs,reason:`token_budget must be a safe integer of at least ${xs}.`},{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<=Ns&&e.seen_item_ids.every(t=>typeof t=="string"&&Ou.test(t)),reason:`seen_item_ids must contain at most ${Ns} portable item identifiers.`}];function Ao(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Oo(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function Io(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{Oo("must be a valid JSON object.")}Ao(t)||Oo("must be a JSON object.");let r=Object.keys(t).filter(i=>!zw.has(i));r.length>0&&Oo(`contains unknown field "${r.sort()[0]}".`);let n=Uw.find(i=>!i.valid(t));n!==void 0&&Oo(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 Au(e){if(Ao(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Ao(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function Hw(e){let t=new Set,r=0,n=Ke(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(!Ao(c))continue;if(typeof c.context_ref=="string"){r+=1;continue}let d=Au(c);d!==void 0&&Ou.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:r}}function Iu(e,t){let r=new Set(t.seen_item_ids);return en(e,n=>{let o=Au(n);return o!==void 0&&r.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:n})}function Ds(e,t,r){let{deliveredIds:n,suppressedRepeatCount:o}=Hw(e),i=new Set(t.seen_item_ids),s=[...n].filter(y=>!i.has(y)).sort(),a=s.slice(0,Ns-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> --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<xs,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let w=nn(u,r);if(w===m)return u;_=Math.max(_,w),m=w}return f(_),u}function Tu(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 on=Symbol.for("pm.readOutputInvocationProvenance");function oD(e,t){return Reflect.set(e,on,{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]="d8782989-f417-515e-892a-17ae8ff2b5fa")}catch{}})();var kt=["include","amount","cost","encoding"],$u=["canonical","legacy","intent","default"],an=ro,vD=Object.freeze(kt.map(e=>an[e])),ED=no,ju={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"],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:{}},Lu=new Set(["--collapse","--fields","--section"]),Ms=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 $s(e){return e.slice(2).replaceAll("-","_")}function qw(e,t){let r=Ms[e];if(r!==void 0)return r;let n=t==="include"?Lu.has(e)?"<csv>":$s(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${an[t]} ${n}.`}function Fu(e){let t=ju[e]??{},r=Object.freeze(Object.fromEntries(kt.map(n=>[n,Object.freeze({dimension:n,canonical_option:an[n],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[n]??[]).map(o=>Object.freeze({flag:o,semantics:Ms[o]===void 0?"replacement":"behavior_preserving",migration_hint:qw(o,n),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:r,precedence:$u,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...Uu(e).keys()])})}var Vw=Object.freeze(Kt.map(Fu)),Bw=new Map(Vw.map(e=>[e.command,e]));function cr(e,t={}){let r=Rr(e.trim().toLowerCase()),n=Cs(r);return n!==void 0?n.read_output===void 0?void 0:`extension:${n.command}`:Ww(r,t)}function Ww(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 Kt.includes(n)?n:void 0}var Gw=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],Kw={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 Yw(e){return Gw.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var Xw=[{keys:["outputInclude","output_include"],valid:e=>sn(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||ar(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||ar(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(Io(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 kD(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(!Yw(t))return;let n=cr(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((Kw[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 Xw){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 zu(e){let t=cr(e);return t?Uu(t):new Map}function Uu(e){return new Map((ju[e]?.include??[]).filter(t=>!Lu.has(t)&&Ms[t]===void 0).map(t=>[$s(t),Hu(t)]))}function Jw(e,t,r){let n=sn(t)??[],o=zu(e),i=[],s=[],a=r,c=a[on],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("_","-")}`;Ls(js(r,y))&&l.add(y),r[_]=!0,s.push(m),d.add(m)}let u=cr(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(r.fields=[...new Set([...sn(r.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[on]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function SD(e,t){let r=t.outputInclude??t.output_include;if(r===void 0)return;let{selectors:n,modes:o}=Jw(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 Hu(e){return e.slice(2).replace(/-([a-z])/gu,(t,r)=>r.toUpperCase())}function js(e,t){let r=Hu(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 Ls(e){return e!==void 0&&e!==!1&&e!==null}function sn(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 ar(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 Zw(e,t,r,n){for(let o of e.legacy_aliases){if(n(o.flag))continue;let i=js(t,o.flag),s={value:i,flag:o.flag};if(Ls(i)&&r(s))return s}}function Cu(e,t){let r=sn(e);if(r)return{source:"canonical",value:r};if(t)return{source:"legacy",value:sn(t.value)??[$s(t.flag)]}}function Ru(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=ar(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=ar(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function xu(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let r=ar(e);if(r!==void 0)return{source:"canonical",value:r};if(!t)return;let n=ar(t.value);return n===void 0?void 0:{source:"legacy",value:n}}function Nu(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 qu(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 Qw(e,t,r,n){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||Ls(js(n,"--no-truncate"))&&!qu(r,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||r?.canonical_include_modes.includes("full")===!0}function ev(e,t){return kt.flatMap(r=>e[r]?.source==="canonical"||r==="include"&&(t?.canonical_include_modes.length??0)>0?[an[r]]:[])}function Vu(e,t){let r=cr(e,t);if(!r)return;let n=Bw.get(r)??Fu(r),o=t[on],i={include:v=>Cu(void 0,v),amount:v=>Ru(void 0,v),cost:v=>xu(void 0,v),encoding:v=>Nu(void 0,v)},s=Object.fromEntries(kt.map(v=>[v,Zw(n.dimensions[v],t,C=>i[v](C)!==void 0,C=>qu(o,v,C))])),a=kt.flatMap(v=>{let C=s[v];return C?[C.flag]:[]}),c=kt.flatMap(v=>{let C=s[v];return C?[n.dimensions[v].legacy_aliases.find(K=>K.flag===C.flag).migration_hint]:[]}),d=Nu(t.outputFormat??t.output_format,s.encoding),l=Cu(t.outputInclude??t.output_include,s.include),u=Ru(t.outputLimit??t.output_limit,s.amount),f=xu(t.outputBudget??t.output_budget,s.cost),m=Qw(e,s,o,t),_=Eu(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:ev({include:l,amount:u,cost:w,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:$u}}function Q(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Fs=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"]),tv=["collection_counts","notes_count","tests_count"];function Bu(e,t){let r=new Set(t.map(n=>n.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([n])=>r.has(n)))}function rv(e){let t=Q(e.item)?e.item:{},r=[...new Set([...Object.keys(t),...tv.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),n=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Fs.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 nv(e,t){let r=rv(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])=>Fs.has(l)||s.has(l)));o?a.item=r.item:i.length>0&&(a.item=Bu(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=[...Q(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 Du(e){let t=0;return en({...e},r=>(Q(r)&&Object.keys(r).length>0&&(t+=1),r)),t}function ov(e,t,r,n){if(Du(t)===0||Du(r)>0)return;let o=[...zu(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 iv(e,t,r){if(e==="get")return nv(t,r);let n=Eo(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=en(s,d=>Q(d)?Bu(d,a):d);return ov(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>r.some(a=>a.split(".")[0]===s)||Fs.has(s)))}function sv(e,t){if(t==="unbounded")return e;let{result:r,truncated:n}=lu(e,t);if(!n)return r;if(r.has_more=!0,r.truncated=!0,typeof r.count=="number"){let o=Q(r.projection)?r.projection.row_key:void 0;r.count=typeof o=="string"&&Array.isArray(r[o])?r[o].length:ko(r)}return r.applied_bound={kind:"output_limit",source:"explicit",value:t},r}function av(e){return kt.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(an[t]))}function Wu(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}function To(e,t,r,n){let o=Ds(e,t,n);sr(e,o);for(let i=0;i<8;i+=1){let s=r.estimated_tokens,a=o.read_session.spent_this_call_tokens;Xe(o,r,n);let c=o;o=Ds(o,t,n),sr(c,o);let d=o.read_session.spent_this_call_tokens;if(r.estimated_tokens===s&&d===a)return o}return o}function zs(e,t){if(!Q(e.read_output))return e;let r=Wu(t),n=e.read_output,o=Io(t.outputSession??t.output_session);return o===void 0?(Xe(e,n,r),e):To(e,o,n,r)}function cv(e,t){if(e!=="validate")return t;let r=Q(t.projection)?t.projection:void 0;if(!(Array.isArray(r?.declared_field_groups)?r.declared_field_groups:[]).some(l=>Q(l)&&l.name==="diagnostic_rows"))return t;let n=[...new Set(Qr(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=Q(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 dv(e,t,r,n,o){let i={...e};if(t.include?.source==="canonical"&&(i=iv(t.command,i,t.include.value)),t.command==="assurance"&&(i=tf(i)),tn(i,e),i=rf(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)),Q(i.projection)&&(i.projection={...i.projection,row_key:n.path}),Q(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=_v(i,e,t.command,n,o);return t.amount?.source==="canonical"&&(i=sv(i,t.amount.value),a.cursorContinuesExistingPage&&Xu(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),tn(i,s),{projected:r===void 0?i:Iu(i,r),continuationState:a}}function lv(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:Tu(t)}]].sort((r,n)=>r.tokens-n.tokens)[0]}function Gu(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function Ku(e,t){return Q(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function Yu(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!Ku(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function uv(e,t,r,n,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...Yu(n),precedence:e.precedence,...Gu(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:To(a,r,s,i);if(r===void 0&&Xe(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 fv(e,t,r){return e.command==="context"&&e.cost?.source==="legacy"&&!Ku(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 mv(e,t,r,n,o){if(t!==void 0||fv(e,o,r))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(Ke(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"||nn(o.outputRowContract===!1?Object.fromEntries(Object.entries(r).filter(([i])=>i!=="row_contract")):r,n)<=e.cost.value}function pv(e,t,r,n,o,i,s){if(!r.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(or(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:Us({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=Ps({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 Xu(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=Hs(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=dn(a.fingerprint,l,u,a.snapshot),!0)}function _v(e,t,r,n,o){let i=new Map(or(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:Co(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 yv(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=>Q(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 Qr(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return Mu(e,o,i.tokens,f,d,m=>{tn(m,l);let _=Xu(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(pv(m,n,o,i,_,c,a.collectionsBeforeBudget),n.command==="history"&&Q(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,To(m,s,o,d))},n.command==="history"&&Array.isArray(e.diff))}function Ju(e,t,r){let n=Vu(e,t);if(!n)return r;let o=Wu(t),i=Io(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?cn(s):void 0,c=av(n),d=cv(n.command,r);if(a===void 0&&mv(n,i,d,o,t))return d;let l=lv(n,i),u=dv(d,n,i,a,t),f=u.projected;sr(f,f,t.outputRowContract===!1);let m={contract_version:1,command:n.command,requested_dimensions:c,...Yu(l,f),precedence:n.precedence,...Gu(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:To(f,i,m,o),Xe(f,m,o),l!==void 0&&m.estimated_tokens>l.tokens){let _=Pu(n.command,t,f);_!==void 0&&(m.applied_depth="brief",m.degradation_reason="output_budget_reached",sr(f,_),f=zs(_,t)),m.estimated_tokens>l.tokens&&(f=yv(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?uv(n,c,i,l,m.estimated_tokens,o):f}function Zu(e){return Q(e)&&Q(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function Qu(e,t){let r=t.outputFormat??t.output_format;if(r==="json"||r==="toon")return r;let n=Vu(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 gv=4096,bv=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"]),ef=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:bv}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function un(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ln(e){return Array.isArray(e)?e.map(ln):un(e)?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ln(r)])):e}function nf(e,t){if(!un(e))return ln(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||!un(i)?[o,ln(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!n.includes(s)).map(([s,a])=>[s,ln(a)]))]))}function wv(e,t){return Array.isArray(e)?e.map(r=>nf(r,t)):nf(e,t)}function Co(e,t,r){let n=r?ef[r]:void 0,o=n?.paths.includes(e)===!0;return hv("sha256").update(R({path:e,value:o?wv(t,n):t,...o?{fingerprint_policy_version:n.version}:{}})).digest("base64url").slice(0,16)}function Us(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 vv(e){return typeof e=="string"&&(cr(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function cn(e){if(e.length>gv)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(!un(t)||t.v!==1||!vv(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 tf(e){if(!Array.isArray(e.assertions))return e;let t=r=>!un(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 rf(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=or(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||Co(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 du(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]="400de68f-104b-5a25-9e79-f69da940832f")}catch{}})();var Vs=1,of=4096,kv=/^[A-Za-z0-9_-]+$/;function qs(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,r)=>r.toUpperCase())}function FD(e,t){let r=[...Object.values(ro),...no],n=new Set(r.flatMap(o=>[qs(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){n.add(qs(o.flag));for(let i of o.aliases??[])n.add(qs(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!n.has(o)))}function zD(e,t){return Ev("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function dn(e,t,r,n){return Buffer.from(JSON.stringify({version:Vs,fingerprint:e,after_id:t,...r===void 0?{}:{after_index:r},...n===void 0?{}:{snapshot:n}})).toString("base64url")}function St(e){return new g(e,h.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]})}function Sv(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Vs&&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 Hs(e){if(typeof e!="string")throw St("Query cursor is malformed.");let t=e.trim();if(t.length===0||t.length>of||!kv.test(t))throw St("Query cursor is malformed.");let r;try{r=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw St("Query cursor is malformed.")}if(!Sv(r)){let n=!1;try{cn(t),n=!0}catch{}throw n?new g("An output cursor must be continued with --output-cursor, not --after.",h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing --after with --output-cursor ${t}; retain any producer --after cursor from the original page.`]}):St("Query cursor version or payload is unsupported.")}return r}function Bs(e,t){let r=Hs(e);if(r.fingerprint!==t)throw St(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function UD(e,t){return Bs(e,t).after_id}function Ov(e,t,r,n){if(t===void 0)return 0;let o=Bs(t,r),i=e.findIndex(s=>n(s)===o.after_id);if(i<0){if(o.after_index!==void 0)return Math.min(o.after_index,e.length);throw St(`Query cursor item ${o.after_id} is no longer present in this result set.`)}return i+1}function HD(e,t){if(t.cursor!==void 0&&Bs(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw St("Query cursor does not match the requested snapshot.");let r=Ov(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:dn(t.fingerprint,t.readId(i),r+n.length-1,t.snapshot)}:{}}}var qD=Object.freeze({version:Vs,max_length:of});import{randomUUID as gE}from"node:crypto";import{randomUUID as pE}from"node:crypto";import{constants as lr}from"node:fs";import{lstat as Ef,mkdir as _E,open as Sf,rename as yE,rm as hE}from"node:fs/promises";import No from"node:path";import{constants as Kv}from"node:fs";import me from"node:fs/promises";import mn from"node:path";import{randomUUID as Js}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 Ro(e){let t=Math.ceil(e.size/2);for(let r of e.keys()){if(t===0)return;e.delete(r),t-=1}}import Av from"node:crypto";import{AsyncLocalStorage as Iv}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 Ws=new Iv,sf=1024;function Tv(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 Cv(e){let t={...Tv(e),clockReads:0,tokenReads:0};return r=>Ws.run(t,r)}async function KD(e,t){return Cv(e)(t)}function af(){let e=Ws.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 YD(e){let t=Ws.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>sf)throw new Error(`Reproducible token length must be an integer between 0 and ${sf}`);let r="";for(;r.length<e;){let n=Av.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 Rv=/^([+-]?)(\d+)([hdwm])$/i,xv=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Nv=/^(\d{4})(\d{2})(\d{2})$/,Dv=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Pv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Mv=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,$v=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function $e(){return af()??new Date().toISOString()}function je(e){return Number.isFinite(Date.parse(e))}function fn(e){let t=$v.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<=Ys(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function dr(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return fn(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var jv=1e4,xo=new Map;function cf(e){let t=xo.get(e);if(t!==void 0)return t;let r=Date.parse(e);return xo.size>=jv&&Ro(xo),xo.set(e,r),r}function ne(e,t){let r=cf(e),n=cf(t);return Number.isFinite(r)&&Number.isFinite(n)&&r!==n?r-n:e.localeCompare(t)}function tP(e,t){return!(t.deadlineBefore&&(!e.deadline||ne(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||ne(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&ne(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&ne(e.updated_at,t.updatedBefore)>0||t.createdAfter&&ne(e.created_at,t.createdAfter)<0||t.createdBefore&&ne(e.created_at,t.createdBefore)>0)}function Gs(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function Ks(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 Lv(e,t,r){r&&r!==t&&(e.includes(r)||e.push(r))}function Fv(e){let t=[],r=d=>Lv(t,e,d),n=Nv.exec(e);if(n){let[,d,l,u]=n;r(`${d}-${l}-${u}`)}let o=Dv.exec(e);if(o){let[,d,l,u,f,m,_,y,w]=o,v=_?`:${_}`:"";r(`${d}-${l}-${u}T${f}:${m}${v}${Gs(y)}${Ks(w)}`)}let i=Pv.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${Gs(m)}${Ks(_)}`)}let s=Mv.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";r(`${d}T${l}:${u}${y}${Gs(m)}${Ks(_)}`)}let a=10,c=e.slice(0,a);if(Uv(c)){let d=a;for(;d<e.length&&Hv(e[d]);)d+=1;d<e.length&&r(`${c}T${e.slice(d)}`)}return t}function zv(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let r of Fv(e)){let n=Date.parse(r);if(Number.isFinite(n))return n}return Number.NaN}function Uv(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 Hv(e){return e?e===" "||e===" "||e===`
|
|
8
|
-
`||e==="\r"||e==="\f"||e==="\v":!1}function Ys(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var qv=["January","February","March","April","May","June","July","August","September","October","November","December"],Vv=/^(\d{4})-(\d{2})-(\d{2})/,Bv=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Wv(e,t,r){let n=Vv.exec(t)??Bv.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=Ys(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${qv[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 Gv(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,Ys(i,s));return r.setUTCFullYear(i,s,a),r}function rP(e,t=new Date,r="deadline"){let n=e.trim();if(n.toLowerCase()==="now")return t.toISOString();let o=Rv.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 Gv(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()}Wv(e,n,r);let i=zv(n);if(!Number.isFinite(i)){let s=r.trim().length>0?r.trim():"deadline",a=xv.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()}(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]="4a6fa947-cc6f-5e48-8722-3db9a1af36f1")}catch{}})();function Yv(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},warnings:[]}}async function pn(e,t=!0){try{let r=await me.readFile(e,"utf8");return t&&await tr({path:e,scope:"project"}),Yv(r)}catch(r){return le(r)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Le(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Xv(e,t,r=process.platform){if(Le(e,"EEXIST"))return!0;if(!Le(e,"EPERM")&&!Le(e,"EACCES")&&!Le(e,"EBUSY"))return!1;try{return await me.lstat(t),!0}catch(n){if(r!=="win32"||!le(n)&&!Le(n,"EPERM")&&!Le(n,"EACCES")&&!Le(n,"EBUSY"))return!1}try{return await me.access(mn.dirname(t),Kv.W_OK),!0}catch{return!1}}async function mf(e,t){await go({path:e,scope:"project",op:t})}function Jv(e,t,r,n=Js()){return{id:e,pid:process.pid,owner:t,token:n,created_at:$e(),ttl_seconds:r}}async function Zv(e,t,r,n,o,i){i&&await me.mkdir(mn.dirname(e),{recursive:!0});let s=await oa(e,t);if(s===null)throw await me.access(mn.dirname(e)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});try{let a=await me.open(e,"wx");try{try{await a.writeFile(`${JSON.stringify(Jv(t,r,n,o),null,2)}
|
|
9
|
-
`,"utf8")}finally{await a.close()}}catch(c){throw await Zs(e,"lock:release"),c}}finally{await s()}await mf(e,"lock:create")}async function Zs(e,t){try{return await me.unlink(e),await mf(e,t),!0}catch{return!1}}async function Qv(e,t,r,n){let o=Date.now(),i=_f;for(;;){let s=await oa(e,t);if(s!==null){try{let d=await pn(e,!1);df(d.info,t,r,n)&&await Zs(e,"lock:release")}finally{await s()}return}let a=await pn(e,!1);if(!df(a.info,t,r,n))return;let c=Date.now()-o;if(c>=lf)return;await gf(Math.min(i,lf-c)),i=Math.min(i*2,ea)}}function df(e,t,r,n){return e?.id===t&&e.pid===process.pid&&e.owner===r&&e.token===n}function Qs(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 pf(e,t,r){let{info:n}=await pn(qi(e,t),!1);return n!==null&&n.owner.startsWith(r)&&!Qs(n,n.ttl_seconds)}function eE(e){return e?.owner?` (owner ${e.owner})`:""}var _f=25,ea=200,tE=250,rE=3,nE=".stale-cleanup",yf="owner.json",hf=1e4,lf=hf+ea,oE=60*6e4;function Xs(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 iE(e){let t=process.env.PM_LOCK_WAIT_MS,r=Xs(t);if(r!==void 0)return r;let n=Xs(e);return n!==void 0?n:0}function sE(e,t){return Math.min(iE(e),t??1/0)}function gf(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(r=>setTimeout(r,t))}function bf(e,t,r){let n=r>0?` after waiting ${r}ms`:"";return new g(`Item ${e} is locked${eE(t)}${n}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:tE}})}function aE(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 cE(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 dE(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 wf(e){try{return dE(await me.readFile(mn.join(e,yf),"utf8"))}catch{return null}}function lE(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!Le(t,"ESRCH")}}function uE(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 vf(e){try{return uE(await me.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function ta(e=process.pid){let t=await vf(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function ra(e,t,r){if(!lE(e.pid))return!1;let n=await vf(e.pid);return e.process_start_identity!==void 0&&n!==null?n===e.process_start_identity:t<=r}async function na(e){try{return await me.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function uf(e,t){let r=await wf(e);r===null||r.token!==t||await na(e)}async function ff(e){try{await me.mkdir(e)}catch(r){return Le(r,"EEXIST"),null}let t={...await ta(),token:Js()};try{await me.writeFile(mn.join(e,yf),`${JSON.stringify(t)}
|
|
10
|
-
`,"utf8")}catch{return await na(e),null}return t}async function fE(e){let t;try{let n=await me.stat(e);if(t=Date.now()-n.mtimeMs,t<=hf)return!1}catch(n){return le(n)}let r=await wf(e);return r!==null&&await ra(r,t,oE)?!1:na(e)}async function oa(e,t){let r=`${e}${nE}`,n=await ff(r);if(n!==null)return async()=>uf(r,n.token);if(!await fE(r))return null;let o=await ff(r);return o===null?null:async()=>uf(r,o.token)}async function mE(e){let t=await oa(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let r=await pn(e.lockPath);if(r.info===null&&r.warnings.length===0)return{lockInfo:r,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!Qs(r.info,e.ttlSeconds))return{lockInfo:r,shouldRetryCreate:!1,staleRemovalCounted:!1};if(cE(e.id,r,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=rE)throw bf(e.id,r.info,Date.now()-e.startedAtMs);return{lockInfo:r,shouldRetryCreate:await Zs(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function ae(e,t,r,n,o=!1,i=!0,s,a={}){let c=Xs(a.maxWaitMs),d=await rr("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 w=aE(d.result);if(w)return async()=>{await Promise.resolve(w()),await rr("lock_release",{pm_root:e,id:t,owner:n})}}let l=qi(e,t),u=sE(s,c),f=Date.now(),m=0,_=_f,y=Js();for(;;)try{return await Zv(l,t,n,r,y,a.createParentDirectories!==!1),async()=>{await Qv(l,t,n,y),await rr("lock_release",{pm_root:e,id:t,owner:n})}}catch(w){if(!await Xv(w,l))throw new g(`Failed to acquire lock for ${t}: ${td(w)}`,h.GENERIC_FAILURE);let v=await pn(l);if(Qs(v.info,r)){let K=await mE({lockPath:l,id:t,ttlSeconds:r,force:o,forceRequiredForStaleLock:i,staleRemovals:m,waitBudgetMs:u,startedAtMs:f,fallbackLockInfo:v});if(v=K.lockInfo,K.staleRemovalCounted&&(m+=1),K.shouldRetryCreate)continue}let C=Date.now()-f;if(u===0||C>=u)throw bf(t,v.info,u===0?0:C);await gf(Math.min(_,u-C)),_=Math.min(_*2,ea)}}(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 Fe={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 Ot(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 Of(e){let t=e.maxBytes??Fe.max_bytes,r=e.maxEvents??Fe.max_events,n=e.retentionDays??Fe.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>Fe.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:Ot(e).ms-n*864e5}}async function Af(e,t){if(!(await Ef(No.dirname(e))).isDirectory())throw new Y("Context usage runtime must be a real directory");try{if((await Ef(e)).isSymbolicLink())throw new Y("Context usage ledger must not be a symbolic link")}catch(n){if(!le(n))throw n}let r=await Sf(e,t|lr.O_NOFOLLOW|lr.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 Do(e){let t=Of(e);try{let r=await Af(No.join(e.pmRoot,"runtime","context-usage.jsonl"),lr.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(`
|
|
11
|
-
`)?a.slice(a.indexOf(`
|
|
12
|
-
`)+1):"":a).split(`
|
|
13
|
-
`).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 kf(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])}
|
|
14
|
-
`;if(o+=Buffer.byteLength(s),o>t)break;n.push(s)}return n.reverse().join("")}async function _n(e,t,r){let n=Of(e),o=No.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(n.maxBytes*Fe.retained_byte_fraction),s=Math.min(Fe.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
|
|
15
|
-
`)>s))throw new Y("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=n.cutoff),c=kf(a,i,n.maxEvents),d=performance.now(),l=await ae(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await _E(No.dirname(o),{recursive:!0});let f=await Af(o,lr.O_WRONLY|lr.O_CREAT|lr.O_APPEND);try{let m=(await f.stat()).size,_=r===void 0?void 0:await Do(e);if(_?.some(C=>C.kind==="delivery"&&C.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=kf([..._??await Do(e),...a],i,n.maxEvents),w=`${o}.${process.pid}.${pE()}.tmp`,v=await Sf(w,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await yE(w,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await hE(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 bE=864e5,Po=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function J(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function AP(e,t){let r=J(e);r!==null&&t!==null&&(r[Po]=t)}function ur(e,t){let r=J(e),n=J(t),o=r?.[Po];n!==null&&o!==void 0&&(n[Po]=o)}function wE(e){return J(e)?.[Po]??null}function Tf(e){let t=J(e);for(let r of["read_output","context_intent"])if(J(t?.[r])?.result_omitted===!0)return!0;return!1}function Je(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function Cf(e,t){if(Array.isArray(t))for(let r of t)Je(e,J(r)?.id)}function If(e,t){if(Array.isArray(t))for(let r of t)Je(e,r)}function vE(e,t){let r=J(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=J(n);Je(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])Je(t,J(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])Je(t,i)}}function EE(e,t){for(let r of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])Cf(t,e[r]);for(let r of Array.isArray(e.blockers)?e.blockers:[])Je(t,J(r)?.blocked_by);kE(e,t)}function kE(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=J(o);Je(t,i?.id),Cf(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])If(t,J(i)?.items);let r=J(e.agenda);for(let o of Array.isArray(r?.events)?r.events:[])Je(t,J(o)?.item_id);let n=J(e.tests);If(t,n?.items_failing)}function SE(e,t){let r=J(e);if(r===null||Tf(e))return[];let n=new Set;return t==="next"?vE(r,n):EE(r,n),[...n]}async function IP(e){let t=wE(e.result);if(t===null)return!1;let r=Tf(e.result);return await OE({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:SE(e.result,t.surface),resultOmitted:r}),!0}async function TP(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,Fe.max_serving_rows),n={serve_id:gE(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:r.map(o=>o.id)};return n.storage=await _n(e,[{kind:"serve",schema_version:2,serve_id:n.serve_id,at:Ot(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 OE(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:Ot(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:r.filter(i=>n.has(i))};await _n(e,[o],o.serve_id)}async function CP(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 _n(e,[{kind:"touch",at:Ot(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function RP(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=Ot(e).iso,i=[...n].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:r}));await _n(e,i)}function AE(e,t,r,n){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=r&&i-r<=n)?.time}function IE(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 xP(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 Do(e),r=Ot(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=IE(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=AE(i,w.id,m,n);if(v===void 0)continue;d+=1;let C=Math.max(0,(r-v)/bE);s.set(w.id,(s.get(w.id)??0)+Math.exp(-C/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]="6a604d54-5425-5ae7-8f20-9d5f1d33c20c")}catch{}})();var xf=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"}]),Nf=new TE;function CE(){return Nf.getStore()??xf}function qP(e,t){return Nf.run(xE(e.workspaceContracts,e.packageContracts),t)}function RE(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 xE(e=[],t=[]){let r=[{source:"core",contracts:xf,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=RE(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 Df(e,t,r=CE(),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=nr(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:nr(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}var Pf={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=$o(e.tokenBudget,t.token_budget),o=jo("context",t.intent,n,r),i=At(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=$o(e.tokenBudget,t.token_budget),o=jo("list",t.intent,n,r),i=At(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=$o(e.tokenBudget,t.token_budget),o=jo("search",t.intent,n,r),i=At(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))}};function VP(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=Df(e,t.for,void 0,r),i=At(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)),Pf[e](s,o,i),s}var NE={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Mo=256;function ia(e){return Array.isArray(e)?e.map(ia):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,r])=>[t,ia(r)])):typeof e=="string"&&e.length>240?`${Ge(e,240)}\u2026`:e}function At(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 $o(e,t){let r=At(e);if(r===void 0)return t;if(r<Mo)throw new g(`Context intent token budget must be at least ${Mo}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Mo}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Mo} or omit the override.`]});return r}function jo(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 Ze(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 Rf={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 Mf(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 DE(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 PE(e,t,r){let n=!1;for(;;){if(Ze(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 ME(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=Mf(i);if(s===void 0)return!1;let a=n.length,c=[...n],d=!1;for(;;){if(d=PE(e,t,n)||d,!d)return!1;let l=DE(n.at(-1));if(l===void 0)return n.splice(0,n.length,...c),Ze(e,t),!1;if(e.next_cursor=dn(s.fingerprint,l,o?s.after_index-(a-n.length):s.after_index+n.length,s.snapshot),Ze(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 $E(e,t,r,n){if(e==="list"||e==="search")return ME(t,r,n);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Ze(t,r),r.estimated_tokens<=r.token_budget)return o;let i=Rf[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=Rf[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 jE(e,t,r){if(typeof t.for!="string")return r;let n=e.startsWith("list-")?"list":e;if(!(n in Pf))return r;let o=n,i=Df(o,t.for),s=$o(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:NE[o],declaration_feasible:!0,result_omitted:!1},c={...r},d=jo(o,i.intent,a.token_budget,At(t.tokenBudget??t.token_budget)!==void 0);if(d!==void 0){let u=At(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 Ze(l,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",l={...ia(c),context_intent:a},Ze(l,a)),a.estimated_tokens>a.token_budget&&$E(o,l,a,t)&&(a.degradation="budget_row_compaction",Ze(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:FE(e,o,i.intent,a,c)},context_intent:a}),l}function LE(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let r=Mf(e.after)?.fingerprint??"opaque_cursor",n={...t};for(let o of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete n[o];return n.continuation_contract={fingerprint:r,metadata:"reference",restore_with:"omit --after"},n}function sa(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function FE(e,t,r,n,o){let i=t==="get"&&sa(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 fr(e,t){if(sa(e))return typeof e[t]=="number"?e[t]:void 0}function zE(e,t){let r=e;for(let n=0;n<8;n+=1){let o=fr(r.context_intent,"estimated_tokens"),i=fr(r.read_output,"estimated_tokens"),s=fr(r.read_session,"spent_this_call_tokens");if(sa(r.context_intent)&&Ze(r,r.context_intent),r=zs(r,t),fr(r.context_intent,"estimated_tokens")===o&&fr(r.read_output,"estimated_tokens")===i&&fr(r.read_session,"spent_this_call_tokens")===s)break}return r}function $f(e,t,r){let n=ou(e,gu(e??"",r)),o=typeof n=="object"&&n!==null&&!Array.isArray(n)?Ju(e??"",{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},LE(t,jE(e??"",t,n))):n;if(ur(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=zE(i,t);return delete s.row_contract,ur(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 mr=["result_rows","envelope","diagnostics","hints"],UE=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,HE=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,qE=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,VE=8;function aa(e){return Buffer.byteLength(e,"utf8")}function jf(e){return aa(JSON.stringify(e)??"null")}function BE(e,t){return HE.test(e)?"diagnostics":qE.test(e)?"hints":UE.test(e)||Array.isArray(t)?"result_rows":"envelope"}function WE(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"]=jf(e),t;for(let[r,n]of Object.entries(e))t[BE(r,n)]+=jf({[r]:n});return Object.values(t).every(r=>r===0)&&(t.envelope=1),t}function GE(e,t){let r=mr.reduce((s,a)=>s+t[a],0),n=mr.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-mr.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))||mr.indexOf(a.section)-mr.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Lf(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Ff(e,t){let r=aa(t(e)),n=GE(r,WE(e)),o=Object.fromEntries(mr.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=Lf(e,i);for(let a=0;a<VE;a+=1){let c=aa(t(s))-r;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Et(c)},s=Lf(e,i)}return s}import{encode as da}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 zf(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 KP(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]="19d6f507-d3b1-5ccc-aba5-594983776618")}catch{}})();var JP=["id","title","status","type","priority","parent","updated_at"],ca=["id","status","type","title"],ZP={list:"brief","list-all":"full","list-draft":"full","list-open":"brief","list-in-progress":"brief","list-blocked":"brief","list-closed":"brief","list-canceled":"full"},KE=["tree_depth","tree_parent","tree_children","tree_title"];function QP(e=[]){return[...new Set([...we,"body",...KE,...e])].flatMap(t=>[t,`item.${t}`]).sort()}var e1=["brief","standard","deep"],YE=["body","linked","claim_state","children","schedule","blockers"],XE=["linked.files","linked.tests","linked.docs"],JE=["claim_state.claimed","claim_state.assignee","claim_state.last_claim","claim_state.last_release"],ZE=["schedule.deadline","schedule.start_at","schedule.end_at","schedule.location","schedule.reminders","schedule.events"];function t1(e=[]){return[...[...new Set([...we,...e,"notes_count","tests_count","collection_counts"])].flatMap(t=>[t,`item.${t}`]),...YE,...XE,...JE,...ZE].sort()}var r1=["id","title","status","type","priority","updated_at","score","matched_fields"],QE=["score","matched_fields","highlights"],Uf=["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 n1(e=[]){let t=[...new Set(e)];return[...QE,...Uf,...Uf.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]="20b84c6a-ac5f-515e-aba1-32be7a69981c")}catch{}})();function pr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function e0(e){if(!pr(e))return!1;let t=e.fields;return e.mode==="brief"&&Object.keys(e).length===2&&Array.isArray(t)&&t.length===ca.length&&ca.every((r,n)=>t[n]===r)}function t0(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 r0(e){return pr(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function n0(e){if(!pr(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&&pr(r)&&Object.keys(r).length===2&&r.name==="full_item_fields"&&r.restore_with==="--full"}function Hf(e){if(!pr(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!e0(e.projection)||!r0(e.completeness)||!t0(e,e.items.length)||!n0(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}:{},...pr(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]="9716962d-d651-5e7a-84d8-496d35e8775f")}catch{}})();var o0=new Set(Object.values(h)),i0=new Map([["notes_count","notes"],["tests_count","tests"]]),la="__pm_native_output",qf=!1;function q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pa(e){let t={read_output:{result_omitted:!0}};ur(e,t),ho(t)}function s0(e,t,r){if(r){ho(e);return}pa(t)}function a0(e){if(!q(e)||e[la]!==!0)return e;let{[la]:t,...r}=e;return r}function ua(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function c0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function d0(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function fa(e){if(e==="stdout"){c0();return}d0()}function Vf(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function l0(){qf||(qf=!0,process.stdout.on("error",e=>{if(ua(e)){fa("stdout");return}Vf(e)}),process.stderr.on("error",e=>{if(ua(e)){fa("stderr");return}Vf(e)}))}function Bf(e,t){l0();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(r){if(ua(r))return fa(e),!1;throw r}}function u0(e){return Bf("stdout",e)}function yn(e){return Bf("stderr",e)}function Wf(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function f0(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 ma(e,t){let r=" ".repeat(t);return e.split(`
|
|
16
|
-
`).map(n=>`${r}${n}`).join(`
|
|
17
|
-
`)}function m0(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 p0(e,t,r,n){let o=" ".repeat(r);if(!q(t)&&!Array.isArray(t))return`${o}${e}: ${Wf(t)}`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=ma(da({[e]:t}),r);if(n&&t.length>=2&&t.every(q)&&!f0(t)&&m0(t)){let s=zf(t),a=ma(da({[e]:s.rows,[`${e}_encoding`]:s.encoding}),r);if(Buffer.byteLength(a)<Buffer.byteLength(i))return a}return i}return q(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
|
|
18
|
-
${Gf(t,r+1)}`}function _0(e,t,r){let n=e.map(o=>Fo(o,t,r||t.preserveRowFacts&&q(o))).filter(o=>o!==void 0);return n.length>0||r?n:void 0}function Fo(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},r=!1){if(e===null)return r?null:void 0;if(Array.isArray(e))return _0(e,t,r);if(q(e)){let n=[],o=Object.entries(e).filter(([i,s])=>{let a=i0.get(i);return!t.omitDuplicateCountAliases||a===void 0||!q(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=Fo(s,t,r);a!==void 0&&n.push([i,a])}return n.length>0||r?Object.fromEntries(n):void 0}return e}function Gf(e,t){let r=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":ma(da(e),t);if(q(e)){let n=Object.entries(e);return n.length===0?"{}":n.map(([o,i])=>p0(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&q(e.verdict)&&e.verdict.authority==="ok"))).join(`
|
|
19
|
-
`)}return`${r}${Wf(e)}`}function y0(e){if(!q(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=q(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(`
|
|
20
|
-
`)}
|
|
21
|
-
`;for(let n of e.events){if(!q(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(`
|
|
22
|
-
`)}
|
|
23
|
-
`}var h0=new Set(["filters","now","projection","sorting"]);function g0(e){let t=Fo(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!q(t)||!Array.isArray(t.items))return t??null;let r=Object.fromEntries(Object.entries(t).filter(([n])=>!h0.has(n)));return r.has_more!==!0&&delete r.next_cursor,r}function b0(e,t){if(!q(e)||!Array.isArray(e.run_results)||!e.run_results.every(q))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 w0(e){return!q(e)||e.ok!==!0||!q(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(v0)}}function v0(e){if(!q(e)||e.ok!==!0||!q(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...r}=e;return r}function Lo(e,t,r=!1){if(t==="json")return`${JSON.stringify(r?g0(e):e,null,2)}
|
|
24
|
-
`;let n=Fo(w0(Hf(e)),{omitDuplicateCountAliases:!0,preserveRowFacts:!0});return n===void 0?`{}
|
|
25
|
-
`:`${Gf(n,0)}
|
|
26
|
-
`}function E0(e,t,r,n){let o=t?{handled:!1,result:e,warnings:[]}:As("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&&yn(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
27
|
-
`),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
|
|
28
|
-
`)?o.result:`${o.result}
|
|
29
|
-
`,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||q(o.result)}}function k0(e,t,r,n){let o=Jl(),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(C=>C[1]!==void 0))},a=Qu(i??"",s)??n,c={...s,resolvedOutputFormat:a},d={...r,command:i,commandOptions:c},l=E0(e,t,d,a);if(l.rendered!==null)return pa(e),l.rendered;let u=l.result;ur(e,u);let f=i==="test"?b0(u,r.lean===!0):u,m=$f(i,c,f);Zu(m)&&(process.exitCode||=h.USAGE);let{structuredDeliveryPreserved:_}=l,y=C=>{if(a==="toon"){let Ee=y0(C);if(Ee!==null)return Ee}let K=t?{rendered:null}:Ql(a,C);return K.rendered!==null?(_=!1,K.rendered.endsWith(`
|
|
30
|
-
`)?K.rendered:`${K.rendered}
|
|
31
|
-
`):a==="json"?Lo(C,"json",r.lean===!0):Lo(C,"toon")},w=r.tokenAccounting===!0?Ff(m,y):m,v=y(w);return s0(w,e,r.quiet!==!0&&_),v}function S0(e,t){let r=Zl(e),n=Un(r.result)?r.result:null,o=r.result,i=q(o)&&o[la]===!0,s=n?n.result:a0(r.result);if(ho(s),n)return pa(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return k0(s,i,t,a)}function g1(e,t){q(e)&&Number.isInteger(e.exit_code)&&o0.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let r=t.idOnly?rn(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?rn(e,{changedFields:"compact"}):rn(e,{compactEnvelope:!0}),n=S0(r,t);t.quiet||u0(n)}function b1(e){let t=As("error_format",{message:e}),r=t.handled&&typeof t.result=="string"?t.result:e;yn(r.endsWith(`
|
|
32
|
-
`)?r:`${r}
|
|
33
|
-
`)}(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 O0=8,A0=64,I0=5,T0=4,Kf=100;function Pu(e,t,r){if(e!=="get"||!_a(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=[..._a(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 Ps(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*I0/T0),i=Math.ceil(o/Kf)*Kf;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 sr(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 nn(e,t){let r=t===void 0?JSON.stringify(e):Lo(e,t);return Math.ceil(Buffer.byteLength(r,"utf8")/4)}function _a(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ya(e,t,r=!1){return typeof e=="string"?r||e.length<=240?e:(t.compacted=!0,`${Ge(e,240)}\u2026`):Array.isArray(e)?e.map(n=>ya(n,t,r)):_a(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,ya(o,t,r||n==="focus_row_states")])):e}function Xe(e,t,r){let n=t.estimated_tokens;for(let o=0;o<O0;o+=1){t.estimated_tokens=n;let i=nn(e,r);if(i===n)return;n=i}t.estimated_tokens=n}function C0(e,t){return Qr(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 R0(e,t,r,n,o,i){for(let s=0;s<A0;s+=1){if(i?.(e),Xe(e,t,o),t.estimated_tokens<=r)return;let a=C0(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=ko(e)),a.path==="items"&&(e.applied_limit=_),i?.(e),Xe(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 Mu(e,t,r,n=new Map,o,i,s=!1){let a={compacted:!1},c=Object.fromEntries(Object.entries(e).map(([d,l])=>[d,ya(l,a,s&&d==="diff")]));return sr(e,c),t.strings_compacted=a.compacted,c.read_output=t,R0(c,t,r,n,o,i),Xe(c,t,o),c}import ga from"node:fs/promises";import zo 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 Qe(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function ba(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:nr(t),suggested_retry_args:t}}function Uo(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 ha(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 x0(e){let t=zo.resolve(e),r=zo.parse(t).root,n=zo.dirname(t);for(;n!==r;){let o;try{o=await ga.stat(n)}catch(i){if(Qe(i,"ENOTDIR"))throw Uo(e);if(!Qe(i,"ENOENT"))throw i;n=zo.dirname(n);continue}if(!o.isDirectory())throw Uo(e);return}}async function Yf(e){let t;try{t=await ga.stat(e)}catch(r){throw Qe(r,"ENOENT")?(await x0(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:ba(e)})):Qe(r,"ENOTDIR")?Uo(e):Qe(r,"EACCES")||Qe(r,"EPERM")?ha(e):r}if(!t.isDirectory())throw Uo(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw ha(e);try{await(await ga.opendir(e)).close()}catch(r){throw Qe(r,"EACCES")||Qe(r,"EPERM")?ha(e):r}}async function N0(e){if(await Yf(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:ba(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]="5c8194ff-d877-51b8-bd54-d206f85a979c")}catch{}})();(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 Xf=["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"],Jf=["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"],wa={"init:type-preset":"init:type_preset"},Zf=["^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_]*$"],M1={version:1,item:Xf,workspace:Jf,aliases:wa,patterns:Zf,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"]},D0=new Set([...Xf,...Jf]),P0=Zf.map(e=>new RegExp(e,"u"));function Qf(e){return Object.hasOwn(wa,e)?wa[e]:e}function $1(e){let t=Qf(e);if(D0.has(t)||P0.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 em(e){let t=Qf(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 M0}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 F1=["sha256","sha512"],$0="sha256",tm="sha256";function It(e){if(e===void 0)return $0;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function et(e,t){return M0(It(t)).update(e,"utf8").digest("hex")}import nm from"node:path";import{link as j0,mkdir as L0,mkdtemp as F0,rm as z0,writeFile as U0}from"node:fs/promises";import va 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 rm(e,t){let r=va.dirname(e);await L0(r,{recursive:!0});let n=await F0(va.join(r,".pm-seed-")),o=va.join(n,"value");try{await U0(o,t,"utf8");try{return await j0(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await z0(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 H0=2e3,Ho=new Map;function tt(e){if(typeof e!="string")return"";let t=Ho.get(e);if(t!==void 0)return t;let r=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Ho.size>=H0&&Ro(Ho),Ho.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 oe=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),sm=Kc,ka=Gc,q0=["create","update"],V0=new Set(Vn),B0=new Set(Wt),W0=new Set(Bn),G0=new Set(Wn),K0=new Set(["string","number","boolean","array","object"]),Y0=16;function am(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var X0=[e=>e.type===void 0||typeof e.type=="string"&&K0.has(e.type),e=>!Object.hasOwn(e,"const")||Vo(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Vo(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||am(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Vo(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=>Vo(n,t)):Object.values(e).every(n=>Vo(n,t));return t.delete(e),r}function qo(e,t=0,r=new Set){if(!am(e)||t>Y0||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(!X0.every(v=>v(n))){r.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,C])=>[v,qo(C,t+1,r)])),y=c===void 0?void 0:qo(c,t+1,r),w=s===void 0?void 0:s.map(v=>qo(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 gn(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 pe(e){if(typeof e!="string"||e.length===0)return;let t=tt(e);return t.length>0?t:void 0}function J0(e){return e.startsWith("--")?e.slice(2):e}function om(e){return typeof e=="string"?J0(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function cm(e){return e.replaceAll("_","-")}function Z0(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 Ea(e,t){let r=pe(e.id);if(!r)return null;let n=[...new Set(gn(e.aliases).map(tt).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=gn(e.roles).filter(a=>V0.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 Q0(e){return{draft_status:pe(e?.draft_status),open_status:pe(e?.open_status),in_progress_status:pe(e?.in_progress_status),blocked_status:pe(e?.blocked_status),close_status:pe(e?.close_status),canceled_status:pe(e?.canceled_status)}}function dm(e,t){if(!Array.isArray(t)||t.length!==2)return;let r=tt(t[0]),n=tt(t[1]);r.length===0||n.length===0||e.pairs.some(o=>o[0]===r&&o[1]===n)||e.pairs.push([r,n])}function ek(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)dm(r,n);return{typeKey:t.toLowerCase(),record:r}}function tk(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let n of e){let o=ek(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)dm(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 lm(e){let t=tt(e.key??"");if(!t)return null;let r=tt(e.metadata_key??e.front_matter_key??t),n=om(e.cli_flag??cm(t));if(!n)return null;let o=gn(e.cli_aliases).map(u=>om(u)).filter(u=>u.length>0&&u!==n),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=B0.has(i)?i:"string",a=(()=>{let u=gn(e.commands).filter(f=>W0.has(f));return u.length>0?u:[...q0]})(),c=e.description?.trim(),d=gn(e.required_types),l=e.value_schema===void 0?void 0:qo(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 rk(e){let t=new Map;for(let[n,o]of e.entries()){let i=Ea(o,n);i&&t.set(i.id,i)}let r=im([...t.values()]);return r.length>0?r:im(ka.map((n,o)=>Ea(n,o)).filter(n=>n!==null))}function im(e){return e.sort((t,r)=>t.order===r.order?t.id.localeCompare(r.id):t.order-r.order)}function nk(e){let t=new Map;for(let r of e??[]){let n=lm(r);n&&t.set(n.key,n)}return[...t.values()].sort((r,n)=>r.key.localeCompare(n.key))}function ok(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 ik(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==cm(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 G0.has(t)?t:"allow"}function Ie(e){let t={...oe,...e?.files},r=e?.statuses&&e.statuses.length>0?e.statuses:ka,n=rk(r),o=nk(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:n.map(ok),fields:o.map(ik),workflow:{...sm,...Q0(e?.workflow)},type_workflows:tk(e?.type_workflows),unknown_field_policy:sk(e?.unknown_field_policy)}}function ak(e,t,r){try{return JSON.parse(e)}catch{r.push(t);return}}function ck(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 dk(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 lk(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 uk(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 fk(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 ce(e,t,r){let n=t?.trim()||r;return nm.isAbsolute(n)?n:nm.join(e,n)}function Z1(e,t){return ce(e,t.files.types,oe.types)}async function um(e,t){let r=Ie(t),n=[{path:ce(e,r.files.types,oe.types),seed:{definitions:[]}},{path:ce(e,r.files.statuses,oe.statuses),seed:{statuses:ka}},{path:ce(e,r.files.fields,oe.fields),seed:{fields:[]}},{path:ce(e,r.files.workflows,oe.workflows),seed:{workflow:sm}}],o=[];for(let i of n)await ft(i.path)||await rm(i.path,`${JSON.stringify(i.seed,null,2)}
|
|
34
|
-
`)&&o.push(i.path);return{created_paths:o}}async function fm(e,t){let r=Ie(t),n=[],o=ce(e,r.files.types,oe.types),i=ce(e,r.files.statuses,oe.statuses),s=ce(e,r.files.fields,oe.fields),a=ce(e,r.files.workflows,oe.workflows),c,d,l,u,f,m=async(C,K)=>{let Ee=await ge(C);if(Ee!==null)return ak(Ee,K,n)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=ck(_),c===void 0&&n.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=dk(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=lk(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=uk(v),u===void 0&&n.push("runtime_schema_workflows_invalid_shape"),f=fk(v)),{schema:Ie({...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 hn(e,t,r,n=!1){let o=r.map(s=>pe(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 mk(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 pk(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 mm(e){let t=Ie(e),r=t.statuses.map((v,C)=>Ea(v,C)).filter(v=>v!==null),{aliasToId:n,byId:o}=mk(r),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=pk(r),u=t.workflow,f=pe(u.open_status)??hn(r,"default_open",["open","in_progress",Bt[0]]),m=pe(u.in_progress_status)??hn(r,"active",["in_progress","in-progress",f],!0),_=pe(u.blocked_status)??hn(r,"blocked",["blocked"]),y=pe(u.close_status)??hn(r,"default_close",["closed","done","complete"]),w=pe(u.canceled_status)??hn(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 Sa(e,t){let r=tt(e);if(r)return t.alias_to_id.get(r)}function pm(e){let t=Ie(e),r=new Map,n=t.fields.map(c=>lm(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 _m(e){return Z0(e.key)}function Q1(e,t){let r=Sa(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 _k=16;function Oa(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 yk(e){return[...new Set([_m(e),Oa(e.key),Oa(e.cli_flag),...e.cli_aliases.map(t=>Oa(t))])]}function gm(e,t){for(let r of yk(t)){if(!Object.hasOwn(e,r))continue;let n=e[r];if(n!==void 0)return n}}function bm(e){return Array.isArray(e)?e.flatMap(t=>bm(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 ym(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 hm(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 hk(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 gk(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 bk(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(!gk(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"&&!fn(e))return`${r} must be an RFC 3339 date-time`}}function wk(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=Bo(i,t.items,`${r}[${o}]`,n+1);if(s)return s}}}function vk(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=Bo(s,a,`${r}.${i}`,n+1);if(c)return c}}function Bo(e,t,r,n=0){if(n>_k)return`${r} value schema exceeds maximum depth`;let o=bk(e,t,r);if(o)return o;let i=wk(e,t,r,n);if(i)return i;let s=vk(e,t,r,n);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Bo(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 Tt(e,t,r){if(!e.value_schema||t===void 0)return t;let n=Bo(t,e.value_schema,r);if(n)throw new g(n,h.USAGE);return t}function Ek(e,t,r,n){let o=n==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Tt(e,hk(o,r,e.type),r)}function bn(e,t,r,n="option"){let o=r??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return Ek(e,t,o,n);if(e.repeatable||e.type==="string_array"){let s=bm(t);return e.type==="number"?Tt(e,s.map(a=>hm(a,o)),o):e.type==="boolean"?Tt(e,s.map(a=>ym(a,o)),o):Tt(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Tt(e,hm(i,o),o):e.type==="boolean"?Tt(e,ym(i,o),o):Tt(e,typeof i=="string"?i:String(i),o)}function kk(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 sM(e,t,r){let n={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=gm(e,i);if(s===void 0){kk(i,r)&&o.push(`--${i.cli_flag}`);continue}n[i.metadata_key]=bn(i,s)}return{values:n,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function aM(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=gm(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),n[s.metadata_key]=bn(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 Aa=1,Ia=2;function dM(e){return Math.max(Ta(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function Ta(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function wm(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function Sk(e,t=2,r=t){return e<r?"outdated":e>t?"ahead":"current"}function lM(e,t=2,r=t){let n=[],o=[];for(let i of e){let s=Sk(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 Ok={"in-progress":"in_progress",cancelled:"canceled"};function Wo(e,t){if(t){let o=Sa(e,t);if(o)return o}if(typeof e!="string")return;let r=e.trim().toLowerCase();if(!r)return;let n=Ok[r]??r;if(Bt.includes(n))return n}function Ak(e,t){return Wo(e,t)??e}function pM(e,t){return t.terminal_statuses.has(Ak(e,t))}import{encode as Rk}from"@toon-format/toon";import{isDeepStrictEqual as vm}from"node:util";import{decode as Ik}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 Ca(e){return{value:Ik(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 Tk=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function Ck(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(Tk);if(!i)continue;let s=i[1];r.push({line:n+1,marker:s,text:o})}return r}function Go(e){return Ck(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 Da=new Set(["schema","tracker","auto","none"]),Am=new Set(["source","isolated","snapshot"]),xk=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),Nk=new Set(["passed","failed","stopped","canceled"]),Dk=new Set(id);function hr(e){return e.replaceAll("\\","/")}function Im(e){for(let t of e)if(t!==0)return t;return 0}function Yo(e){for(let[t,r]of Object.entries(e))r===void 0&&delete e[t]}var Tm=["id","title","description","created_at","updated_at"],Pk=new Set(we);function Cm(e){if(e?.schema)return{statusRegistry:mm(e.schema),fieldRegistry:pm(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Mk(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(r=>r.toLowerCase()).includes(t.trim().toLowerCase()):!1}function rt(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 En(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 Rm(e,t){if(!t||typeof e!="object"||e===null)return;let r=Ta(e);if(!(r<=Ia))throw new g(`Stored item uses format version ${r}; this runtime supports up to ${Ia}. 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 xm(e){let t=new Set(Pk);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||rt(t)}function kn(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&rt(t),e}function Ra(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 Em(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 Pa(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 $k(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(Nr.includes(r),`event.recurrence.by_weekday entries must be one of: ${Nr.join(", ")}`)}}}function jk(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 Lk(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 Fk(e){let t=kn(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(Yn.includes(r),`event.recurrence.freq must be one of: ${Yn.join(", ")}`),Em(t,"interval","event.recurrence.interval"),Em(t,"count","event.recurrence.count"),Pa(t,"until","event.recurrence.until"),$k(t.by_weekday),jk(t.by_month_day),Lk(t.exdates)}function zk(e){for(let n of Tm)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>=Aa,`pm_format_version must be an integer >= ${Aa}`),t}function Uk(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=Wo(r,n),i=n?n.definitions.map(s=>s.id):[...Bt];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function Hk(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 qk(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"||Kn.includes(r);O(n,`confidence string value must be one of: ${[...Kn,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function Vk(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&rt("severity must be a string");let r=t.trim().toLowerCase(),n=r==="med"||Gn.includes(r);O(n,`severity value must be one of: ${[...Gn,"med"].join(", ")}`)}function Bk(e){e.regression!==void 0&&typeof e.regression!="boolean"&&rt("regression must be a boolean")}function Wk(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=kn(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 Gk(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 Kk(e){e.recurrence!==void 0&&(Fk(e.recurrence),e.recurrence.until!==void 0&&O(ne(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Yk(e){let t=kn(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(ne(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Gk(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),Kk(t)}function Xk(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let r of t)Yk(r)}}function Jk(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 Zk(e){let t=e.type_options;if(t===void 0)return;let r=kn(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 Qk(e,t,r){if(r?.fieldRegistry)for(let n of r.fieldRegistry.definitions){let o=e[n.metadata_key];if(o===void 0){Mk(n,t)&&rt(`missing required schema field: ${n.metadata_key}`);continue}try{e[n.metadata_key]=bn(n,o,`metadata field "${n.metadata_key}"`,"metadata")}catch(i){rt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function eS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=xm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length!==0&&(t.unknownFieldPolicy==="reject"?rt(`unknown schema fields are not allowed: ${n.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`))}function Ma(e,t){let r=kn(e,"item metadata must be an object"),n=zk(r);Uk(r,t),Hk(r),qk(r),Vk(r),Bk(r),Ra(r,"created_at"),Ra(r,"updated_at"),r.deadline!==void 0&&Ra(r,"deadline"),Wk(r),Xk(r),Pa(r,"closed_at","closed_at"),Pa(r,"completed_at","completed_at"),Jk(r),Zk(r),Qk(r,n,t),eS(r,t)}function tS(e){if(!(!e||e.length===0))return[...e].map((t,r)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&fn(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=ne(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 xa(e){if(!(!e||e.length===0))return[...e].sort((t,r)=>{let n=ne(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 rS(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=ne(r.at,n.at);return o!==0?o:r.text.localeCompare(n.text)});return t.length===0?void 0:t}function nS(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Yn.includes(t))return;let r=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Nr.includes(s)))).sort((s,a)=>Li(s)-Li(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)=>ne(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 oS(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(iS).sort(sS)}function iS(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:nS(e.recurrence)};return Yo(t),t}function sS(e,t){return Im([ne(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 aS(e){if(!(!e||e.length===0))return e.map(t=>({path:hr(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function cS(e){if(!e||e.length===0)return;let t=e.map(fS).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)=>Im([ne(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 _r(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function dS(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Na(e){return typeof e=="string"?e:""}function lS(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 Ko(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function uS(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:Ko(r.requested_pm_context_mode,Da),pm_context_mode:Ko(r.pm_context_mode,Da),workspace_context_mode:Ko(r.workspace_context_mode,Am),trust_reason:Ko(r.trust_reason,xk)}));return t.length>0?t:void 0}function fS(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",r=e.kind==="test"||e.kind==="test-all"?e.kind:"test",n=Nk.has(e.status)?e.status:"failed",o={run_id:t,kind:r,status:n,started_at:Na(e.started_at),finished_at:Na(e.finished_at),recorded_at:Na(e.recorded_at),attempt:dS(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:_r(e.passed)??0,failed:_r(e.failed)??0,skipped:_r(e.skipped)??0,items:_r(e.items),linked_tests:_r(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:lS(e.measurements),executions:uS(e.executions)};return Yo(o),o}function mS(e){if(!(!Array.isArray(e)||e.length===0))return e.map(gS)}function wn(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 Fa(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function za(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function km(e){if(!Fa(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),String(n).trim()]).filter(([r,n])=>r.length>0&&!za(r)&&n.length>0).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function pS(e){if(!Fa(e))return;let t=Object.entries(e).map(([r,n])=>[r.trim(),Number(n)]).filter(([r,n])=>r.length>0&&!za(r)&&Number.isFinite(n)).sort(([r],[n])=>r.localeCompare(n));return t.length>0?Object.fromEntries(t):void 0}function _S(e){let t=e?.trim().toLowerCase();if(!(!t||!Da.has(t)))return t}function yS(e){let t=e?.trim().toLowerCase();if(!(!t||!Am.has(t)))return t}function hS(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Fa(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 gS(e){let t={command:e.command?.trim()||void 0,path:e.path?hr(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:_S(e.pm_context_mode),workspace_context_mode:yS(e.workspace_context_mode),...hS(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:km(e.env_set),env_clear:wn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:wn(e.assert_stdout_contains),assert_stdout_regex:wn(e.assert_stdout_regex),assert_stderr_contains:wn(e.assert_stderr_contains),assert_stderr_regex:wn(e.assert_stderr_regex),assert_stdout_min_lines:_r(e.assert_stdout_min_lines),assert_json_field_equals:km(e.assert_json_field_equals),assert_json_field_gte:pS(e.assert_json_field_gte),note:e.note?.trim()||void 0};return Yo(t),t}function bS(e){if(!(!e||e.length===0))return[...e].map(t=>({path:hr(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 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=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 vS(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:hr(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 ES(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=hr(i));let a=E(n.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function kS(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:hr(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 SS(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&&Dk.has(o)?o:void 0,s=qn(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 OS(d,t),d}function OS(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",wS],["files","files",vS],["tests","tests",ES],["docs","docs",kS]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function AS(e){if(!Array.isArray(e))return;let t=e.flatMap(r=>{let n=SS(r);return n?[n]:[]});return t.sort((r,n)=>r.order-n.order),t.length>0?t:void 0}function IS(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 TS(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 CS(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 RS(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 yr(e){let t=0;for(;t<e.length&&e[t]===`
|
|
35
|
-
`;)t+=1;return e.slice(t).trimEnd()}function xS(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Kn.includes(t))return t}function NS(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Gn.includes(t))return t}function vn(e){return e||void 0}function DS(e,t){let r=e,n=t;for(let[o,i]of Object.entries(n))za(o)||Object.prototype.hasOwnProperty.call(r,o)||i===void 0||(r[o]=i)}function PS(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]=bn(n,o,`metadata field "${n.metadata_key}"`,"metadata"))}}function MS(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let r=xm(t),n=Object.keys(e).filter(o=>!r.has(o)).sort((o,i)=>o.localeCompare(i));n.length>0&&t.unknownFieldPolicy==="reject"&&rt(`unknown schema fields are not allowed: ${n.join(", ")}`),n.length>0&&t.onWarning?.(`item_unknown_schema_fields:${n.join(",")}`)}function Xo(e,t={}){let r=Cm(t),n=Wo(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:wm(e.pm_format_version),source_type:E(e.source_type),type_options:RS(e.type_options),status:n,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:tS(e.dependencies),comments:xa(e.comments),notes:xa(e.notes),learnings:xa(e.learnings),files:aS(e.files),tests:mS(e.tests),test_runs:cS(e.test_runs),docs:bS(e.docs),deadline:vn(e.deadline),reminders:rS(e.reminders),events:oS(e.events),closed_at:vn(e.closed_at),completed_at:vn(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:vn(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:xS(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:NS(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:vn(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:AS(e.plan_steps),plan_decisions:IS(e.plan_decisions),plan_discoveries:TS(e.plan_discoveries),plan_validation:CS(e.plan_validation)};return DS(i,e),PS(i,r),MS(i,r),Yo(i),i}function Nm(e){return A(e,we)}function $S(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 jS(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=$S(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 LS(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(`
|
|
36
|
-
`,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 $a(e,t){return Xo(e,{...t,onWarning:void 0})}function FS(e,t,r={}){let n=LS(e);n.stripped&&r.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=jS(n.content);o||(e.trimStart().startsWith("{")&&En("json_markdown","JSON front matter is not valid JSON"),En("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{En("json_markdown","JSON front matter is not valid JSON")}return Rm(s,r.requireSupportedFormat),Ma(s,t),{metadata:$a(s,r),body:yr(i)}}function zS(e,t,r={}){let n;try{n=Ca(e).value}catch{En("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(Rm(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,r.requireSupportedFormat),!Tm.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&En("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ma(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:$a(o.front_matter,r),body:yr(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"),Ma(s,t),{metadata:$a(s,r),body:yr(typeof i=="string"?i:"")}}function US(e,t={}){let r=Xo(e.metadata,t),n=Nm(r),o=yr(e.body??"");La(JSON.parse(JSON.stringify(n))),La({body:o});let i=JSON.stringify(n,null,2);return o?`${i}
|
|
37
|
-
|
|
38
|
-
${o}
|
|
39
|
-
`:`${i}
|
|
40
|
-
`}var HS=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function ja(e,t){return typeof e=="string"?Sm(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Om(e.map((r,n)=>()=>ja(r,`${t}[${n}]`))):Om(Object.entries(e).map(([r,n])=>()=>{let o=t?`${t}.${r}`:r;return Sm(r,`${o} (key)`)??ja(n,o)}))}function Sm(e,t){let r=e.search(HS);return r<0?null:{path:t,index:r}}function Om(e){for(let t of e){let r=t();if(r!==null)return r}return null}function La(e){let t=ja(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 qS(e,t={}){let r=Xo(e.metadata,t),n=Nm(r),o=yr(e.body??""),i={...n,body:o},s=JSON.parse(JSON.stringify(i));La(s);let a=Rk(s),c;try{c=Ca(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(!vm(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!vm(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}
|
|
41
|
-
`}function DM(e,t={}){let r=Go(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=Cm(t);return n==="toon"?zS(e,o,t):FS(e,o,t)}function PM(e,t={}){return(t.format??"toon")==="toon"?qS(e,t):US(e,t)}function gr(e,t={}){return{metadata:Xo(e.metadata,t),body:yr(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 Dm(e){return e}import{AsyncLocalStorage as VS}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 Ua=new VS,Pm=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Jo(e,t){let r=typeof e=="string"?e.trim():"";return r.length>0?r.slice(0,t):void 0}function Ct(e,t){if(e===void 0)return;let r=typeof e=="object"&&e!==null?e:{},n=Jo(r.id,128),o=Jo(r.parent_id,128);if(n===void 0||!Pm.test(n)||o!==void 0&&!Pm.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Jo(r.label,256);return{id:n,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function br(e){let t={};for(let[r,n]of Object.entries(e??{}).slice(0,32)){let o=r.trim().toLowerCase().slice(0,64),i=Jo(n,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function BS(e,t,r){let n=Ua.getStore(),o=br({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Ct(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={...br(n?.provenance),...o,...br(e?.provenance)},a=Ct(e?.episode,!1)??Ct(r,!1)??i??Ct(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 Ha(e,t){return BS(e.session_context,t,e.client_info?.episode)??{}}function LM(e,t){let r=Ua.getStore(),n=Ct(e.episode,!0),o=Ct(r?.episode,!1),i=n!==void 0&&n.parent_id===void 0&&o!==void 0?{...n,parent_id:o.id}:n,s={...br(r?.provenance),...br(e.provenance)};return Ua.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function FM(e){let t=br(e.provenance),r=Ct(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 Mm}from"node:crypto";import{existsSync as qa,promises as $m,readFileSync as WS}from"node:fs";import Te 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 GS="session.json";function Va(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function jm(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=Va(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=>Va(c,128)),a=t.focused_item_id===void 0||Va(t.focused_item_id,128);if([r,n,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function KS(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([r,n])=>{let o=jm(n);return o&&r.length<=128?[[r,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Ba(e){return Te.join(Vi(e),GS)}async function Lm(e){try{let t=await $m.readFile(Ba(e),"utf8"),r=JSON.parse(t);if(r===null||typeof r!="object"||Array.isArray(r))return{};let n=r,o=n.focused_item,i=KS(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 Wa(e,t){let r=await ae(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let n=await Lm(e);t(n);let o=Ba(e);await $m.mkdir(Te.dirname(o),{recursive:!0}),await mt(o,JSON.stringify(n))}finally{await r()}}function Ga(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Mm("sha256").update(e).digest("hex").slice(0,24)}`}function Ka(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Ya(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)}+${Mm("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Xa(e,t,r){await Wa(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 KM(e){let t=Ga(e.principal);await Xa(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??Ya(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Ka([...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 YM(e){let t=Ga(e.principal);await Xa(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??Ya(n),confidence:o?"high":"medium",evidence:Ka([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:n}})}async function XM(e){let t=Ga(e.principal);await Xa(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??Ya(n),confidence:o?"high":"medium",rule_version:"v2",evidence:Ka([...n.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:n,...o?{focused_item_id:o}:{}}})}function YS(e,t){let r=t.PM_PATH?.trim();if(r){let o=Te.resolve(e,r);if(qa(Te.join(o,"settings.json")))return o;let i=Te.join(o,".agents","pm");if(qa(Te.join(i,"settings.json")))return i}let n=Te.resolve(e);for(let o=0;o<32;o+=1){let i=Te.join(n,".agents","pm");if(qa(Te.join(i,"settings.json")))return i;let s=Te.dirname(n);if(s===n)break;n=s}}function Fm(e){if(!e.key)return;let t=YS(e.cwd,e.env);if(t)try{let r=JSON.parse(WS(Ba(t),"utf8"));return jm(r.semantic_attribution?.[e.key])}catch{return}}async function JM(e){return(await Lm(e)).focused_item}async function ZM(e,t){await Wa(e,r=>{r.focused_item=t})}async function QM(e){await Wa(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as tc}from"node:async_hooks";import{createHash as XS}from"node:crypto";import de from"node:fs";import qm from"node:os";import Nt 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 rc=["model","effort","role","topic","version"],ei=new tc,Vm=new tc,ti=new tc,nc=[{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:[]}],Bm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),JS=Object.freeze({...Bm,max_bytes:4194304}),Ja=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function ZS(e){let t=ot(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"?JS:Bm,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 Wm=Object.freeze(nc.filter(e=>e.harness!=="ci").map(ZS).sort((e,t)=>e.harness.localeCompare(t.harness))),xt=new Map,wr=new Map;function U(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function nt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function ot(e){let t=e.harness.trim().toLowerCase();if(!Ja.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:nt(e.environment_keys),model_environment_keys:nt(e.model_environment_keys),session_environment_keys:nt(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),nt(n)]).filter(([r])=>Ja.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"&&Ja.test(r[0])&&(r[1]==="ai_agent_version"||r[1]==="claude_session_file"||r[1]==="codex_session_file"))),provenance_unavailable_dimensions:nt(e.provenance_unavailable_dimensions).map(r=>r.toLowerCase()),argv_markers:nt(e.argv_markers).map(r=>r.toLowerCase()),client_names:nt(e.client_names).map(r=>r.toLowerCase())}}var Gm=nc.map(ot);function QS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Qo(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function oc(e=[]){let t=new Map(nc.filter(o=>o.harness!=="ci").map(o=>[o.harness,ot(o)]));for(let{adapter:o}of xt.values())t.set(o.harness,ot(o.descriptor));let r=[...t.values(),...Gm.filter(o=>o.harness==="ci"),...[...wr.values()].map(o=>o.descriptor),...ti.getStore()?.descriptors??[],...e.map(ot)],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 ic(e,t){for(let r of t??[]){let n=U(e[r]);if(n)return n.slice(0,256)}}function eO(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 Km(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 U(n[o+1])?.slice(0,256);let s=r.find(a=>i.startsWith(`${a}=`));if(s)return U(i.slice(s.length+1))?.slice(0,256)}}var tO=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Rt(e,t){if(e!=="role"||t===void 0)return t;let r=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return tO.has(r)?r:void 0}function Za(e,t){return U(e?.[t])?.slice(0,256)}var rO=1048576,ec=4194304,Zo=new Map,zm=Object.freeze({}),Qa=new Map,Um=Object.freeze({});function Hm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function nO(e){let t;try{t=JSON.parse(e)}catch{return Um}let r=Hm(t);if(!r)return Um;let n=[{value:r,depth:0}],o=0,i,s;for(;n.length>0&&o<64;){let a=n.shift();if(o+=1,i??=U(a.value.model)?.slice(0,256),s??=U(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Hm(c);d&&n.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function Ym(e){try{return de.lstatSync(e).isFile()?"available":"missing"}catch(t){return Se(t)?"missing":"failed"}}function oO(e,t){let r;try{r=de.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Nt.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:Ym(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 Xm(e,t){let r=U(t.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return{status:"unavailable"};let n=Nt.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Nt.join(e.home_dir??qm.homedir(),".claude","projects"),i=Nt.join(o,n,`${r}.jsonl`),s=U(e.session_file),a=s&&Nt.basename(s)===`${r}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=Ym(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return oO(o,r)}function iO(e,t,r){let n=Xm(t,r);if(n.status==="available")try{let o=de.openSync(n.path,de.constants.O_RDONLY|de.constants.O_NOFOLLOW);try{let i=de.fstatSync(o),s=`${n.path}\0${i.size}\0${i.mtimeMs}`,a=Qa.get(s);if(a)return a[e];let c=Math.min(i.size,rO),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);de.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&de.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
|
|
42
|
-
`):[...u.toString("utf8").split(`
|
|
43
|
-
`).slice(0,4096),...f.toString("utf8").split(`
|
|
44
|
-
`).slice(-4096)];for(let w of _){if(w.length===0||w.length>262144)continue;let v=nO(w);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return Qa.clear(),Qa.set(s,y),y[e]}finally{de.closeSync(o)}}catch{return}}function sO(e,t){let r=0,n=(o,i)=>{if(i>4||r>=512)return;let s;try{s=de.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=Nt.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 aO(e){if(e<=ec)return[{offset:0,length:e}];let t=Math.floor(ec/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function cO(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??=U(o?.model)?.slice(0,256),e.effort??=U(o?.effort)?.slice(0,256)}function dO(e,t){let r={},n=4096;for(let o of aO(t)){let i=Buffer.alloc(o.length);de.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
|
|
45
|
-
`).reverse().slice(0,n);n-=s.length;for(let a of s)if(cO(r,a),r.model&&r.effort)break;if(r.model&&r.effort||n<=0)break}return r}function lO(e,t,r){let n=U(r.CODEX_THREAD_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return;let o=Nt.join(t.home_dir??qm.homedir(),".codex","sessions"),i=`${o}\0${n}`,s=Zo.get(i);if(s)return s[e];let a=sO(o,n);if(!a){Zo.set(i,zm);return}try{let c=de.openSync(a,"r");try{let d=de.fstatSync(c).size,l=dO(c,d);return Zo.set(i,l),l[e]}finally{de.closeSync(c)}}catch{Zo.set(i,zm);return}}function uO(e,t,r,n){let o=ti.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(U(r.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=n?.provenance_resolvers[e];if(i==="claude_session_file")return iO(e,t,r);if(i==="codex_session_file")return lO(e,t,r);if(i==="ai_agent_version"){let s=U(r.AI_AGENT);return!s||!n||!Qo(s,n.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function fO(e,t,r,n){if(e==="ai_agent_version"){let o=U(n.AI_AGENT);return o!==void 0&&Qo(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?U(n.CODEX_THREAD_ID)!==void 0?"available":"unavailable":Xm(r,n).status}function sc(e){return e||(Vm.getStore()??{env:process.env,argv:process.argv})}function mO(e,t,r,n){let o=e.environment_keys.some(a=>U(t[a])!==void 0),i=e.argv_markers.some(a=>r.some(c=>{let d=c.replaceAll("\\","/");return Qo(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>n===a||Qo(n,a));return o||i||s}function pO(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 _O(e){let t=e.find(([r])=>r!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function yO(e,t,r,n,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...rc,...Object.keys(n?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=Rt(e,U(r[s])?.slice(0,256)),l=Rt(e,Km(t.argv??[],e)),d=Rt(e,eO(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=Za(o?.provenance,e),_=Rt(e,ic(r,u[e])),y=Rt(e,Za(f,e)),w=Rt(e,Za(t.provenance,e)),v=uO(e,t,r,n);return _O([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[w,"host"],[v,"probe"]])??pO(e,i)??(d?{value:d,source:"argv"}:void 0)}function hO(e,t){if(!(!e||!t))return XS("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function gO(e,t,r,n,o){let i=Object.keys(r?.provenance_environment_keys??{}),s=new Set([...rc,...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=yO(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(ot),r=new Map(Gm.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=wr.get(i.harness);if(s&&!QS(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);n.add(i.harness)}for(let i of t){let s=wr.get(i.harness);wr.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=wr.get(i.harness);!s||s.registrations<=1?wr.delete(i.harness):s.registrations-=1}}}}function bO(e){let t=ot(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=U(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>ec||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(nt(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 l$(){let e=new Map(Wm.map(t=>[t.harness,t]));for(let{adapter:t}of xt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,r)=>t.harness.localeCompare(r.harness)))}function u$(e){let t=e.map(bO),r=new Map(Wm.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=xt.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=xt.get(i.harness);xt.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=xt.get(i.harness);!s||s.registrations<=1?xt.delete(i.harness):s.registrations-=1}}}}function f$(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 m$(e,t){return Vm.run(e,t)}function p$(e,t,r={}){let n=e.map(ot);return oc(n),ti.run({descriptors:n,probesEnabled:r.probesEnabled!==!1},t)}function ac(e){let t=sc(e),r=t.env??{},n=oc(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(_=>mO(_,r,o,i)),a=Ha(t,r),c=[ic(r,s?.session_environment_keys),U(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=hO(s?.harness,c),l=Fm({cwd:t.cwd??process.cwd(),env:r,key:d}),u=gO(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 wO(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function vO(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=fO(a,r,n,o);return{...wO(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 Jm(e){let t=sc(e),r=ac(t),n=oc(t.descriptors).find(d=>d.harness===r.harness),o=t.env??{},i=t.probes_enabled!==!1&&ti.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(U(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Ha(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,ic(o,n?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,Km(t.argv??[],"role")].some(d=>{let l=U(d)?.slice(0,256);return l!==void 0&&Rt("role",l)===void 0}),c=Object.fromEntries(rc.map(d=>[d,vO(d,r,n,t,o,i,d==="role"&&a)]));return{...r,provenance_outcomes:c}}function _$(){return process.env.PM_AUTHOR}function y$(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function h$(e){return ac(e).harness}function EO(e,t,r){let n=sc(r),o=ac(n);if(e!==void 0){let s=U(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(n.env?.PM_AUTHOR!==void 0){let s=U(n.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=U(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Zm(e){let t=ei.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Qm(e){let t=ei.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 g$(e){let t=ei.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function ep(e,t){let r=EO(e,t);return ei.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 kO(e,t){let r=await ge(e);if(r===null)return{raw:r,entries:[]};if(await tr({path:e,scope:"project"}),r.trim()==="")return{raw:r,entries:[]};let n=Go(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 ze(e,t){return(await kO(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 A$=1,SO=["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"],OO=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],AO=new Set(SO),IO=new Set(OO),TO=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 CO(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 vr(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:AO.has(e.op)?"maintenance":IO.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let r=CO(t);return r!==void 0&&TO.has(r)})?"maintenance":"substantive"}import Cp from"fast-json-patch";import Op from"node:fs/promises";import rA from"node:path";import j from"node:fs/promises";import V from"node:path";import{randomUUID as fc}from"node:crypto";import{createRequire as RO}from"node:module";import{setImmediate as np}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 tp(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 rp(e,t){let r=Number.parseInt(e,10);return Number.isFinite(r)&&r>=22?tp(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 xO="history-event-index.sqlite",mc="6",NO=8,lp="history-event-index",DO="history-event-index:append:",PO=5e3,pc=300,up=3e4,MO="history-event-index-invalidation",$O="history-event-index-invalidations",jO=pc*2*1e3,it=Symbol("history-index-changed"),Dt=new Map;function Mt(e){return V.join(e,"runtime",xO)}function fp(e){return V.join(e,"runtime","history-event-index-repair-deferred")}async function mp(e){try{let t=Number(await j.readFile(fp(e),"utf8")),r=Date.now()-t;return r>=0&&r<PO}catch{return!1}}async function op(e){try{await j.writeFile(fp(e),`${Date.now()}
|
|
46
|
-
`)}catch{}}function Sn(e){return V.join(e,"runtime",$O)}async function oi(e){let t=await j.readdir(Sn(e)).catch(r=>{if(le(r))return[];throw r});return{pending:t.filter(r=>r.endsWith(".pending")).sort(),committed:t.filter(r=>r.endsWith(".committed")).sort()}}async function ip(e){let t=await oi(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 ra({pid:Number(n[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(n[3])),jO))return r}return await j.rm(V.join(Sn(e),r),{force:!0}),null}))).filter(r=>r!==null),committed:t.committed}}async function lc(e,t,r=up){let n=await ae(e,MO,pc,`history-event-index-invalidation:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await n()}}async function LO(e){let t=Sn(e);await j.mkdir(t,{recursive:!0});let r=fc(),n=await ta(),o=V.join(t,`${n.pid}-${n.process_start_identity??"unknown"}-${Date.now()}-${r}.pending`);return await j.writeFile(o,`pending
|
|
47
|
-
`,{flag:"wx"}),{pendingPath:o,committedPath:V.join(t,`${r}.committed`)}}function FO(e,t){return e.length===t.length&&e.every((r,n)=>r===t[n])}async function ii(e){try{await j.rm(Mt(e),{force:!0})}catch{}}async function cc(e,t){let r=Sn(e);await j.mkdir(r,{recursive:!0}),await j.writeFile(V.join(r,`${fc()}${t?".contended":""}.committed`),`committed
|
|
48
|
-
`,{flag:"wx"}),t||await ii(e)}function si(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function uc(e,t){let r;try{return r=new t(Mt(e)),r.exec("PRAGMA busy_timeout = 0"),r.exec("BEGIN EXCLUSIVE"),!1}catch(n){return Pt(n)}finally{r?.close()}}async function sp(e,t){return t.pending.length>0||await pf(e,lp,DO)}async function pp(e,t,r=up,n="rebuild"){let o=await ae(e,lp,pc,`history-event-index:${n}:${process.pid}`,!1,!1,r,r===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function _p(e){let t=V.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=Dt.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!Dt.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=V.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 yp(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(_c)),Dt.delete(e),Dt.set(e,n),Dt.size>NO){let s=Dt.keys().next().value;Dt.delete(s)}return{events:n.ordered_events,stream_byte_sizes:new Map([...n.streams].map(([s,a])=>[s,a.byte_size]))}}async function yp(e,t){let r=await ze(e,t);for(let[n,o]of r.entries())if(typeof o.ts!="string"||!dr(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 zO(e){return(await _p(e)).events}var dc;function ci(){return dc!==void 0||(dc=rp(process.versions.node,RO(import.meta.url))),dc}function UO(e){e.exec(`
|
|
49
|
-
PRAGMA journal_mode = OFF;
|
|
50
|
-
PRAGMA synchronous = OFF;
|
|
51
|
-
CREATE TABLE metadata (
|
|
52
|
-
key TEXT PRIMARY KEY,
|
|
53
|
-
value TEXT NOT NULL
|
|
54
|
-
) STRICT;
|
|
55
|
-
CREATE TABLE events (
|
|
56
|
-
stream_id TEXT NOT NULL,
|
|
57
|
-
stream_offset INTEGER NOT NULL,
|
|
58
|
-
ts TEXT NOT NULL,
|
|
59
|
-
author TEXT NOT NULL,
|
|
60
|
-
agent_harness TEXT,
|
|
61
|
-
agent_instance TEXT,
|
|
62
|
-
op TEXT NOT NULL,
|
|
63
|
-
event_class TEXT NOT NULL CHECK(event_class IN ('substantive', 'maintenance')),
|
|
64
|
-
entry_json TEXT NOT NULL,
|
|
65
|
-
PRIMARY KEY(stream_id, stream_offset)
|
|
66
|
-
) STRICT;
|
|
67
|
-
CREATE TABLE streams (
|
|
68
|
-
stream_id TEXT PRIMARY KEY,
|
|
69
|
-
byte_size INTEGER NOT NULL CHECK(byte_size >= 0)
|
|
70
|
-
) STRICT;
|
|
71
|
-
CREATE INDEX events_order
|
|
72
|
-
ON events(ts, stream_id, stream_offset);
|
|
73
|
-
CREATE INDEX events_op_order
|
|
74
|
-
ON events(op, ts, stream_id, stream_offset);
|
|
75
|
-
CREATE INDEX events_class_stream_order
|
|
76
|
-
ON events(event_class, stream_id, ts, stream_offset);
|
|
77
|
-
CREATE INDEX events_author_order
|
|
78
|
-
ON events(author, ts, stream_id, stream_offset);
|
|
79
|
-
CREATE INDEX events_harness_order
|
|
80
|
-
ON events(agent_harness, ts, stream_id, stream_offset);
|
|
81
|
-
CREATE INDEX events_instance_order
|
|
82
|
-
ON events(agent_instance, ts, stream_id, stream_offset);
|
|
83
|
-
`),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(mc)}function hp(e,t){let r={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
|
|
84
|
-
stream_id, stream_offset, ts, author, agent_harness,
|
|
85
|
-
agent_instance, op, event_class, entry_json
|
|
86
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,r.ts,r.author,r.agent_harness??null,r.agent_instance??null,r.op,vr(r),JSON.stringify(r))}function gp(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!dr(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 bp(e,t,r){e.prepare(`INSERT INTO streams(stream_id, byte_size) VALUES (?, ?)
|
|
87
|
-
ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size`).run(t,r)}async function HO(e,t={}){let r=ci();return r?pp(e,async()=>{let n;try{n=await lc(e,()=>ip(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(n.pending.length>0||si(n)&&uc(e,r))return!1;let o=Mt(e);await j.mkdir(V.dirname(o),{recursive:!0});let i=`${o}.${fc()}.tmp`,s;try{s=new r(i),UO(s),s.exec("BEGIN IMMEDIATE");let a=await _p(e);await qO(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await lc(e,async()=>{let d=await ip(e);return d.pending.length>0||!FO(n.committed,d.committed)||si(d)&&uc(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(V.join(Sn(e),d),{force:!0}))),c||(await op(e),await j.rm(i,{force:!0})),c}catch(a){throw await op(e),s?.close(),await j.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function qO(e,t){let r=0;for(let n of t.events)hp(e,n),++r%500===0&&await np();for(let[n,o]of t.stream_byte_sizes)bp(e,n,o),++r%500===0&&await np()}function ri(e,t){return!t||t.length===0||t.includes(e)}function _c(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function ai(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function VO(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(_c(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:ai(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<ai(t.since_ts))return!1;return!0}function BO(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 WO(e,t){return!VO(e,t)||!ri(e.entry.op,t.ops)||!ri(e.entry.author,t.authors)||!ri(e.entry.agent_instance??"",t.agent_instances)||!ri(e.stream_id,t.stream_ids)||!BO(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 H$(e,t){let r=Math.max(0,Math.floor(t.limit)),n=(await zO(e)).filter(o=>WO(o,t)).slice(0,r+1);return{events:n.slice(0,t.limit),has_more:n.length>t.limit}}async function GO(e,t){let r=e.prepare("SELECT byte_size FROM streams WHERE stream_id = ?").get(V.basename(t,".jsonl")),n=0;try{n=(await j.stat(t)).size}catch(o){if(!le(o))throw o}return Number(r?.byte_size??0)===n}async function wp(e,t,r){let n=V.dirname(V.dirname(e)),o=ci(),i=!1,s=async()=>{await r(),i=!0};if(!o){await ap(n,s);return}try{await pp(n,async()=>{let a=Mt(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!==mc)throw new TypeError("Unsupported history event index version");if(!await GO(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Pt(l))throw l;await cc(n,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Pt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await cc(n,!1),await s();return}let d=!1;try{await s(),d=!0;let l=V.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);hp(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),bp(c,l,(await j.stat(e)).size),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await cc(n,Pt(l))}},0,"append")}catch(a){if(i){await ii(n);return}if(!YO(a))throw a;await ap(n,s,Pt(a))}}async function ap(e,t,r=!1){let n=!1,o;try{await lc(e,async()=>{let i=r||si(await oi(e)),s=await LO(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 ii(e)})}catch(i){if(n){await ii(e);try{await j.rm(o,{force:!0})}catch{}return}throw i}}async function yc(e){await j.rm(Mt(V.dirname(V.dirname(e))),{force:!0})}function ni(e,t,r,n){!n||n.length===0||(e.push(`${r} IN (${n.map(()=>"?").join(", ")})`),t.push(...n))}function KO(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 vp(e,t,r,n){let o;try{let i=await oi(e);if(await sp(e,i))return it;let s=await cp(e);if(i.committed.length>0)return si(i)&&uc(e,t)?it:null;if(o=new t(Mt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==mc)return null;let a=n(o);if(a===null)return null;let c=XO(o,r),d=o;o=void 0,d.close();let l=await QO([...c.keys()],e,r),u=await ZO(c,e,l),f=await oi(e);return f.committed.length>0||await sp(e,f)||s!==await cp(e)?it:u?a:null}catch(i){return Pt(i)?it:null}finally{o?.close()}}function Pt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function YO(e){return Pt(e)||e instanceof g&&e.code==="lock_conflict"}function XO(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 cp(e){let t=await j.stat(Mt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function q$(e,t){let r=ci();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=ai(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(ai(t.since_ts)));ni(n,o,"op",t.ops),ni(n,o,"author",t.authors),KO(n,o,t.harnesses,t.harness_alias_authors),ni(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);ni(n,o,"stream_id",t.stream_ids);let i=n.length===0?"":` WHERE ${n.join(" AND ")}`,s=await vp(e,r,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
88
|
-
FROM events${i}
|
|
89
|
-
ORDER BY ts, stream_id, stream_offset
|
|
90
|
-
LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(gp);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===it?null:s,repair_needed:s===null&&!await mp(e)}}function Ep(e,t){let r=Object.create(null);for(let n of e){if(!t.has(n.stream_id)||vr(n.entry)!=="substantive")continue;let o=r[n.stream_id];(o===void 0||_c(o,n)<0)&&(r[n.stream_id]=n)}return r}async function JO(e,t){if(V.basename(t)!==t)return null;try{return(await j.stat(V.join(e,"history",`${t}.jsonl`))).size}catch(r){if(le(r))return 0;throw r}}async function ZO(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=>JO(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 QO(e,t,r){if(r&&r.length>0)return[...new Set(r.filter(o=>o.trim().length>0))];let n=await j.readdir(V.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(le(o))return[];throw o});return[...new Set([...e,...n])]}async function dp(e,t,r,n){return e?vp(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
|
|
91
|
-
FROM (
|
|
92
|
-
SELECT stream_id, stream_offset, entry_json,
|
|
93
|
-
ROW_NUMBER() OVER (
|
|
94
|
-
PARTITION BY stream_id
|
|
95
|
-
ORDER BY ts DESC, stream_offset DESC
|
|
96
|
-
) AS recency_rank
|
|
97
|
-
FROM events
|
|
98
|
-
WHERE event_class = 'substantive'
|
|
99
|
-
AND stream_id IN (${a.map(()=>"?").join(", ")})
|
|
100
|
-
)
|
|
101
|
-
WHERE recency_rank = 1`).all(...a).map(gp);if(c.includes(null))return null;i.push(...c)}return Ep(i,n)}):null}async function V$(e,t){let r=[...new Set(t.filter(a=>a.trim().length>0&&V.basename(a)===a))];if(r.length===0)return{};let n=new Set(r),o=ci(),i=await dp(o,e,r,n);if(i!==null&&i!==it)return i;if(o&&i!==it&&!await mp(e))try{if(await HO(e,{lockWaitMs:0})){let a=await dp(o,e,r,n);if(a!==null&&a!==it)return a}}catch{}let s=[];return await Promise.all(r.map(async a=>{let c=V.join(e,"history",`${a}.jsonl`);(await yp(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})})})),Ep(s,n)}import hc from"node:fs/promises";import Er 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 eA=Er.join("runtime","history-drift-cache.json"),kp={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 Sp(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function tA(e){let t=Er.join(e,eA),r=!1,n="invalid_cache_path";try{r=(await hc.stat(await hc.realpath(e))).isDirectory()}catch(o){let i=Sp(o);n=i===void 0?"unknown":kp[i]??"filesystem_error"}if(!r){yn(`[pm] warning: history_drift_cache_invalidation_failed:${n}
|
|
102
|
-
`);return}try{await hc.rm(t,{force:!0})}catch(o){let i=Sp(o);if(le(o))return;let s=i===void 0?"unknown":kp[i]??"filesystem_error";yn(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
103
|
-
`)}}async function di(e){let t=Er.dirname(Er.resolve(e));Er.basename(t)==="history"&&await tA(Er.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 nA={front_matter:{},body:""},$t=3,On=[1,2,3],oA=1,iA=[1];function Rp(e){return et(R(e),e.hash_algorithm)}function kr(e){return Qn(R(e))}function pj(e){return Qn(R(e))}function vc(e){let t={...e,record_hash_version:oA},{record_hash:r,...n}=t;return{...t,record_hash:Rp(n)}}function fi(e){try{It(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(!iA.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...r}=e;return Rp(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:kr(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 xp(e,t,r={}){let n=fi(e);if(!n.ok)throw new TypeError(n.error);let o=kr(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!==kr(t.patch),s=vc({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],sA(e,r)]}:{}}),a=Ec(s);if(!a.ok)throw new TypeError(a.error);return s}function Np(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!jt(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 aA(e){return jt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&Np(e.patch)}function cA(e){let t=e.record_hash_version!==void 0,r=e.record_hash!==void 0;return t===r}function dA(e){return!jt(e)||!cA(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&&!Np(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||aA(e.record)}function lA(e){try{for(let t of e){if(!dA(t))return!1;It(t.hash_algorithm)}return!0}catch{return!1}}function uA(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&&kr(t.patch)===e.patch_hash}function fA(e,t,r){if(t.patch&&kr(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return uA(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let n=t.patch??e.patch;if(kr(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 Ec(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!lA(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=fA(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(!fi(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};r=i.entry}return{ok:!0,coverage:"complete"}}function li(e,t){return(e??"").localeCompare(t??"")}function Ap(e,t){return(e??0)-(t??0)}function st(e,t,r){return JSON.stringify(e??r).localeCompare(JSON.stringify(t??r))}function mA(e,t){return[e.scope.localeCompare(t.scope),li(e.path,t.path),li(e.command,t.command),Ap(e.timeout_seconds,t.timeout_seconds),li(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,st(e.env_clear,t.env_clear,[]),st(e.env_set,t.env_set,{}),st(e.assert_stdout_contains,t.assert_stdout_contains,[]),st(e.assert_stdout_regex,t.assert_stdout_regex,[]),st(e.assert_stderr_contains,t.assert_stderr_contains,[]),st(e.assert_stderr_regex,t.assert_stderr_regex,[]),Ap(e.assert_stdout_min_lines,t.assert_stdout_min_lines),st(e.assert_json_field_equals,t.assert_json_field_equals,{}),st(e.assert_json_field_gte,t.assert_json_field_gte,{}),li(e.note,t.note)].find(r=>r!==0)??0}function pA(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function _A(e,t){let r=pA(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:jt(n)&&Object.prototype.hasOwnProperty.call(n,o)?n[o]:void 0;if(s===void 0)return!1;n=s}return!0}function yA(e,t){let r=[],n=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!_A(n,o.path)?{...o,op:"add"}:o;r.push(i),n=Cp.applyPatch(n,[i],!0,!0).newDocument}return r}function ui(e,t,r=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let n=gr(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(mA)}:o;return{front_matter:A(i,we),body:n.body}}function Ip(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=gr(e);return{metadata:A(t.metadata,we),body:t.body}}function _j(e){return Dp(e,$t)}function Dp(e,t,r){if(!On.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return et(R(ui(e,t)),r)}function Pp(e,t,r){let n=Dp(e,t,r);return t===2?[n,et(R(ui(e,t,!0)),r)]:[n]}function yj(){return Qn(R(nA))}function An(e){let t=em(e.op),r=ui(e.before,$t),n=ui(e.after,$t),o=Ip(e.before),i=Ip(e.after),s=Cp.compare(o,i),a=yA(o,s),c=Qm(e.author),d=c.harness?Object.fromEntries(Object.entries(Jm().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??tm,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??Zm(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:et(R(r),u),after_hash:et(R(n),u),item_hash_version:$t,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return vc({...f,event_class:vr(f)})}function jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gc(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function Mp(e){let t=e.ts.trim();if(t.length===0)return $e();if(!dr(t))throw gc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw gc("History timestamp must not contain surrounding whitespace");return e.ts}function Tp(e,t){let r=e.ts;if(typeof r=="string"&&r.trim().length>0){if(!dr(r))throw gc("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function bc(e,t){let r=Mp(t);if(typeof e=="string"){let n;try{n=JSON.parse(e)}catch{return e}return jt(n)?JSON.stringify(Tp(n,r)):e}return jt(e)?JSON.stringify(Tp(e,r)):JSON.stringify(e)}async function hA(e,t,r){if(r===!1)return!0;if(typeof r=="string"){let s=bc(r,t);return await wc(e,s),await di(e),await yc(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=bc(typeof n.line=="string"?n.line:n.entry??t,t);return await wc(o,i),await di(o),await yc(o),!0}async function wc(e,t){let r;try{r=JSON.parse(t)}catch{r=null}if(!jt(r)||r.op!=="create"){await Jc(e,t);return}await Op.mkdir(rA.dirname(e),{recursive:!0});try{await Op.writeFile(e,`${t}
|
|
104
|
-
`,{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 In(e,t){let r=await rr("history_append",{history_path:e,entry:t});if(r.handled&&await hA(e,t,r.result))return;let n=t.ts.trim().length>0?t:{...t,ts:Mp(t)},o=vc({...n,hash_algorithm:It(n.hash_algorithm),event_class:vr(n)});await wp(e,o,async()=>{await wc(e,bc(o,o))}),await di(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 $p(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 Sc 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 gA={metadata:{},body:""};function mi(){return structuredClone(gA)}function Ij(e,t=$t,r){return kc(e,t,r)[0]}function kc(e,t,r){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Pp(pi(e),t,r)}catch{}let n=et(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),r);return t===2?[n,n]:[n]}function Fp(e,t,r,n,o){let i=It(n.hash_algorithm),s=`${r}:${i}`,a=o?.before.get(s)??kc(e,r,i),c=kc(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 pi(e){return{metadata:e.metadata,body:e.body}}function Tj(e,t={}){return gr(pi(e),t)}function Cj(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=gr(e);return{metadata:A(t.metadata,we),body:t.body}}function jp(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function bA(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function zp(e){return Array.isArray(e)?e.filter(bA).map(t=>({...t,path:jp(t.path),from:typeof t.from=="string"?jp(t.from):void 0})):[]}function wA(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 _i(e,t){try{let r=zp(t),n=Sc.applyPatch(structuredClone(e),r,!0,!0).newDocument;return wA(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 vA(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&On.includes(t)))]}function Up(e){return e!==void 0&&!On.includes(e)}function EA(e,t){return e!==void 0?[e]:t===void 0?[...On]:[t]}function Hp(e){let t=fi(e);if(!t.ok)return t.error;let r=Ec(e);return r.ok?void 0:r.error}function kA(e,t){let r=Hp(e);if(r)return{ok:!1,error:r};let n=_i(t,e.patch);return n.ok?{ok:!0,document:n.document}:{ok:!1,error:"patch_apply_failed"}}function SA(e,t){let r=Hp(e);if(r)throw new TypeError(`${r}:entry_${t+1}`)}function OA(e,t,r,n,o){let i=[];for(let s of r){let a=Fp(e,t,s,n,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function qp(e){let t=mi(),r=new Map,n,o,i=$p(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=Up(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=kA(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=EA(c,o),f={before:r,after:new Map},m=OA(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 Lt(e){let t=qp(e);return{ok:t.ok,errors:t.errors}}function Lp(e,t){try{return{ok:!0,document:Sc.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function AA(e,t){let r=structuredClone(e),n=0,o=0;for(let s of zp(t)){let a=Lp(r,s);if(a.ok){r=a.document;continue}if(s.op==="replace"){let c=Lp(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 IA(e){let t=vA(e);if(t.length===1)return t[0];let r=qp(e);return r.ok&&r.item_hash_version!==void 0?r.item_hash_version:t.length===0?1:$t}function TA(e,t,r=t.patch){let n=_i(e,r);if(n.ok)return{next:n.document,patch:r,repaired:R(r)!==R(t.patch),converted:0,skipped:0};let o=AA(e,r);return{next:o.document,patch:Sc.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function CA(e,t,r){return TA(e,t,r.projectPatch?.(t,e))}function Rj(e,t=IA(e),r={}){let n=e.findIndex(m=>Up(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=mi(),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];SA(_,m);let y=CA(o,_,r),{next:w,patch:v,repaired:C,converted:K,skipped:Ee}=y;d+=K,l+=Ee,c+=Number(C);let ke=Fp(o,w,t,_);u===void 0||r.continuousHashSurface!==!0?u=[ke.pairIndex,ke.beforeIndex,ke.afterIndex,Math.min(u??0,ke.beforeHashes.length-1)].find(x_=>x_>=0):u=Math.min(u,ke.beforeHashes.length-1);let Hc=ke.beforeHashes[u],qc=ke.afterHashes[u],Ti=Hc!==_.before_hash||qc!==_.after_hash;Ti&&(a+=1);let Ht={..._,patch:v,before_hash:Hc,after_hash:qc};f?Ht.item_hash_version=t:delete Ht.item_hash_version;let R_=Ht.item_hash_version!==_.item_hash_version;(Ti||C||R_)&&(Ht=xp(_,Ht,{retainOriginalPatch:C})),i.push(Ht),s.push({index:m+1,rehashed:Ti,patch_repaired:C,converted_replace_to_add:K,skipped_ops:Ee}),o=w}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function xj(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
105
|
-
`)}
|
|
106
|
-
`}import Vp from"node:fs/promises";import Sr 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 at="_workspace";function Ft(e){return Sr.join(e,"history",`${at}.jsonl`)}function Oc(e,t){return{metadata:{id:at,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 zt(e,t=e.length){let r=mi();for(let n of e.slice(0,t))r=_i(r,n.patch).document;return pi(r)}function Or(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Ar(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 yi(e,t){let r=Sr.resolve(t),n=Sr.relative(e,r).replaceAll("\\","/");if(n.length===0||n===".."||n.startsWith("../")||Sr.isAbsolute(n))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:n,absolutePath:r}}async function Vj(e){let t=await ze(Ft(e),at),r=Lt(t);r.ok||Ar(r.errors);let n=Or(t.length===0?Cr:zt(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(n).sort()){let d;try{let l=yi(e,Sr.resolve(e,c));if(d=await ge(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 Bp(e){let t=Ft(e.pmRoot),r=await ze(t,at),n=Lt(r);n.ok||Ar(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=$e(),s=r.length===0?Cr:zt(r),a=Or(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=Oc({...a,[e.documentPath]:e.after},r.length===0?i:s.metadata.created_at),l=An({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 In(t,l),{entry:l,historyPath:t}}async function Bj(e){let t=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Bp(e)}finally{await t()}}async function Wj(e){let t=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=Ft(e.pmRoot),n=await ze(r,at),o=Lt(n);o.ok||Ar(o.errors);let i=n.length===0?Cr:zt(n),s=An({nowIso:$e(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await In(r,s),{entry:s,historyPath:r}}finally{await t()}}async function Wp(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 Bp({pmRoot:e.pmRoot,documentPath:Sr.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 Vp.rm(e.filePath,{force:!0}):await mt(e.filePath,t),o}return!0}async function Gp(e){let{documentPath:t}=yi(e.pmRoot,e.filePath),r=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await ge(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await ze(Ft(e.pmRoot),at),s=Lt(i);s.ok||Ar(s.errors);let a=Or(i.length===0?Cr:zt(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 Wp({...e,raw:o.raw},n),result:o.result}}finally{await r()}}async function Gj(e){let t=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Wp(e,await ge(e.filePath))}finally{await t()}}async function Kj(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let r=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:o}=yi(e.pmRoot,e.filePath),i=Ft(e.pmRoot),s=await ze(i,at),a=Lt(s);a.ok||Ar(a.errors);let c=zt(s),d=Or(c);if(!Object.hasOwn(d,n))throw new TypeError(`Workspace history does not govern document ${n}`);let l=await ge(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=$e(),m=An({nowIso:f,author:e.author,op:e.op,before:c,after:Oc({...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 In(i,m),{changed:!0,entry:m,historyPath:i}}finally{await r()}}async function Yj(e){let t=await ae(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:n}=yi(e.pmRoot,e.filePath),o=await ze(Ft(e.pmRoot),at),i=Lt(o);if(i.ok||Ar(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=Or(zt(o,e.targetVersion))[r];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${r}`);let a=await ge(n),c=`${JSON.stringify(s,null,2)}
|
|
107
|
-
`;if(a===c)return{document_path:r,restored_from_version:e.targetVersion,changed:!1};let d=zt(o),l=$e(),u=An({nowIso:l,author:e.author,op:e.op,before:d,after:Oc({...Or(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 In(Ft(e.pmRoot),u)}catch(f){throw a===null?await Vp.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 YA}from"node:async_hooks";import{lstat as XA,realpath as n_}from"node:fs/promises";import o_ 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 _e={ok:!1},b=e=>typeof e=="string"?{ok:!0,value:e}:_e,x=e=>typeof e=="boolean"?{ok:!0,value:e}:_e;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?_e:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:_e}function k(e,t){return r=>{if(!Array.isArray(r)||t!==void 0&&r.length>t)return _e;let n=[];for(let o of r){let i=e(o);if(!i.ok)return _e;n.push(i.value)}return{ok:!0,value:n}}}function Ic(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}:_e}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function hi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return _e;let r={};for(let[n,o]of Object.entries(t)){let i=e(o);if(!i.ok)return _e;r[n]=i.value}return{ok:!0,value:r}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return _e;let r=t,n={};for(let[o,i]of Object.entries(e)){let s=i(r[o]);if(!s.ok)return _e;s.value!==void 0&&(n[o]=s.value)}return{ok:!0,value:n}}}var RA=I({key:b,values:k(b),required:p(x),aliases:p(k(b)),description:p(b)}),xA=I({command:N("create","update"),option:b,required:p(x),visible:p(x),enabled:p(x)}),NA=I({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(RA)),command_option_policies:p(k(xA))}),DA=I({id:b,aliases:p(k(b)),roles:p(k(N(...Vn))),description:p(b),order:p(L())}),PA=I({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(...Wt)),commands:p(k(N(...Bn))),repeatable:p(x),required:p(x),required_on_create:p(x),required_types:p(k(b)),allow_unset:p(x)}),MA=e=>{if(!Array.isArray(e)||e.length!==2)return _e;let[t,r]=e;return typeof t!="string"||typeof r!="string"?_e:{ok:!0,value:[t,r]}},$A=I({type:b,allowed_transitions:k(MA)}),jA=p(I({version:p(L({int:!0})),files:p(I({types:p(b),statuses:p(b),fields:p(b),workflows:p(b)})),statuses:p(k(DA)),fields:p(k(PA)),workflow:p(I({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($A)),unknown_field_policy:p(N(...Wn))})),LA=p(I({preset:p(N(...od)),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}))})),FA=I({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))}),Ac=N("block","warn"),zA=e=>typeof e=="string"?Ac(e):I({global:p(Ac),project:p(Ac)})(e),UA=p(I({mode:p(N("off","warn","enforce")),trust_mode:p(N("off","warn","enforce")),pm_max_version_exceeded_mode:p(zA),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(FA))})),Ut=Ic(128),HA=I({harness:Ic(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(Ut,64)),model_environment_keys:p(k(Ut,64)),session_environment_keys:p(k(Ut,64)),provenance_environment_keys:p(hi(k(Ut,64))),provenance_resolvers:p(hi(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(Ut,64)),argv_markers:p(k(Ut,64)),client_names:p(k(Ut,64))}),qA=I({version:L({int:!0}),id_prefix:b,ids:p(I({token_length:p(L({int:!0,min:4,max:12}))})),author_default:b,agent_identity:p(I({probes_enabled:p(x),identity_vocabulary:p(I({version:L({int:!0,positive:!0}),aliases:hi(Ic(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(HA)})),mutation_guard:p(I({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:I({ttl_seconds:L({int:!0}),wait_ms:p(L({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(L({int:!0,positive:!0}))})),output:I({default_format:N("toon","json")}),ux:p(I({deprecation_hints:p(x)})),history:p(I({missing_stream:N("auto_create","strict_error"),compact_policy:p(I({enabled:p(x),max_entries:p(L({int:!0,positive:!0})),trigger:p(N("health_warn","auto"))}))})),validation:p(I({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(hi(L({int:!0,positive:!0})))})),governance:LA,workflow:p(I({definition_of_done:k(b)})),testing:p(I({record_results_to_items:x,allow_untrusted_linked_tests:p(x)})),telemetry:p(I({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(I({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(I({definitions:k(NA)})),schema:jA,context:p(I({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(I({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:I({enabled:k(b),disabled:k(b),policy:UA}),search:I({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(I({enabled:p(x),provider:p(b)})),rerank:p(I({enabled:p(x),model:p(b),top_k:p(L({int:!0,positive:!0}))})),bm25:p(I({k1:p(L()),b:p(L())}))}),providers:I({openai:I({base_url:b,api_key:b,model:b}),ollama:I({base_url:b,model:b})}),vector_store:I({adapter:p(b),collection_name:p(b),qdrant:I({url:b,api_key:b}),lancedb:I({path:b})})});function Tc(e){let t=qA(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 gi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cc(e,t,r,n=[]){if(B(e,t)&&(n.length>0||gi(r)))return r;if(B(e,r)||B(t,r))return t;if((e===void 0||gi(e))&&gi(t)&&gi(r)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(r)]);return Object.fromEntries([...i].flatMap(s=>{let a=Cc(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 VA={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Kp=120;function Rc(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Xp(e){let t=new Map;for(let[r,n]of Object.entries(e))t.set(r.toLowerCase(),n);return t}var BA=Xp(VA),Yp=new WeakMap;function WA(e){let t=Yp.get(e);if(t)return t;let r=Xp(e);return Yp.set(e,r),r}function nL(e,t){let r=(e??"").trim().toLowerCase();if(r.length===0)return Kp;if(t){let o=WA(t).get(r);if(Rc(o))return Math.floor(o)}let n=BA.get(r);return Rc(n)?Math.floor(n):Kp}function xc(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||!Rc(n)||(t[o]=Math.floor(n))}return t}import{stat as GA}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 bi=new Map;function Jp(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}async function KA(e){try{let t=await GA(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function ct(e){let t=Jp(e),r=await Promise.all(t.map(n=>KA(n)));return r.sort((n,o)=>n.path.localeCompare(o.path)),r}function Tn(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 Zp(e){return bi.get(e)}function wi(e,t){let r=Jp(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));bi.set(e,{tracked_paths:r,signatures:n,value:t.value})}function dt(e){if(e){bi.delete(e);return}bi.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]="0caecc9d-687a-5b36-b19c-2f2a9c7a1a8a")}catch{}})();var Mc=new YA;async function SL(e,t,r=()=>!0){let n=new Set([o_.resolve(e)]);try{n.add(await n_(e))}catch{}return Mc.run([...Mc.getStore()??[],[n,r]],t)}function JA(e){let t=o_.resolve(e);return Mc.getStore()?.some(([r,n])=>r.has(t)&&n())??!1}var ZA="settings:write",i_=Symbol("pm.settings.persist_source"),QA=128,eI=new Set(["off","advisory","strict"]);function Qp(e){return structuredClone(Yc[e])}function tI(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}function e_(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 rI(e){return e.preset==="custom"?e_({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):e_({preset:e.preset},e)}function nI(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),eI.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 s_(e){let t=e.governance??{},r=tI(t.preset),n=nI(t);if(r==="custom"){let s=Qp("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=Qp(r),i=n.require_close_reason??o.require_close_reason;return{preset:r,...o,...n,require_close_reason:i}}function a_(){return structuredClone(S)}function c_(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function d_(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function l_(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function u_(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function f_(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function m_(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function p_(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function __(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,QA);return t.length>0?t:S.vector_store.collection_name}function Nc(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function y_(e,t){let r=e.schema,n=Nc(r?.statuses),o=Nc(r?.fields),i=Nc(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:Ir(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:Ir(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 ki(e,t){Object.defineProperty(e,i_,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Lc(e){let t=e[i_];if(!(!t||typeof t!="object"))return t}function OL(e){let t=Lc(e);if(t){let r=structuredClone(t);r.source_settings.item_format=e.item_format,ki(e,r)}}function vi(e){let t=structuredClone(e.settings),r=Lc(e.settings);return r&&ki(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function oI(e,t,r){let n=Ie(t);return[r,ce(e,n.files.types,oe.types),ce(e,n.files.statuses,oe.statuses),ce(e,n.files.fields,oe.fields),ce(e,n.files.workflows,oe.workflows)]}async function iI(e,t,r){let n=await ct(t);wi(e,{tracked_paths:t,signatures:n,value:vi(r)})}async function sI(e,t,r){try{await iI(e,t,r)}catch{dt(e)}}function t_(e,t){return e.find(r=>r.path===t)}function aI(e,t,r){for(let n of r){let o=t_(e,n),i=t_(t,n);if(!o||!i||!Tn([o],[i]))return!1}return!0}async function Dc(e,t,r,n,o){try{let i=await ct(t);if(!aI(n,i,o)){dt(e);return}wi(e,{tracked_paths:t,signatures:i,value:vi(r)})}catch{dt(e)}}function cI(e,t){let r=Ie(e.schema),n=Ir(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=B(n,t.runtime_item_type_definitions),s=B(r.statuses,t.runtime_schema_statuses),a=B(r.fields,t.runtime_schema_fields),c=B(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Ir(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 Ce(e){return{settings:a_(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function h_(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function $c(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function g_(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:$c(e?.last_checked_files??t.last_checked_files)}}function ve(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,r)=>t.localeCompare(r))}function dI(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function lI(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function b_(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function uI(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=b_(e.sandbox_profile));let n=ve(e.allowed_capabilities),o=ve(e.blocked_capabilities),i=ve(e.allowed_surfaces),s=ve(e.blocked_surfaces),a=ve(e.allowed_commands),c=ve(e.blocked_commands),d=ve(e.allowed_actions),l=ve(e.blocked_actions),u=ve(e.allowed_services),f=ve(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 fI(e){let t=new Map;for(let r of e??[]){let n=uI(r);n&&t.set(n.name,n)}return[...t.values()].sort((r,n)=>r.name.localeCompare(n.name))}function Pc(e){return e==="block"||e==="warn"?e:void 0}function mI(e){if(typeof e=="string")return Pc(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Pc(e.global),r=Pc(e.project);return t===void 0&&r===void 0?void 0:{...t!==void 0?{global:t}:{},...r!==void 0?{project:r}:{}}}}function ye(e,t){return ve(e?.[t]??S.extensions.policy[t])}function w_(e){let t=mI(e?.pm_max_version_exceeded_mode);return{mode:dI(e?.mode),trust_mode:lI(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ye(e,"trusted_extensions"),default_sandbox_profile:b_(e?.default_sandbox_profile),allowed_extensions:ye(e,"allowed_extensions"),blocked_extensions:ye(e,"blocked_extensions"),allowed_capabilities:ye(e,"allowed_capabilities"),blocked_capabilities:ye(e,"blocked_capabilities"),allowed_surfaces:ye(e,"allowed_surfaces"),blocked_surfaces:ye(e,"blocked_surfaces"),allowed_commands:ye(e,"allowed_commands"),blocked_commands:ye(e,"blocked_commands"),allowed_actions:ye(e,"allowed_actions"),blocked_actions:ye(e,"blocked_actions"),allowed_services:ye(e,"allowed_services"),blocked_services:ye(e,"blocked_services"),extension_overrides:fI(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function v_(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 W(e,t){return e===void 0?t:e}function he(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function jc(e){return Array.isArray(e)?e:[]}function pI(e,t,r){return{...t.validation,...e.validation,parent_reference:r.parent_reference,metadata_profile:r.metadata_profile,metadata_required_fields:v_(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:xc(e.validation?.estimate_defaults_by_type)}}function _I(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 yI(e,t){return{...t.search,...e.search,default_mode:d_(e.search?.default_mode),mutation_refresh_policy:c_(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:l_(e.search?.query_expansion?.enabled),provider:u_(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:f_(e.search?.rerank?.enabled),model:m_(e.search?.rerank?.model),top_k:p_(e.search?.rerank?.top_k)}}}function hI(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:__(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function gI(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function bI(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 wI(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Ir(e){let t=(e??[]).map(n=>Xn(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 Ei(e){let t=a_(),r=s_({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:gI(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:pI(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:_I(e,t),agent_guidance:g_(e.agent_guidance??t.agent_guidance),item_types:{definitions:Ir(e.item_types?.definitions)},schema:Ie(e.schema??t.schema),context:bI(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:w_(e.extensions.policy??t.extensions.policy)},search:yI(e,t),providers:wI(e,t),vector_store:hI(e,t)}}function vI(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(he(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=jc(e.agent_identity.harness_signals).map(r=>A(he(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(he(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(he(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(he(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(he(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=jc(e.extensions.policy.extension_overrides).map(r=>A(he(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(he(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(he(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(he(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(he(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(he(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(he(e.vector_store.lancedb),["path"])}function EI(e){return{...e,locks:W(e.locks,S.locks),ids:W(e.ids,S.ids),agent_identity:W(e.agent_identity,S.agent_identity),mutation_guard:W(e.mutation_guard,S.mutation_guard),checkpoints:W(e.checkpoints,S.checkpoints),output:W(e.output,S.output),ux:W(e.ux,S.ux),history:W(e.history,S.history),validation:W(e.validation,S.validation),workflow:W(e.workflow,S.workflow),testing:W(e.testing,S.testing),telemetry:W(e.telemetry,S.telemetry),agent_guidance:W(e.agent_guidance,S.agent_guidance),item_types:W(e.item_types,S.item_types),schema:W(e.schema,S.schema),context:W(e.context,S.context),extensions:W(e.extensions,S.extensions),search:W(e.search,S.search),providers:W(e.providers,S.providers),vector_store:W(e.vector_store,S.vector_store)}}function kI(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:v_(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:xc(e.validation?.estimate_defaults_by_type)}}function SI(e){return{...S.search,...e.search,default_mode:d_(e.search?.default_mode),mutation_refresh_policy:c_(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:l_(e.search?.query_expansion?.enabled),provider:u_(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:f_(e.search?.rerank?.enabled),model:m_(e.search?.rerank?.model),top_k:p_(e.search?.rerank?.top_k)}}}function OI(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 AI(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:__(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function II(e,t,r,n){return{...e,item_format:"toon",validation:kI(e,t),governance:t,agent_guidance:g_(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:SI(e),context:OI(e),extensions:{enabled:$c(e.extensions?.enabled),disabled:$c(e.extensions?.disabled),policy:w_(e.extensions?.policy)},vector_store:AI(e)}}function E_(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)?E_(o,n):e[r]=structuredClone(n)}}function k_(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(!B(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:{};k_(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Fc=["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 r_(e,t){let r=EI(e),n=s_(r),o=Ie(r.schema),i=cI(r,t),s=II(r,n,o,i),a=A({...s,governance:rI(n)},Fc);return vI(a),a}function TI(e,t={}){let r=t.source===void 0?t.persist_source:y_(t.source.validated,Ei(t.source.validated)),n=r_(e,r);if(r){let o=Ei(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=r_(o,r);t.source!==void 0&&E_(i,t.source.validated);let s=structuredClone(t.source===void 0?r.source_settings:t.source.raw);return k_(s,i,n),`${JSON.stringify(A(s,Fc),null,2)}
|
|
108
|
-
`}return`${JSON.stringify(n,null,2)}
|
|
109
|
-
`}async function CI(e){let t;try{t=await n_(e)}catch(a){if(Se(a))return Ce();throw a}let r=Oe(t),n;try{n=await XA(r)}catch(a){if(Se(a))return Ce();throw a}if(!n.isFile())throw Ri("settings.json");let o;try{o=await Xc(r,Ri("settings.json"))}catch(a){if(Se(a))return Ce();throw a}let i;try{i=JSON.parse(o)}catch{return Ce("settings_read_invalid_json")}let s=Tc(i);return s.success?{settings:Ei(s.data),metadata:{has_explicit_item_format:h_(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:Ce("settings_read_invalid_schema")}async function S_(e){if(JA(e))return CI(e);let t=Oe(e),r=[t];await tr({path:t,scope:"project"});let n=Zp(e);if(n){let d=await ct(n.tracked_paths);if(Tn(d,n.signatures))return vi(n.value)}let o=await ct([t]),i;try{i=await ge(t)}catch{return Ce("settings_read_fs_error")}if(i===null){let d=Ce();return await Dc(e,[t],d,o,[t]),d}let s=await ct([t]);if(!Tn(o,s))return dt(e),S_(e);let a;try{a=JSON.parse(i)}catch{let d=Ce("settings_read_invalid_json");return await Dc(e,[t],d,s,[t]),d}let c=Tc(a);if(!c.success){let d=Ce("settings_read_invalid_schema");return await Dc(e,[t],d,s,[t]),d}try{let d=Ei(c.data),l=oI(e,d.schema,t);r=l;let u=await ct(l),f=await um(e,d.schema),m=await fm(e,d.schema),_=await ct(l),y={...d,item_types:{definitions:Ir([...d.item_types.definitions,...jc(m.type_definitions_from_file)])},schema:m.schema};ki(y,y_(c.data,y));let w={settings:y,metadata:{has_explicit_item_format:h_(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(v=>`runtime_schema_bootstrap_created:${v}`),...m.warnings]};return f.created_paths.length===0?Tn(u,_)?wi(e,{tracked_paths:l,signatures:_,value:vi(w)}):dt(e):dt(e),w}catch{let d=Ce("settings_read_merge_failed");return await sI(e,r,d),d}}async function AL(e){return(await S_(e)).settings}async function IL(e,t,r=ZA){let n=Oe(e),o=Lc(t),i=TI(t,{persist_source:o}),s=JSON.parse(i);try{await Gp({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(Cc(o.persisted_settings,s,c),Fc),null,2)}
|
|
110
|
-
`:i,result:void 0}},op:r,author:ep(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),o&&ki(t,{...o,persisted_settings:structuredClone(s)}),await go({path:n,scope:"project",op:r})}finally{dt(e)}}import O_ from"node:fs";import Cn from"node:path";import{createRequire as RI}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 Rn="@unbrained/pm-cli",xI=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"]),A_=new Set(["--author","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Uc=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,Ii="2026.8.31";function ie(e,t){return e.some(r=>t.includes(r.split("=",1)[0]))}function zc(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ie(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var NI={changelog:(e,t)=>{if(t[0]==="generate")return!ie(e,["--check"]);let r=e.indexOf("export");return t[0]==="export"&&(ie(e,["--output"])||r>=0&&e[r+1]!==void 0&&!e[r+1].startsWith("-"))},comments:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ie(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:zc,files:(e,t)=>ie(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ie(e,["--apply"]),health:e=>!ie(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ie(e,["--add","--delete","--edit","--file","--stdin"]),package:zc,packages:zc,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]??"")&&!(ie(e,["--infer"])&&!ie(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(r=>["clear","flush"].includes(r)),templates:(e,t)=>t[0]==="save",test:e=>ie(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ie(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 Oi(e){let t=e.match(Uc);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function ut(e,t){let r=Oi(e),n=Oi(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 Si(e){return ut(e,Ii)!==-1?3:2}function DI(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 Ai(e){try{let t=JSON.parse(O_.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function PI(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 MI(e){let t=e.split("||").map(r=>PI(r));return{bounded:t.some(r=>r.length>0),compatible:t.some(r=>r.every(n=>{let o=ut(Ii,n.version);return o!==null&&(n.inclusive?o!==1:o===-1)}))}}function I_(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let r=e[t];if(typeof r!="object"||r===null)return[];let n=r[Rn];return typeof n=="string"?[n.trim()]:[]})}function $I(e){return I_(e).flatMap(t=>{let r=/^[<!]/u.test(t)?void 0:t.match(Uc)?.[0];if(!r)return[];let n=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=MI(t);return[{version:r,constraint:n?"exact":o.bounded?"range":"minimum",...n?{}:{declaration:t},history_epoch_compatible:n?ut(r,Ii)!==-1:o.compatible}]})}function jI(e){let t=Ai(Cn.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 LI(e,t){try{let r=O_.readFileSync(Cn.join(e,t),"utf8").split(/\r?\n/u),n=r.findIndex(s=>s.includes(Rn));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(`
|
|
111
|
-
`).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Uc)?.[0]}catch{return}}function T_(e){let t=[],r=Ai(Cn.join(e,"package.json"));r&&t.push(...$I(r).map(i=>({...i,source:"package.json"})));let n=Ai(Cn.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof n=="string"&&Oi(n)&&t.push({version:n,source:"installed-package",constraint:"exact",history_epoch_compatible:Si(n)===3});let o=jI(e);o&&Oi(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:Si(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=LI(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:Si(s)===3})}return t}function PL(e,t){if(t<=1)return;let{minVersion:r,lt:n}=RI(import.meta.url)("semver"),o=I_(Ai(Cn.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?T_(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 C_(e){for(let t=0;t<e.length;t+=1){let r=e[t];if(A_.has(r)){t+=1;continue}if(!r.startsWith("-"))return{command:r.toLowerCase(),index:t}}}function FI(e){let t=C_(e);if(!t||ie(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(A_.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=NI[r];return i?i(e,o):xI.has(r)}function zI(e){let t=C_(e.argv)?.command,r=FI(e.argv),n=T_(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=Si(e.executingVersion),a=DI(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 ${Rn} ${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 ML(e){let t=zI(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 ${Rn} pin to ${Ii} 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 ${Rn} ${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{N_ as a,D_ as b,P_ as c,M_ as d,xi as e,UI as f,$_ as g,Rr as h,jn as i,HI as j,qI as k,VI as l,Ni as m,Mi as n,$i as o,YI as p,XI as q,JI as r,B_ as s,Zc as t,ZI as u,fs as v,ji as w,Qc as x,Un as y,Hn as z,oT as A,iT as B,Q_ as C,aT as D,cT as E,dT as F,td as G,lT as H,uT as I,fT as J,ed as K,rd as L,mT as M,ey as N,nd as O,Bt as P,Vn as Q,Wt as R,Bn as S,_T as T,yT as U,hT as V,Gn as W,Kn as X,gT as Y,bT as Z,wT as _,vT as $,Yn as aa,Nr as ba,Li as ca,ET as da,id as ea,kT as fa,ST as ga,OT as ha,AT as ia,sy as ja,dd as ka,pd as la,MT as ma,Hi as na,gy as oa,$T as pa,Ny as qa,Dy as ra,jT as sa,LT as ta,GT as ua,Yy as va,KT as wa,YT as xa,XT as ya,gd as za,Oe as Aa,JT as Ba,ZT as Ca,QT as Da,qi as Ea,Vi as Fa,Jn as Ga,Jy as Ha,eC as Ia,Zy as Ja,Qy as Ka,tC as La,rC as Ma,eh as Na,nC as Oa,R as Pa,B as Qa,Qn as Ra,uh as Sa,wd as Ta,Bi as Ua,ph as Va,_h as Wa,eo as Xa,Ed as Ya,hh as Za,wh as _a,uC as $a,fC as ab,Sh as bb,Oh as cb,Ah as db,hC as eb,gC as fb,Ih as gb,to as hb,bC as ib,wC as jb,Th as kb,Ch as lb,Rh as mb,Sd as nb,Gt as ob,xh as pb,vC as qb,EC as rb,kC as sb,SC as tb,OC as ub,AC as vb,IC as wb,ro as xb,no as yb,Kt as zb,F as Ab,oo as Bb,NC as Cb,io as Db,Od as Eb,Wi as Fb,Fh as Gb,zh as Hb,jr as Ib,Gi as Jb,Ki as Kb,Yi as Lb,Xi as Mb,Ji as Nb,Zi as Ob,gs as Pb,Hh as Qb,qh as Rb,Gh as Sb,Kh as Tb,Nd as Ub,Yh as Vb,es as Wb,WC as Xb,Pd as Yb,Md as Zb,so as _b,YC as $b,jd as ac,XC as bc,_l as cc,Nl as dc,Dl as ec,eg as fc,ts as gc,rg as hc,rs as ic,ns as jc,os as kc,is as lc,ss as mc,as as nc,ds as oc,ls as pc,us as qc,Vg as rc,Wg as sc,Gg as tc,tb as uc,Rx as vc,xx as wc,Nx as xc,$x as yc,Lx as zc,wb as Ac,vb as Bc,Os as Cc,Sb as Dc,Ob as Ec,Wx as Fc,yo as Gc,Gx as Hc,Kx as Ic,Yx as Jc,Xx as Kc,Jx as Lc,Zx as Mc,Qx as Nc,Xl as Oc,eN as Pc,tN as Qc,Jl as Rc,rN as Sc,ho as Tc,nN as Uc,oN as Vc,iN as Wc,sN as Xc,aN as Yc,go as Zc,cN as _c,tr as $c,dN as ad,lN as bd,uN as cd,fN as dd,mN as ed,rr as fd,bN as gd,wN as hd,rn as id,SN as jd,bo as kd,Rb as ld,xb as md,ON as nd,Ae as od,AN as pd,$b as qd,Fb as rd,Wb as sd,ou as td,au as ud,Gb as vd,Kb as wd,Yb as xd,wo as yd,CN as zd,iu as Ad,su as Bd,nr as Cd,DN as Dd,du as Ed,Eo as Fd,Qb as Gd,Ke as Hd,or as Id,Qr as Jd,ko as Kd,en as Ld,lu as Md,MN as Nd,tn as Od,Ps as Pd,nn as Qd,_w as Rd,YN as Sd,wu as Td,yw as Ud,Ow as Vd,Iw as Wd,vu as Xd,Tw as Yd,Cw as Zd,Eu as _d,Et as $d,ku as ae,XN as be,JN as ce,xs as de,Ns as ee,Io as fe,Iu as ge,Ds as he,Tu as ie,on as je,oD as ke,kt as le,vD as me,ED as ne,Vw as oe,cr as pe,kD as qe,zu as re,Jw as se,SD as te,Vu as ue,zs as ve,Ju as we,Zu as xe,Qu as ye,ef as ze,Co as Ae,Us as Be,cn as Ce,FD as De,zD as Ee,dn as Fe,Hs as Ge,Bs as He,UD as Ie,Ov as Je,HD as Ke,qD as Le,Ro as Me,Tv as Ne,Cv as Oe,KD as Pe,YD as Qe,$e as Re,je as Se,fn as Te,dr as Ue,ne as Ve,tP as We,rP as Xe,ae as Ye,Fe as Ze,Y as _e,AP as $e,ur as af,SE as bf,IP as cf,TP as df,OE as ef,CP as ff,RP as gf,xP as hf,xf as if,CE as jf,qP as kf,xE as lf,Df as mf,VP as nf,Mf as of,DE as pf,jE as qf,$f as rf,Ff as sf,zf as tf,KP as uf,JP as vf,ca as wf,ZP as xf,QP as yf,e1 as zf,t1 as Af,r1 as Bf,n1 as Cf,Hf as Df,u0 as Ef,yn as Ff,Lo as Gf,g1 as Hf,b1 as If,ba as Jf,Yf as Kf,N0 as Lf,Xf as Mf,Jf as Nf,wa as Of,Zf as Pf,M1 as Qf,Qf as Rf,$1 as Sf,em as Tf,F1 as Uf,$0 as Vf,tm as Wf,It as Xf,et as Yf,rm as Zf,tt as _f,oe as $f,ka as ag,Ie as bg,ce as cg,Z1 as dg,um as eg,fm as fg,mm as gg,Sa as hg,pm as ig,_m as jg,Q1 as kg,gm as lg,bn as mg,sM as ng,aM as og,Aa as pg,Ia as qg,dM as rg,Ta as sg,wm as tg,Sk as ug,lM as vg,Wo as wg,Ak as xg,pM as yg,Go as zg,gS as Ag,Xo as Bg,jS as Cg,DM as Dg,PM as Eg,gr as Fg,Dm as Gg,Ct as Hg,Ha as Ig,LM as Jg,FM as Kg,Ba as Lg,Lm as Mg,Ga as Ng,KM as Og,YM as Pg,XM as Qg,JM as Rg,ZM as Sg,QM as Tg,rc as Ug,nc as Vg,Wm as Wg,d$ as Xg,l$ as Yg,u$ as Zg,f$ as _g,m$ as $g,p$ as ah,ac as bh,Jm as ch,_$ as dh,y$ as eh,h$ as fh,EO as gh,g$ as hh,ep as ih,kO as jh,ze as kh,A$ as lh,SO as mh,OO as nh,vr as oh,rp as ph,HO as qh,H$ as rh,q$ as sh,V$ as th,tA as uh,di as vh,$t as wh,On as xh,oA as yh,iA as zh,Rp as Ah,kr as Bh,pj as Ch,vc as Dh,fi as Eh,xp as Fh,Ec as Gh,_j as Hh,Dp as Ih,Pp as Jh,yj as Kh,An as Lh,In as Mh,$p as Nh,gA as Oh,mi as Ph,Ij as Qh,kc as Rh,pi as Sh,Tj as Th,Cj as Uh,zp as Vh,_i as Wh,qp as Xh,Lt as Yh,IA as Zh,Rj as _h,xj as $h,at as ai,Ft as bi,Vj as ci,Bj as di,Wj as ei,Gp as fi,Gj as gi,Kj as hi,Yj as ii,Tc as ji,nL as ki,dt as li,SL as mi,JA as ni,s_ as oi,OL as pi,Ei as qi,TI as ri,S_ as si,AL as ti,IL as ui,Ii as vi,ut as wi,Si as xi,T_ as yi,PL as zi,FI as Ai,zI as Bi,ML as Ci};
|
|
112
|
-
//# sourceMappingURL=chunk-PNPE2OVJ.js.map
|