@unbrained/pm-cli 2026.8.4 → 2026.8.5
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 +2 -2
- package/CHANGELOG.md +39 -13
- package/dist/cli/error-guidance.js +4 -4
- package/dist/cli/register-structured-mutation.d.ts +2 -0
- package/dist/cli/register-structured-mutation.js +124 -12
- package/dist/cli-bundle/bundle-manifest.json +407 -407
- package/dist/cli-bundle/chunks/append-VXXGOXSG.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-QVO3VTA4.js → chunk-2WFXWAYX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NM5G7RLU.js → chunk-3FTILRJ2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VH2EAGUG.js → chunk-42E7YPLG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RB65T4RX.js → chunk-43HQQI6S.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J4EPW4GT.js → chunk-45G53IU4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PQXEB7W4.js → chunk-4VN6GS4U.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4YUBDMQM.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-D2MBVMVE.js → chunk-54FNT7U2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NRDKVOUE.js → chunk-5ZBOIPGP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3XZYTRPC.js → chunk-6MSQJOTG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GOICHIX4.js → chunk-7A5OT5J2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HTYC76A4.js → chunk-7C4PTJG6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BKMZTZYL.js → chunk-A62CYISG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5H47J5FG.js → chunk-BPELKUQD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HE3DZFN4.js → chunk-BXQLRKWF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BLINBTMX.js → chunk-CSI3WS5I.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KH4GVBMC.js → chunk-DXDREUXT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KIKLF2W4.js → chunk-E2RKBKWB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-377OOXUF.js → chunk-EGJ4JTUG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SULWTPQO.js → chunk-FPBQHMFT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V5K52PYW.js → chunk-GE4KCSZP.js} +35 -35
- package/dist/cli-bundle/chunks/{chunk-NPUJ7OLK.js → chunk-HNFD72UK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QMWUL66F.js → chunk-HWRRMBJO.js} +5 -5
- package/dist/cli-bundle/chunks/chunk-L3AZOELJ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-CGY5I2GO.js → chunk-LKDGK44W.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LN2WFEU4.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ZSH4GNBH.js → chunk-M72BKL5Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQ2WU7OY.js → chunk-MHK6LIWE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-H6FITE7D.js → chunk-NE5VRDAI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NY4T3JWN.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-DCJ6CM6F.js → chunk-OMXVBQ2N.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OPVH7SKD.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-CU5ENFNP.js → chunk-OTHLDSFP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NH35JNK5.js → chunk-PMXJEU3F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SVDH5CHC.js → chunk-Q35VBGOQ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-5PZGZMPG.js → chunk-R546TPDE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q5F6OI7C.js → chunk-RKAVWO3O.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JMKVCQSE.js → chunk-SSF4PIUR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PA5XRN2A.js → chunk-UN66FZRO.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-FQ4EFFDU.js → chunk-UP7DTVMD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NFF3JAQR.js → chunk-UZBWIUYD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2POYGY53.js → chunk-V3774P7D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-B5ZLCD5Z.js → chunk-V3EUXXOF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6S7I3UKV.js → chunk-VCKLFEUN.js} +19 -19
- package/dist/cli-bundle/chunks/{chunk-PYYPQLHC.js → chunk-VN5VITU3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-WRL4KNDL.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-UJHUR3LZ.js → chunk-XCEZYMNI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JDPKBV5P.js → chunk-YEWNL576.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OB7TRZ2G.js → chunk-YSO3YFZ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UVZREFZU.js → chunk-ZYHOB3SN.js} +2 -2
- package/dist/cli-bundle/chunks/close-VZ3OQPN5.js +2 -0
- package/dist/cli-bundle/chunks/close-many-SB4TI27P.js +2 -0
- package/dist/cli-bundle/chunks/comments-BIF3Q4KY.js +2 -0
- package/dist/cli-bundle/chunks/copy-6AI5Z57X.js +2 -0
- package/dist/cli-bundle/chunks/{create-RLLCBCXM.js → create-XLKTXTUF.js} +2 -2
- package/dist/cli-bundle/chunks/delete-ZY2VHQTP.js +2 -0
- package/dist/cli-bundle/chunks/{deps-J4ONTF4X.js → deps-ITTY3GIC.js} +2 -2
- package/dist/cli-bundle/chunks/{docs-YL2DJ4WD.js → docs-W4OSRTYR.js} +2 -2
- package/dist/cli-bundle/chunks/{files-NGNAIYKK.js → files-EOK4AZI4.js} +2 -2
- package/dist/cli-bundle/chunks/focus-DLBNWL7L.js +2 -0
- package/dist/cli-bundle/chunks/{history-compact-HW62K5XP.js → history-compact-7UGTMLL3.js} +2 -2
- package/dist/cli-bundle/chunks/{history-redact-HVBKUJOW.js → history-redact-4DZRMD6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{history-repair-OPNBH5JJ.js → history-repair-UPOSZW5R.js} +2 -2
- package/dist/cli-bundle/chunks/{learnings-F36PZXT6.js → learnings-GMRNCBS3.js} +2 -2
- package/dist/cli-bundle/chunks/{profile-N3XMWBM7.js → profile-2MUUMHRE.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-BKGHBI7Y.js → register-list-query-LR3SQ5ZF.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-SUOHFVWM.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-ARRRKOVN.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-KWV6UD77.js → register-setup-O6AYP6NP.js} +2 -2
- package/dist/cli-bundle/chunks/restore-ZVCVHTB5.js +2 -0
- package/dist/cli-bundle/chunks/{schema-4PJQMGUY.js → schema-FJ4EA3XF.js} +2 -2
- package/dist/cli-bundle/chunks/update-YHV52CSS.js +2 -0
- package/dist/cli-bundle/chunks/update-many-M6YHVNXM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-7J5TUBUJ.js +153 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ONIX2KKW.js → chunk-A7BJ5SS6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-B7LJWAZE.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QM2BIVK7.js → chunk-BIMTMOS7.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-BOGRY7M6.js → chunk-FGKY4MBE.js} +10 -10
- package/dist/cli-bundle/focused-chunks/chunk-G6ETT4QK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C2QSL62X.js → chunk-GJ2TG2CW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RO5BQFG3.js → chunk-IPWSFADF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UFCPSWIL.js → chunk-MJ7HWSFK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2VIIXOAD.js → chunk-N5XU5UVK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PG2RIZBX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OYTK4VNH.js → chunk-PIMMYG7Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-K37BB4JL.js → chunk-QVHKCI4T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SQXVGHMH.js → chunk-RUR5I3TK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SV3O7TSH.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-L6A4NVQC.js → chunk-UIL2M2NA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WVGJAD7L.js → chunk-VLYOEYML.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-W7BJEWHX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DQ4PLKEE.js → chunk-WEM2E2PE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WVIVUWVL.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y4LDYLLT.js +2 -0
- package/dist/cli-bundle/main.js +4 -4
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +28 -28
- 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 +1 -1
- 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 +1 -1
- package/dist/core/extensions/loader.js +5 -2
- package/dist/core/item/item-format.js +14 -20
- package/dist/core/shared/constants.js +3 -2
- package/dist/core/store/item-store.js +2 -2
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +12 -6
- package/dist/mcp/tool-definitions.js +14 -7
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +18 -18
- package/dist/sdk/cli-contracts/agent-output-contracts.js +51 -23
- package/dist/sdk/cli-contracts/commander-mutation-options.js +26 -2
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +28 -2
- package/dist/sdk/cli-contracts/registration-helpers.js +4 -2
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +10 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +20 -5
- package/dist/sdk/cli-contracts/tool-schema.js +4 -2
- package/dist/sdk/cli-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/cli-program.js +3 -3
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +3 -2
- package/dist/sdk/dependency-provenance.d.ts +2 -0
- package/dist/sdk/dependency-provenance.js +7 -3
- package/dist/sdk/error-code-catalog.d.ts +23 -0
- package/dist/sdk/error-code-catalog.js +25 -5
- package/dist/sdk/generated-error-code-catalog.js +499 -3
- package/dist/sdk/graph/governance.js +3 -3
- package/dist/sdk/graph/remediation.js +3 -3
- package/dist/sdk/graph/run.js +4 -8
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/index.js +4 -3
- package/dist/sdk/item-transaction.d.ts +51 -6
- package/dist/sdk/item-transaction.js +132 -22
- package/dist/sdk/lifecycle/create.d.ts +4 -0
- package/dist/sdk/lifecycle/create.js +26 -10
- package/dist/sdk/lifecycle-policy.d.ts +9 -0
- package/dist/sdk/lifecycle-policy.js +22 -9
- package/dist/sdk/merge/driver.js +6 -3
- package/dist/sdk/output-contracts.d.ts +67 -0
- package/dist/sdk/output-contracts.js +173 -0
- package/dist/sdk/package-import-adapters.js +2 -2
- package/dist/sdk/structured-mutations.d.ts +23 -0
- package/dist/sdk/structured-mutations.js +219 -10
- package/dist/sdk/workspace-snapshot.js +58 -12
- package/dist/sdk/workspace.js +30 -4
- package/docs/COMMANDS.md +40 -10
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MERGE_SAFETY.md +2 -0
- package/docs/PR_REVIEW_LOOP.md +10 -4
- package/docs/README.md +22 -22
- package/docs/RELEASING.md +3 -3
- package/docs/SCRIPTING.md +32 -9
- package/docs/SDK.md +91 -11
- package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
- package/docs/TESTING.md +25 -0
- package/docs/examples/sdk-contract-consumer/README.md +11 -1
- package/docs/examples/sdk-contract-consumer/package.json +2 -1
- package/docs/examples/sdk-contract-consumer/parse-receipt.mjs +22 -0
- package/marketplace.json +2 -2
- package/package.json +3 -2
- 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-codex/.codex-plugin/plugin.json +1 -1
- package/sdk/public-surface.json +292 -14
- package/dist/cli-bundle/chunks/append-DHBRLHHS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-2INN52SU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-6RSK4IFN.js +0 -20
- package/dist/cli-bundle/chunks/chunk-ASJJKA57.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IYAVULRN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RRQBHQOV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XBLOD5TZ.js +0 -2
- package/dist/cli-bundle/chunks/close-VLHNN6YB.js +0 -2
- package/dist/cli-bundle/chunks/close-many-LSJNZKU6.js +0 -2
- package/dist/cli-bundle/chunks/comments-AAIA6A6X.js +0 -2
- package/dist/cli-bundle/chunks/copy-Z7YMLEHN.js +0 -2
- package/dist/cli-bundle/chunks/delete-KNOHHQJM.js +0 -2
- package/dist/cli-bundle/chunks/focus-LFRCGALV.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-GU3DCECN.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-PTWH727R.js +0 -2
- package/dist/cli-bundle/chunks/restore-4HZSLILR.js +0 -2
- package/dist/cli-bundle/chunks/update-E6LPS5IV.js +0 -2
- package/dist/cli-bundle/chunks/update-many-OSIC6KRO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5MTKO7TV.js +0 -153
- package/dist/cli-bundle/focused-chunks/chunk-6GIZK7VQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AOP2WIZZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CL75YW32.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-E7OFMWGT.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-I5F5UK3Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-T5TSY36R.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-VT6BF2IX.js +0 -2
|
@@ -1,35 +1,35 @@
|
|
|
1
|
-
import*as z from"node:fs/promises";import
|
|
2
|
-
`,"utf8")}finally{await r.close()}}async function ik(e){try{await z.unlink(e)}catch(t){if(!We(t,"ENOENT"))throw t}}function We(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===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]="938c39a8-6545-5d8b-b717-69138932d528")}catch{}})();var _e=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],vn=2,co=Object.freeze({migration:"schema",validation:"schema"}),ak=Object.freeze({version:vn,capabilities:[..._e],legacy_aliases:{...co}}),Sn=["off","warn","enforce"],xn=["off","warn","enforce"],In=["none","restricted","strict"],vs=["block","warn"],Tn=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore"],Mt=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function An(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",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:[]}}(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]="8a44d44d-70c7-5321-b436-08aa6505a854")}catch{}})();var uo=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),fo=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Cn=".agents/pm",On="settings.json",lk="Closed at creation via pm create",pu=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],_u=["decisions","events","reminders","milestones","meetings","plans"],uk=[...pu,..._u],se={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},yu=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],ye=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...yu,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],mo={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},gu=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],lo={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function Ss(e){return e?[...e]:void 0}var S={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...gu],lifecycle_closure_like_blocked_reason_patterns:[...lo.blocked_reason],lifecycle_closure_like_resolution_patterns:[...lo.resolution],lifecycle_closure_like_actual_result_patterns:[...lo.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...mo.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:uo.map(e=>({...e,aliases:Ss(e.aliases),roles:Ss(e.roles)})),fields:[],workflow:{...fo},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:An()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},Lt={metadata:{},body:""},b={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5},hu=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});function fk(e){let t=(e??"").trim().toLowerCase();if(t.length===0)return"unknown";let n=hu[t];return typeof n=="string"?n:t.includes("conflict")||t.includes("locked")?"conflict":t.startsWith("unknown_")||t.startsWith("missing_required_")?"usage":t.startsWith("invalid_")||t.endsWith("_not_found")||t.includes("validation")?"validation":t.endsWith("_error")||t.endsWith("_failed")?"runtime":"unknown"}(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]="c2c9251e-86bf-5a92-acdb-581e59d269d8")}catch{}})();var w=class extends Error{exitCode;code;context;constructor(t,n,r={}){super(t),this.name="PmCliError",this.exitCode=n,this.context=r,this.code=r.code}};(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]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function bu(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function _k(e){return bu(e)??void 0}function yk(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 gk(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function Is(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Rn(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 hk(e){let t=Rn(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function bk(e,t,n){let r=Rn(e);return r===null||r<t||r>n?null:r}function wk(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function lt(e){return typeof e!="object"||e===null?null:e}function xs(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Ts(e){let t=xs(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=xs(t.default);return typeof n?.activate=="function"?n:null}function Ek(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]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function Nn(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import wu from"node:crypto";import{AsyncLocalStorage as Eu}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]="cc84ae55-6dc4-57d4-b7de-c43ae1fb4603")}catch{}})();var po=new Eu,As=1024;function ku(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.length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}async function Ik(e,t){let n=ku(e);return po.run({...n,clockReads:0,tokenReads:0},t)}function Cs(){let e=po.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 Os(e){let t=po.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>As)throw new Error(`Reproducible token length must be an integer between 0 and ${As}`);let n="";for(;n.length<e;){let r=wu.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}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]="6be1497f-a0d5-518b-bf6a-e549b18fad8a")}catch{}})();var vu=/^([+-]?)(\d+)([hdwm])$/i,Su=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,xu=/^(\d{4})(\d{2})(\d{2})$/,Iu=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Tu=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Au=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i;function He(){return Cs()??new Date().toISOString()}function Oe(e){return Number.isFinite(Date.parse(e))}var Cu=1e4,Dn=new Map;function Rs(e){let t=Dn.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Dn.size>=Cu&&Nn(Dn),Dn.set(e,n),n}function W(e,t){let n=Rs(e),r=Rs(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function Nk(e,t){return!(t.deadlineBefore&&(!e.deadline||W(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||W(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&W(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&W(e.updated_at,t.updatedBefore)>0||t.createdAfter&&W(e.created_at,t.createdAfter)<0||t.createdBefore&&W(e.created_at,t.createdBefore)>0)}function _o(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function yo(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 Ou(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function Ru(e){let t=[],n=d=>Ou(t,e,d),r=xu.exec(e);if(r){let[,d,l,f]=r;n(`${d}-${l}-${f}`)}let o=Iu.exec(e);if(o){let[,d,l,f,p,m,h,_,y]=o,T=h?`:${h}`:"";n(`${d}-${l}-${f}T${p}:${m}${T}${_o(_)}${yo(y)}`)}let i=Tu.exec(e);if(i){let[,d,l,f,p,m,h]=i,_=p?`:${p}`:"";n(`${d}T${l}:${f}${_}${_o(m)}${yo(h)}`)}let s=Au.exec(e);if(s){let[,d,l,f,p,m,h]=s,_=p?`:${p}`:"";n(`${d}T${l}:${f}${_}${_o(m)}${yo(h)}`)}let a=10,c=e.slice(0,a);if(Du(c)){let d=a;for(;d<e.length&&Pu(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Nu(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of Ru(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Du(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function Pu(e){return e?e===" "||e===" "||e===`
|
|
3
|
-
`||e==="\r"||e==="\f"||e==="\v":!1}function Ns(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Mu=["January","February","March","April","May","June","July","August","September","October","November","December"],Lu=/^(\d{4})-(\d{2})-(\d{2})/,$u=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Fu(e,t,n){let r=Lu.exec(t)??$u.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new w(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,b.USAGE);let c=Ns(o,i-1);if(s<1||s>c)throw new w(`Invalid ${a} value "${e}". ${Mu[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,b.USAGE)}function ju(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,Ns(i,s));return n.setUTCFullYear(i,s,a),n}function Dk(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=vu.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return ju(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()}Fu(e,r,n);let i=Nu(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Su.test(r)?"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 w(`Invalid ${s} value "${e}". ${a}`,b.USAGE)}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]="8a7dca67-8f1e-5451-b45c-4a75b1117d72")}catch{}})();var zu=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function Ds(e){return typeof e!="string"?null:zu[e.trim().toLowerCase()]??null}function Ps(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function Ms(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())}import ut from"node:fs";import ve from"node:path";import{fileURLToPath as Uu}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]="dffcc28d-16a3-53d4-ba02-5298ae7a6d63")}catch{}})();var qu="@unbrained/pm-cli";function Bu(e){try{return JSON.parse(ut.readFileSync(e,"utf8")).name===qu}catch{return!1}}function Vu(e){let t=ut.existsSync(e)&&ut.statSync(e).isDirectory()?ve.resolve(e):ve.dirname(ve.resolve(e));for(;;){let n=ve.join(t,"package.json");if(ut.existsSync(n)&&Bu(n))return t;let r=ve.dirname(t);if(r===t)return;t=r}}function Pn(e,t=[]){let n=Uu(e),r=Vu(n);return r||ve.resolve(ve.dirname(n),...t)}function jk(e,t=[]){try{let n=ve.join(Pn(e,t),"package.json");if(!ut.existsSync(n))return;let r=JSON.parse(ut.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function zk(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?ve.resolve(o.trim()):n?Pn(n,r):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]="2a2072c1-f4a7-579e-ac11-4c75758d76d3")}catch{}})();var Wu=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],Ls=Wu,ft=["draft","open","in_progress","blocked","closed","canceled"],Mn=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],mt=["string","number","boolean","string_array","array","object"],Ln=["create","update","update_many","list","search","calendar","context"],$n=["allow","warn","reject"],qk=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","supersedes","task","verifies"],Bk=["project","global"],Vk=["low","medium","high","critical"],Fn=["low","medium","high","critical"],jn=["low","medium","high"];var $s=["minimal","default","strict","custom"],Wk=["none","warn","strict"],Hk=["progressive","strict"],Kk=["off","warn","strict"],Gk=["off","warn","strict"];var zn=["daily","weekly","monthly","yearly"],$t=["mon","tue","wed","thu","fri","sat","sun"];function go(e){return $t.indexOf(e)}var Xk=["draft","research","review","approved","executing","paused","completed","superseded"],Fs=["pending","in_progress","completed","blocked","skipped","superseded"],Yk=["codex","claude-code","cursor","generic"],Jk=["related","blocks","blocked_by","depends_on","discovered_from","implements","verifies","supersedes"],Qk=["brief","standard","deep","full"],Zk=["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]="f6e82c93-54e8-53a7-94df-10a573aae933")}catch{}})();import Yu 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]="815165a9-27a7-5933-adae-c7e55330c8e4")}catch{}})();function Re(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Hu(e){let t=e.key.trim();if(t.length===0)return null;let n=Re(e.aliases),r=e.description?.trim();return{key:t,values:Re(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var Ku=e=>e,zs=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function Gu(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function Xu(e,t){let n=new Map;for(let r of e??[]){let o=Gu(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function js(e,t){return t?Re(e):void 0}function ho(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Un(e,t={}){let n=t.resolvePolicyCommand??Ku,r=e.name.trim();if(r.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=Re(e.aliases),d=(e.options??[]).map(f=>Hu(f)).filter(f=>f!==null).sort((f,p)=>f.key.localeCompare(p.key)),l=Xu(e.command_option_policies,n);return{name:r,description:ho(e.description),default_status:ho(e.default_status),folder:ho(e.folder),aliases:c.length>0?c:void 0,required_create_fields:js(e.required_create_fields,o),required_create_repeatables:js(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]="88b2ed4e-b5fd-5014-abf1-c163db033abf")}catch{}})();var Ju=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],Qu=["dep","comment","note","learning","file","test","doc"],qs=["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"],Zu=["title","description","type","status","priority","tags","body",...qs,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ef=["title","description","body","status","closeReason","priority","type","tags",...qs,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Bs={"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"},tf={...Bs},nf={...Bs},Vs=[["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"]],Ws=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Hs(e){return Object.fromEntries(e)}var rf=Hs([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Vs,["author","--author"],["message","--message"],["dep","--dep"],...Ws]),of=Hs([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Vs,...Ws,["author","--author"],["message","--message"],["force","--force"]]);function sf(e){return e.trim().replace(/^--+/,"").toLowerCase()}function af(e){return e==="create"?Zu:ef}function cf(e){return e==="create"?tf:nf}function Ks(e,t){let n=sf(t);if(n.length===0)return;let r=cf(e)[n];return r||af(e).find(o=>o.toLowerCase()===n)}function cv(e,t){return(e==="create"?rf:of)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function wo(e){let t=lf(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function df(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=Yu.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(o)||o==="."||o===".."||o.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return o}function lf(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function uf(e){return Un(e,{resolvePolicyCommand:zs})}function Ft(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function ff(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:Ft(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Ft(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function mf(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 n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,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 pf(e){if(Array.isArray(e.options))return e.options.map(t=>ff(t)).filter(t=>t!==null)}function _f(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>mf(t)).filter(t=>t!==null)}function yf(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=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:n,description:o,default_status:i,folder:r,aliases:Ft(t,"aliases"),required_create_fields:Ft(t,"required_create_fields"),required_create_repeatables:Ft(t,"required_create_repeatables"),options:pf(t),command_option_policies:_f(t)}}function gf(e,t){return e.required_create_fields?Re(e.required_create_fields):t?.required_create_fields??[]}function hf(e,t){return e.required_create_repeatables?Re(e.required_create_repeatables):t?.required_create_repeatables??[]}function bf(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function wf(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Ef(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=df(e.folder??t?.folder??wo(n)),s={name:n,folder:i,aliases:Re([...t?.aliases??[],...e.aliases??[]]),required_create_fields:gf(e,t),required_create_repeatables:hf(e,t),options:bf(e,t),command_option_policies:wf(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function Us(e,t){for(let n of e){let r=uf(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Ef(r,i))}}function kf(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=yf(o);i&&t.push(i)}}return t}function Gs(e,t=null){let n=new Map;for(let c of Ls)n.set(c.toLowerCase(),{name:c,folder:se[c],aliases:[],required_create_fields:[...Ju],required_create_repeatables:[...Qu],options:[],command_option_policies:[]});Us(e.item_types?.definitions??[],n),Us(kf(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){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(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function vf(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Sf(e,t){let n=vf(e,t);if(n)return t.by_type[n]}function xf(e,t,n,r){for(let o of r){let i=Ks(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function bo(e,t,n){if(n){e.add(t);return}e.delete(t)}function If(e,t,n,r){let o=Ks(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&bo(e.required,o,r.required),r.visible!==void 0&&bo(e.hidden,o,!r.visible),r.enabled!==void 0&&bo(e.disabled,o,!r.enabled)}function Tf(e,t,n){for(let r of t.command_option_policies)r.command===n&&If(e,t,n,r)}function Af(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function dv(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return xf(a,e,t,n),Tf(a,e,t),Af(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function Cf(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function Of(e,t,n){let r=e.values;if(r.length===0)return t;let i=new Map(r.map(s=>[s.toLowerCase(),s])).get(t.toLowerCase());if(!i){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return i}function lv(e,t,n){let r=Sf(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Cf(r),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),f=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(f.length===0){o.push(`type option "${l}" must not be empty`);continue}let p=i.get(l.toLowerCase());if(!p){let h=r.options.map(_=>_.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${h}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=Of(p,f,o);m!==void 0&&(s[p.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.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 Rf,readdirSync as Nf,statSync as Df}from"node:fs";import Pf from"node:os";import A 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]="c155ccd1-cf4c-57fd-9d0e-5274eb29a764")}catch{}})();var Mf={json_markdown:".md",toon:".toon"},Lf={".md":"json_markdown",".toon":"toon"},$f=new Set([".git","coverage","dist","node_modules"]),qn=[".md",".toon"];function jt(e){try{return Df(e),!0}catch{return!1}}function Xs(e){try{let t=JSON.parse(Rf(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Ff(e){let t=A.resolve(e);for(;;){let n=A.join(t,Cn),r=A.join(n,On);if(jt(r))return n;let o=A.join(t,On);if(jt(o)&&Xs(o))return t;let i=A.dirname(t);if(i===t)return;t=i}}function jf(e){return Ff(e)??A.resolve(e,Cn)}function gv(e,t){let n=t?A.resolve(t):void 0;try{return Nf(A.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!$f.has(r.name)).map(r=>A.join(A.resolve(e),r.name)).filter(r=>r!==n).filter(r=>jt(Ke(r))).filter(r=>Xs(Ke(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function hv(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=A.resolve(e,r);if(!jt(Ke(o))){let i=A.join(o,Cn);if(jt(Ke(i)))return i}return o}return jf(e)}function bv(e){let t=A.resolve(e),n=A.dirname(t);return A.basename(t)==="pm"&&A.basename(n)===".agents"?A.dirname(n):t}function Ys(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:A.join(Pf.homedir(),".pm-cli");return A.resolve(e,n)}function Ke(e){return A.join(e,On)}function zf(e,t,n=se){let r=n[t]??wo(t);return A.join(e,r)}function Eo(e,t,n,r="toon",o=se){return A.join(zf(e,t,o),`${n}${Mf[r]}`)}function ko(e){let t=e.replaceAll("\\","/"),n=A.posix.extname(t).toLowerCase();return Lf[n]??null}function zt(e,t){return A.join(e,"history",`${t}.jsonl`)}function Js(e,t){return A.join(e,"locks",`${t}.lock`)}function Uf(e){return A.join(e,"runtime")}function Bn(e){return A.join(Uf(e),"test-runs")}function qf(e){return A.join(Bn(e),"runs")}function wv(e,t){return A.join(qf(e),`${t}.json`)}function Bf(e){return A.join(Bn(e),"stdout")}function Vf(e){return A.join(Bn(e),"stderr")}function Ev(e,t){return A.join(Bf(e),`${t}.log`)}function kv(e,t){return A.join(Vf(e),`${t}.log`)}function Wf(e){return A.join(Bn(e),"results")}function vv(e,t){return A.join(Wf(e),`${t}.json`)}(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]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function pt(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;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 f=e[c-1]===t[l-1]?0:1,p=i[l-1]+f,m=s[l-1]+1,h=i[l]+1,_=Math.min(p,m,h);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(_=Math.min(_,o[l-2]+1)),s[l]=_,_<d&&(d=_)}if(d>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?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]="a89f0df7-e280-5ce4-8515-1f107a4aeaab")}catch{}})();var Hf=[{kind:"blocked_by",direction:"directed",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",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",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",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",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];function Hn(e){return e.trim().toLowerCase().replaceAll("-","_")}function Kf(e){if(e===void 0)return;let t=Hn(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function So(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)So(n,t);return Object.freeze(e)}for(let n of Object.values(e))So(n,t);return Object.freeze(e)}function Gf(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 Xf(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 Yf(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=Hn(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 Jf(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}`)}function Qf(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(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}var xo=class{#e=new Map;#n=new Map;constructor(t=Hf){for(let n of t)this.register(n)}register(t){let n=Yf(t);if(Jf(t,n),Qf(t,n),Gf(t,n),Xf(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Kf(t.inverse),o=[...new Set((t.aliases??[]).map(Hn))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,hierarchy:t.hierarchy??!1,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?So(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Hn(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Io(){return new xo}var Ut=Io();function Iv(e,t=Ut){return t.resolve(e)?.ordering===!0}function Zf(e,t,n,r=Ut){let o=qt(e),i=qt(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function Vn(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function em(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=Zf(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function Wn(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function qt(e){return typeof e=="string"?e.trim():""}function vo(e,t){let n=qt(e);return n&&t.has(n)?n:void 0}function tm(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Qs=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=Ut){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=em(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(Vn));for(let i of this.#r)Wn(this.#s,i.source,i),Wn(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(Wn(this.#s,i.target,i),Wn(this.#a,i.source,i))}static fromItems(t,n=Ut){let r=new Set(t.map(i=>qt(i.id)).filter(Boolean)),o=[];for(let i of t){let s=qt(i.id);if(!s)continue;let a=vo(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=vo(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=vo(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||Vn(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.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||Vn(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,f=0,p=!1;e:for(let m=0;m<d.length;m+=1){n.signal?.throwIfAborted();let h=d[m];l+=1;let _=this.#t(h.id,o,r);if(f+=_.length,h.depth>=s){_.some(y=>!a.has(y.id))&&(p=!0);continue}for(let y of _)if(!a.has(y.id)){if(c.length>=i){p=!0;break e}a.add(y.id),c.push(y.id),d.push({id:y.id,depth:h.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:f,truncated:p,nextCursor:c.at(-1)}}}shortestPath(t,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,f=0,p=!1;for(let m=0;m<a.length;m+=1){r.signal?.throwIfAborted();let h=a[m];l+=1;let _=this.#t(h.id,i,o);if(f+=_.length,h.depth>=s){_.some(y=>!d.has(y.id))&&(p=!0);continue}for(let y of _)if(!d.has(y.id)){if(c.set(y.id,h.id),y.id===n)return{value:tm(t,n,c),meta:{visitedNodes:l,inspectedEdges:f,truncated:!1}};d.add(y.id),a.push({id:y.id,depth:h.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:f,truncated:p}}}subgraph(t,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.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(Vn)},meta:r.meta}}};function Tv(e,t,n=Ut){return{source:e,target:t.id,kind:n.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]="3225f4de-aa48-55b7-a704-d93ccb3ee0f4")}catch{}})();function Bt(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ne(e){return _e.includes(e)}function Zs(e){let t=e.trim().toLowerCase();return Ne(t)?t:null}function ea(e){return e.filter(t=>!Ne(t))}function To(e){let t=e.trim().toLowerCase();return t.length===0?null:co[t]??null}function ta(e){let t=Bt([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=To(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:Bt(n),legacy_aliases:o}}function nm(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=To(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of _e){let a=pt(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function na(e,t,n){let r=_e.join(","),o=nm(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function ra(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function rm(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(m=>m.trim()).filter(m=>m.length>0),d=To(o),f=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:vn,suggested_capability:f,suggestion_source:f?d===f?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function om(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[..._e],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),f=d?.trim(),p=l?.trim().toLowerCase();!f||!p||!Ne(p)||a.push({layer:i,name:r,capability:f,allowed_capabilities:s,capability_contract_version:vn,suggested_capability:p,suggestion_source:"legacy_alias",legacy_alias_target:p})}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]="baa8b608-7f1e-5382-abe3-b1af79e46da4")}catch{}})();function Vt(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Ao(){return{overrides:[],handlers:[]}}function Co(){return{overrides:[]}}function Oo(){return{overrides:[]}}function Ro(){return{overrides:[]}}function No(){return{overrides:[]}}function Do(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[]}}(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]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function im(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function Z(e){return e?C(e):{}}function ee(e){return e?C(e):im()}function C(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]="8ba4e82a-ab38-5527-84cf-ec553f434a22")}catch{}})();var sm=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),am=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","parser_overrides","service_overrides","renderer_overrides"];function cm(e,t){for(let n of am){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>sm.has(n)?j(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function dm(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>j(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function Po(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 n={schema_version:1};if(!cm(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let i=dm(o);if(i===null)return null;n.renderer_ownership=i}return n}function Mv(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,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}}import lm 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]="83232698-197a-5aef-be7c-aa37f3c56822")}catch{}})();function um(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 fm(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Kn(o))}return n}function Kn(e){let t=um(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Kn(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Kn(r)}return fm(e)}function ae(e){return JSON.stringify(Kn(e))}function oa(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function mm(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function pm(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function _m(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!oa(o,n,r,te))return!1;return!0}function ym(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!oa([o,i],n,r,([a,c],[d,l])=>te(a,d)&&te(c,l)))return!1;return!0}function gm(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>te(n,t[r]))}function hm(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!te(e[i],t[i]))return!1}return!0}var bm=[mm,pm,_m,ym,gm];function te(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of bm){let r=n(e,t);if(r!==void 0)return r}return hm(e,t)}function Ge(e){return lm.createHash("sha256").update(e,"utf8").digest("hex")}function x(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}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]="4c40667c-1e20-5813-b2f3-eb4cb966b246")}catch{}})();var wm=5e3;async function Wt(e,t,n){let r=[];for(let o of e)try{await o.run(C(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Em(e,t){return Wt(e.beforeCommand,"beforeCommand",t)}function km(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new w(`Extension mutation guard ${t.name} returned an invalid decision.`,b.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 r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new w(`Extension mutation guard ${t.name} returned an invalid denial.`,b.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 r.message=="string"?r.message.trim():"";throw new w(s||`Extension mutation guard ${t.name} denied ${n}.`,b.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Mo(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:C(t.before),after:t.after===null?null:C(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new w(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,b.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},wm),o.unref?.()})])}catch(i){throw i instanceof w?i:new w(`Extension mutation guard ${n.name} failed before ${t.operation}.`,b.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}km(r,n,t.operation)}}async function vm(e,t){return Wt(e.afterCommand,"afterCommand",t)}async function Lo(e,t){return Wt(e.onWrite,"onWrite",t)}async function $o(e,t){return Wt(e.onRead,"onRead",t)}async function Fo(e,t){return Wt(e.onIndex,"onIndex",t)}function Sm(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 n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${n.slice(0,r-1)}\u2026`:n}function Gn(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?n.slice(0,300):void 0}function xm(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 jo(e,t){let n=j(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,args:C(t.args),options:C(t.options),global:C(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",xm(o)],["errorCode",Gn(o,"code")],["remediation",Gn(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:${r.layer}:${r.name}:${r.command}`],errorMessage:Sm(o),...Object.fromEntries([["errorCode",Gn(o,"code")],["remediation",Gn(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function zo(e,t){let n=j(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:C(t.args),options:Z(t.options),global:ee(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 r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:C(t.args),options:Z(t.options),global:ee(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(r.run({command:n,args:C(t.args),options:Z(t.options),global:ee(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)?C(o.args):C(t.args),s=o.options?Z(o.options):Z(t.options),a=o.global?ee(o.global):ee(t.global);return{overridden:!0,context:{command:n,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:n,args:C(t.args),options:Z(t.options),global:ee(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:${r.layer}:${r.name}:${r.command}`]}}}async function Uo(e,t){let n=[...e.overrides].reverse()[0],r={command:j(t.command),args:C(t.args),options:Z(t.options),global:ee(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},o=C(t.decision);if(!n)return{overridden:!1,context:r,decision:o,warnings:[]};try{let i=await Promise.resolve(n.run({command:r.command,args:C(r.args),options:Z(r.options),global:ee(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:C(o)}))??{},s={command:r.command,args:Array.isArray(i.args)?C(i.args):r.args,options:i.options?Z(i.options):r.options,global:i.global?ee(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:o.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:o.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:o.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:o.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:r,decision:o,warnings:[`extension_preflight_override_failed:${n.layer}:${n.name}`]}}}function ia(e){return{handled:!1,result:e.payload,warnings:[]}}function sa(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function aa(e){return{service:e.service,command:e.command?j(e.command):void 0,args:e.args?C(e.args):void 0,options:e.options?Z(e.options):void 0,global:e.global?ee(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:C(e.payload)}}function Im(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 ca(e,t){return Im(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 da(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&te(e,n.payload)}function qo(e,t){let n=sa(e,t.service);if(n.length===0)return ia(t);let r=[];for(let o of n)try{let i=aa(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(da(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=ca(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Bo(e,t){let n=sa(e,t.service);if(n.length===0)return ia(t);let r=[];for(let o of n)try{let i=aa(t),s=await Promise.resolve(o.run(i));if(da(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=ca(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function Vo(e,t){let n=j(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=Z(t.options),i=ee(t.global),s=r.run({command:n,args:C(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:C(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function Tm(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(C(n))}catch{return!1}}function Wo(e,t){let n=typeof t.command=="string"?j(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&Tm(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?C(t.args):[],i=Z(t.options),s=ee(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,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:C(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import Qe from"node:fs/promises";import Je from"node:path";import{pathToFileURL as Wm}from"node:url";import la 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]="624aced5-552c-5354-9e34-b96e267d34d1")}catch{}})();function Ho(e,t){let n=la.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!la.isAbsolute(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]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var Xn=mt;function Yn(e){let t=e.trim().toLowerCase();return Xn.includes(t)?t:null}function ua(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Xn)if(pt(t,r,n)!==null)return r;return null}import Am from"node:fs/promises";import Ht 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]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}catch{}})();async function fa(e,t){let n=Ht.dirname(t.manifest_path),r=Ht.relative(n,t.entry_path);if(r.startsWith("..")||Ht.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Ht.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Am.cp(n,o,{recursive:!0,force:!0}),Ht.join(o,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]="1558713a-91ea-5eef-8426-d910e0b77045")}catch{}})();function ma(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(([n,r])=>[n,r.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[n,r]of Object.entries(t.registrations))e.registrations[n].length=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]="dc9a3977-a78a-501e-b600-45e7031dcebd")}catch{}})();function Se(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function G(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 pa(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function Xe(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[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function Kt(e,t){if(Xe(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}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]="45d00ef3-870c-5f3f-89c1-6abd54c518fe")}catch{}})();function _a(e){H("registerCommand definition.action",e.action),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")}(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]="875ac35b-c6ce-5690-a05a-8e4d279a49bf")}catch{}})();var Cm=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:"--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"}]),Ko=new Set(Cm.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]="4eccf02f-7401-539f-b843-f55b63ed878c")}catch{}})();var Om=/^--[a-z0-9][a-z0-9_-]*(?:[ =](?:<[^<>]+>|\[[^[\]]+\]))?$/;function Rm(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return Ko.has(n)?"host_owned_flag_collision":Om.test(t)?null:"malformed_long_flag"}function ya(e,t){let n=[e,t].find(i=>typeof i=="string"&&Ko.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=Rm(r);return o===null?null:{token:r,failure:o}}function ga(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]="849502d0-2616-500c-96de-228c0759459d")}catch{}})();function ha(e){return typeof e=="string"?e:String(e)}function Gt(e){let n=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(n)?n.split(/[.-]/).map(r=>Number(r)):null}function Go(e,t){let n=Gt(e),r=Gt(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function ba(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=ha(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!Gt(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=Go(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function wa(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=ha(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!Gt(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=Go(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,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]="24383c0a-592e-5105-84a3-a6cfb7801281")}catch{}})();function ce(e){return typeof e!="string"?"":e.trim().toLowerCase()}function R(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function Nm(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function _t(e){return new Set((e??[]).map(t=>Nm(t)).filter(t=>t.length>0))}function Ea(e){let t=ce(e);return Sn.includes(t)?t:"off"}function ka(e){let t=ce(e);return xn.includes(t)?t:"off"}function Xt(e){let t=ce(e);return In.includes(t)?t:"none"}function Xo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return vs.includes(t)?t:void 0}function va(e){if(typeof e=="string"){let t=Xo(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Xo(e.global)??"block",project:Xo(e.project)??"block"}:{global:"block",project:"block"}}function Dm(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function P(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Pm(e){let t=ce(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?Xt(e.sandbox_profile):void 0,allowedCapabilities:R(e.allowed_capabilities),blockedCapabilities:R(e.blocked_capabilities),allowedSurfaces:_t(e.allowed_surfaces),blockedSurfaces:_t(e.blocked_surfaces),allowedCommands:R(e.allowed_commands),blockedCommands:R(e.blocked_commands),allowedActions:R(e.allowed_actions),blockedActions:R(e.blocked_actions),allowedServices:R(e.allowed_services),blockedServices:R(e.blocked_services)}}}function Sa(e){let t=new Map;for(let n of e??[]){let r=Pm(n);r&&t.set(r.name,r.normalized)}return t}function Mm(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of P([...e.allowedCapabilities,...e.blockedCapabilities]))Ne(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of P([...o.allowedCapabilities,...o.blockedCapabilities]))Ne(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(Tn);for(let o of P([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of P([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function xa(e){let t=e.extensions?.policy??{},n=R(t.allowed_capabilities),r=R(t.blocked_capabilities),o=_t(t.allowed_surfaces),i=_t(t.blocked_surfaces),s=Sa(t.extension_overrides);return{mode:Ea(t.mode),trustMode:ka(t.trust_mode),pmMaxVersionExceededMode:va(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:R(t.trusted_extensions),defaultSandboxProfile:Xt(t.default_sandbox_profile),allowedExtensions:R(t.allowed_extensions),blockedExtensions:R(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:R(t.allowed_commands),blockedCommands:R(t.blocked_commands),allowedActions:R(t.allowed_actions),blockedActions:R(t.blocked_actions),allowedServices:R(t.allowed_services),blockedServices:R(t.blocked_services),overridesByName:s,warnings:Mm({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function Ia(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:P(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:P(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:P(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:P(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:P(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:P(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:P(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:P(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:P(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:P(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:Dm(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:P(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:P(e.allowedExtensions),blocked_extensions:P(e.blockedExtensions),allowed_capabilities:P(e.allowedCapabilities),blocked_capabilities:P(e.blockedCapabilities),allowed_surfaces:P(e.allowedSurfaces),blocked_surfaces:P(e.blockedSurfaces),allowed_commands:P(e.allowedCommands),blocked_commands:P(e.blockedCommands),allowed_actions:P(e.allowedActions),blocked_actions:P(e.blockedActions),allowed_services:P(e.allowedServices),blocked_services:P(e.blockedServices),extension_overrides:t}}function Ta(e){let t=Sa(e.extension_overrides);return{mode:Ea(e.mode),trustMode:ka(e.trust_mode),pmMaxVersionExceededMode:va(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:R(e.trusted_extensions),defaultSandboxProfile:Xt(e.default_sandbox_profile),allowedExtensions:R(e.allowed_extensions),blockedExtensions:R(e.blocked_extensions),allowedCapabilities:R(e.allowed_capabilities),blockedCapabilities:R(e.blocked_capabilities),allowedSurfaces:_t(e.allowed_surfaces),blockedSurfaces:_t(e.blocked_surfaces),allowedCommands:R(e.allowed_commands),blockedCommands:R(e.blocked_commands),allowedActions:R(e.allowed_actions),blockedActions:R(e.blocked_actions),allowedServices:R(e.allowed_services),blockedServices:R(e.blocked_services),overridesByName:t,warnings:[]}}function De(e,t){return e.overridesByName.get(ce(t))??null}function yt(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function Aa(e,t,n){let r=n.trim().toLowerCase(),o=De(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return yt(i,s,r,"capability_not_allowlisted","capability_blocked")}function Lm(e,t,n){let r=De(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return yt(o,i,n,"surface_not_allowlisted","surface_blocked")}function $m(e,t,n){let r=j(n);if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return yt(i,s,r,"command_not_allowlisted","command_blocked")}function Fm(e,t,n){let r=ce(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return yt(i,s,r,"action_not_allowlisted","action_blocked")}function jm(e,t,n){let r=ce(n);if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return yt(i,s,r,"service_not_allowlisted","service_blocked")}function zm(e,t){let n=ce(t.name);return De(e,t.name)?.disabled===!0?"extension_override_disabled":yt(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Um(e,t){if(e.trustMode==="off")return null;let n=De(e,t.name),r=ce(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function qm(e,t){if(e.mode==="off")return null;let r=De(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(r==="none")return null;let o=t.permissions;if(!o)return"sandbox_permissions_missing";let i=s=>o[s]===!0;return r==="restricted"?i("process_spawn")?"sandbox_restricted_disallows_process_spawn":i("env_write")?"sandbox_restricted_disallows_env_write":null:i("process_spawn")?"sandbox_strict_disallows_process_spawn":i("network")?"sandbox_strict_disallows_network":i("fs_write")?"sandbox_strict_disallows_fs_write":i("env_write")?"sandbox_strict_disallows_env_write":null}function Jn(e,t,n,r,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}:${n.layer}:${n.name}:reason=${r}${s}`}function Ca(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=zm(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Um(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=qm(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:Jn("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:Jn("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function Oa(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=Aa(e,t,n);return r?{allowed:e.mode==="warn",warning:Jn(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Bm(e,t,n,r,o){let i=typeof r=="string"?Aa(e,t,r):null,s=Lm(e,t,n),a=o.command?$m(e,t,o.command):null,c=o.action?Fm(e,t,o.action):null,d=o.service?jm(e,t,o.service):null;return i??s??a??c??d}function Vm(e,t,n,r){let o={method:ce(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=j(r.command)),r.action&&(o.action=ce(r.action).replace(/\s+/g,"-")),r.service&&(o.service=ce(r.service)),o}function Ra(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Bm(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=Jn(e.mode==="warn"?"violation":"blocked","registration",t,a,Vm(r,n,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]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();function Na(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]="b21c2101-ceac-54b1-acaa-6c8d9c25ae8b")}catch{}})();var Hm=100,Da=null,Km=Object.freeze(An()),Pa=0;function Gm(e=Date.now()){return Pa+=1,`${Pa}-${e}`}function Ma(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function Xm(e){if(e==null)return;let t=lt(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Yo(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Ha(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function Ye(e){if(e!=null)return typeof e!="boolean"?null:e}function Ym(e){let t=Ha(e.priority);return t===void 0?Hm:t}function Jm(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=Xt(t);return n!==t.trim().toLowerCase()?null:n}function Jo(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Qm(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=Jo(t.source),r=Jo(t.signature),o=Jo(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function Zm(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=Ye(t.fs_read),r=Ye(t.fs_write),o=Ye(t.network),i=Ye(t.env_read),s=Ye(t.env_write),a=Ye(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function ep(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=ta(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function tp(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>j(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function np(e){let t=Ha(e.manifest_version);if(t===null)return null;let n=Ma(e,"pm_min_version");if(n===null)return null;let r=Ma(e,"pm_max_version");if(r===null)return null;let o=Xm(e.engines);if(o===null)return null;let i=Ye(e.trusted);if(i===null)return null;let s=Jm(e);if(s===null)return null;let a=Qm(e.provenance);if(a===null)return null;let c=Zm(e.permissions);if(c===null)return null;let d=ep(e.capabilities);if(d===null)return null;let l=tp(e.activation);if(l===null)return null;let f=Po(e.contributions);return f===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:f}}function rp(e){if(typeof e!="object"||e===null)return null;let t=e,n=Yo(t,"name");if(n===null)return null;let r=Yo(t,"version");if(r===null)return null;let o=Yo(t,"entry");if(o===null)return null;let i=Ym(t);if(i===null)return null;let s=np(t);return s===null?null:{name:n,version:r,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}}function op(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function ip(e,t){let[n,r]=await Promise.all([Qe.realpath(e),Qe.realpath(t)]);return Ho(n,r)}function sp(e,t=process.cwd()){return{global:Je.join(Ys(t),"extensions"),project:Je.join(e,"extensions")}}async function ap(e){try{return(await Qe.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort((n,r)=>n.localeCompare(r))}catch{return[]}}function cp(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 La(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function dp(e){let t=new Map;try{let n=JSON.parse(await Qe.readFile(Je.join(e,".managed-extensions.json"),"utf8")),o=lt(n)?.entries;if(!Array.isArray(o))return t;for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=La(s.source?.package),c=[s.source?.input,s.source?.name,a].map(f=>La(f)).filter(f=>f!==void 0),d=Po(s.contributions),l={aliases:[...new Set(c)],...a?{package_name:a}:{},...d?{contributions:d}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&t.set(`directory:${s.directory.trim()}`,l),typeof s.name=="string"&&s.name.trim().length>0&&t.set(`name:${s.name.trim()}`,l)}}catch{return t}return t}function $a(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function lp(e,t){let n=[...$a(e),...$a(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Fa(e,t,n,r,o){let i=[],s=[],a=[],c=await ap(t),d=await dp(t);for(let l of c){let f=await mp(e,t,l,n,r,d,o);i.push(f.diagnostic),s.push(...f.warnings),f.candidate&&a.push(f.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function up(){return{diagnostics:[],warnings:[],candidates:[]}}function ja(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function fp(e,t,n,r,o,i){let s=[];Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&s.push(ra(e,t.name,t.legacy_capability_aliases));for(let a of ea(t.capabilities))s.push(na(e,t.name,a));return n?r||s.push(`extension_entry_missing:${e}:${t.name}`):s.push(`extension_entry_outside_extension:${e}:${t.name}`),o.warning&&s.push(o.warning),i.warning&&s.push(i.warning),s}async function mp(e,t,n,r,o,i,s){let a=Je.join(t,n),c=Je.join(a,"manifest.json");if(!await ke(c))return ja(e,n,c,`extension_manifest_missing:${e}:${n}`);let d;try{let q=JSON.parse(await Qe.readFile(c,"utf8"));d=rp(q)}catch{d=null}if(!d)return ja(e,n,c,`extension_manifest_invalid:${e}:${n}`);let l=Je.resolve(a,d.entry),f=Ho(a,l),p=f?await ke(l):!1,m=f&&p?await ip(a,l):f,h=op(d.name,r,o),_=await yp(e,d),y=await gp(e,d,s),T=fp(e,d,m,p,_,y),L=m&&p&&_.allowed&&y.allowed,J=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:l,enabled:h,status:L?"ok":"warn"},warnings:T,candidate:Na({layer:e,directory:n,manifestPath:c,entryPath:l,manifest:d,sourceIdentity:J,extensionReady:L,enabledForLoad:h})}}async function pp(e){let t=sp(e.pmRoot,e.cwd??process.cwd()),n=Bt(e.settings.extensions.enabled),r=Bt(e.settings.extensions.disabled),o=xa(e.settings),i=Ia(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?up():await Fa("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Fa("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],f=lp(c.candidates,d.candidates),p=[];for(let m of f){let h={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},_=Ca(o,h);if(_.warning&&l.push(_.warning),!!_.allowed){for(let y of m.manifest.capabilities){let T=Oa(o,h,y);T.warning&&l.push(T.warning)}p.push(cp(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:p,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function tr(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function _p(){try{let e=Pn(import.meta.url,["../../.."]),t=await Qe.readFile(Je.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Ka(){return Da??=_p(),Da}function Ga(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function yp(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=ba(t.pm_min_version,await Ka()),r=Ga(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function gp(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=wa(t.pm_max_version,await Ka(),n),o=Ga(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function za(e){try{let t=await Qe.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function hp(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await fa(t.module_graph_snapshot_root,e));let r=new URL(Wm(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[i,s]=await Promise.all([za(e.entry_path),za(e.manifest_path)]),a=t.reload_token??Gm();return r.searchParams.set("pm_ext_reload",a),r.searchParams.set("pm_ext_entry",i),r.searchParams.set("pm_ext_manifest",s),r.href}async function MS(e){let t=await pp(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let c=await import(await hp(s,e));n.push({...s,module:c})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:tr(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Ua=5e3,bp=2147483647;function wp(e){let n={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let r=e.deactivate;n.deactivate=r.bind(e)}return n}function Xa(e){let t=Ts(e);return t?wp(t):null}async function LS(e,t,n={}){let r=Ep(n?.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 f=Xa(l.module);!f||typeof f.deactivate!="function"||i.push({extension:l,deactivate:f.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:f})=>{try{return await kp(f,r),{ok:!0}}catch(p){return{ok:!1,layer:l.layer,name:l.name,error:tr(p)}}})),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 Ep(e){return typeof e!="number"||e<0?Ua:e===0||e===1/0?0:Number.isFinite(e)?Math.min(bp,Math.max(1,Math.floor(e))):Ua}async function kp(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function vp(e){return e==="toon"||e==="json"}function Sp(e){return Mt.includes(e)}function gt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}function ne(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Yt(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function qa(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Ba(e,t){return j(`${e} ${t}`)}function Zn(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>Zn(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={},r=Object.keys(t).sort((o,i)=>o.localeCompare(i));for(let o of r)n[o]=Zn(t[o]);return n}return e}function er(e){if(Array.isArray(e))return e.map(t=>er(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=er(t[r]);return n}return e}var Ya=Symbol("extension_registration_trace");function Pe(e,t){let n=new TypeError(e);return Object.defineProperty(n,Ya,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function xp(e){if(e instanceof Error)return e[Ya]}function Qn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return Zn(t)}function Qo(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return er(t)}function ni(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>Qn(e,n))}var Ip=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","visible"]);function Zo(e,t){return ni(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function Tp(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Va(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 n=Tp(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Wa(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[r,o]of e.entries()){let i=Se(`registerCommand definition.arguments[${r}]`,o),s=ne(`registerCommand definition.arguments[${r}].name`,i.name);if(G(`registerCommand definition.arguments[${r}].required`,i.required),G(`registerCommand definition.arguments[${r}].variadic`,i.variadic),H(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].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 n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function ei(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=Se(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!Ip.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=r.long,s=r.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=ya(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${ga(a.token,a.failure)}`);if(H(`registerFlags flags[${t}].value_name`,r.value_name),H(`registerFlags flags[${t}].description`,r.description),G(`registerFlags flags[${t}].required`,r.required),G(`registerFlags flags[${t}].enabled`,r.enabled),G(`registerFlags flags[${t}].visible`,r.visible),G(`registerFlags flags[${t}].list`,r.list),G(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(pa(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Ap(`registerFlags flags[${t}]`,r)}}function Ap(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=Ds(n);if(r===null)throw new TypeError(`${e} value_type "${n}" 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?Ps(t.default):[t.default];for(let[i,s]of o.entries())if(!Ms(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Cp(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=Se(`registerItemFields fields[${t}]`,n);ne(`registerItemFields fields[${t}].name`,r.name);let o=ne(`registerItemFields fields[${t}].type`,r.type);if(Yn(o)===null){let i=ua(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Xn.join(", ")}).${s}`)}G(`registerItemFields fields[${t}].optional`,r.optional)}}function Op(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=Se(i,o);ne(`${i}.command`,s.command),ne(`${i}.option`,s.option),G(`${i}.enabled`,s.enabled),G(`${i}.required`,s.required),G(`${i}.visible`,s.visible)}}function Rp(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=Se(i,o);ne(`${i}.key`,s.key),Xe(`${i}.values`,s.values),G(`${i}.required`,s.required),Xe(`${i}.aliases`,s.aliases)}}function Np(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=Se(r,n);ne(`${r}.name`,o.name),H(`${r}.folder`,o.folder),Xe(`${r}.aliases`,o.aliases),Xe(`${r}.required_create_fields`,o.required_create_fields),Xe(`${r}.required_create_repeatables`,o.required_create_repeatables),Op(t,o.command_option_policies),Rp(t,o.options)}}function Dp(e){let t=Se("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(G("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 Ja=["types","statuses","fields","workflows","config","templates","packages"],Pp={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[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] 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 Mp(e){let t=Se("registerProfile profile",e);if(ne("registerProfile profile.name",t.name),ne("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 n of Ja){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);Pp[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function Lp(e){e.summary===void 0&&(e.summary="");for(let t of Ja)e[t]===void 0&&(e[t]=[]);return e}function ti(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}function $p(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Ne(r)&&t.add(r)}return t}function F(e,t,n){let r=$p(e);if(r!==null&&!r.has(t))throw Pe(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,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 ${n} registration call.`})}function Fp(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>_e.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function jp(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 ri=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,f){this.#e=t,this.extension=Fp(t),this.#n=jp(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=f,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.hooks={beforeCommand:p=>this.registerBeforeCommand(p),beforeMutation:p=>this.registerBeforeMutation(p),afterCommand:p=>this.registerAfterCommand(p),onWrite:p=>this.registerOnWrite(p),onRead:p=>this.registerOnRead(p),onIndex:p=>this.registerOnIndex(p)}}allowRegistration(t,n,r,o){let i=Ra(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:Zn(o),hint:i}}registerCommandOverride(t,n){let r=j(t);if(r.length===0)throw Pe("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Pe(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Pe("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Pe("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=j(t.name);if(n.length===0)throw Pe("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Pe(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{_a(t);let o=Va(n,t.action);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let i=t.description?.trim(),s=t.intent?.trim(),a=Kt("registerCommand definition.examples",t.examples),c=Kt("registerCommand definition.failure_hints",t.failure_hints),d=Wa(t.arguments);t.flags!==void 0&&(F(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(ei(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Zo("registerCommand definition.flags",t.flags)})));let l={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:a,failure_hints:c,arguments:d,tier:t.tier};i&&(l.description=i),s&&(l.intent=s),this.#t.commands.push(l)}catch(o){let i=tr(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Pe(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(F(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(F(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=j(ne("registerParser command",t));Yt("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){F(this.#e,"preflight","registerPreflight"),this.allowRegistration("preflight.override","registerPreflight","preflight")&&(Yt("registerPreflight override",t),this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerService(t,n){F(this.#e,"services","registerService");let r=String(t).trim().toLowerCase();if(!Sp(r))throw new TypeError(`registerService service must be one of: ${Mt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:r})&&(Yt("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:r,run:n}))}registerRenderer(t,n,r={}){if(F(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!vp(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return j(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(F(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=j(ne("registerFlags targetCommand",t));ei(n);let o=Zo("registerFlags flags",n);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:r,flags:o})}registerItemFields(t){if(F(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Cp(t);let n=ni("registerItemFields fields",t);if(n.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:n})}registerItemTypes(t){if(F(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Np(t);let n=ni("registerItemTypes types",t);if(n.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:n})}registerRelationshipKinds(t){if(F(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 n=Io();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(F(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Dp(t);let n=Qo("registerMigration definition",t);this.#t.migrations.push(ti({layer:this.#e.layer,name:this.#e.name,definition:Qn("registerMigration definition",t)},n))}registerProfile(t){if(F(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=er(t);Mp(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Lp(n)})}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))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={...r,description:r?.description??o,arguments:r?.arguments??i};H(`${t} options.action`,s.action),H(`${t} options.description`,s.description),H(`${t} options.intent`,s.intent);let a=Va(n,s.action),c=Kt(`${t} options.examples`,s.examples),d=Kt(`${t} options.failure_hints`,s.failure_hints),l=Wa(s.arguments);s.flags!==void 0&&(F(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(ei(s.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Zo(`${t} options.flags`,s.flags)})));let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:a,examples:c,failure_hints:d,arguments:l},p=s.description?.trim();p&&(f.description=p);let m=s.intent?.trim();m&&(f.intent=m),this.#t.commands.push(f)}registerImporter(t,n,r){if(F(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=qa(ne("registerImporter name",t));Yt("registerImporter importer",n);let i=Ba(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n({registration:o,action:"import",command:s.command,args:C(s.args),options:C(s.options),global:C(s.global),pm_root:s.pm_root,source_workspace_root:s.source_workspace_root,repo_root:s.repo_root,pm_root_rel:s.pm_root_rel,...s.sdk===void 0?{}:{sdk:s.sdk}})})}registerExporter(t,n,r){if(F(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=qa(ne("registerExporter name",t));Yt("registerExporter exporter",n);let i=Ba(o,"export");this.applyImportExportCommandMetadata("registerExporter",i,r),this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n({registration:o,action:"export",command:s.command,args:C(s.args),options:C(s.options),global:C(s.global),pm_root:s.pm_root,source_workspace_root:s.source_workspace_root,repo_root:s.repo_root,pm_root_rel:s.pm_root_rel,...s.sdk===void 0?{}:{sdk:s.sdk}})})}registerSearchProvider(t){if(F(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=Qo("registerSearchProvider provider",t);this.#t.search_providers.push(ti({layer:this.#e.layer,name:this.#e.name,definition:Qn("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(F(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=Qo("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(ti({layer:this.#e.layer,name:this.#e.name,definition:Qn("registerVectorStoreAdapter adapter",t)},n))}registerBeforeCommand(t){F(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){F(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){F(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){F(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){F(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){F(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 zp(e,t,n,r,o,i,s,a,c,d,l){return new ri(e,t,n,r,o,i,s,a,c,d,l)}function Up(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=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:n,item_fields:r,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}}function qp(e){let t=[],n=(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 f of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${f.layer}:${f.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.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 Bp(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Vp(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);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:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}function Wp(e){if(e.overrides.length<=1)return[];let t=e.overrides[e.overrides.length-1];return e.overrides.slice(0,-1).map(n=>`extension_preflight_override_collision:${t.layer}:${t.name}:${n.layer}:${n.name}`)}var Hp=new Set(["output_format"]);function Kp(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Hp.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function $S(e){let t=Ta(e.policy??Km),n=Vt(),r=Ao(),o=Co(),i=Oo(),s=Ro(),a=No(),c=Do(),d=[],l=[];for(let m of e.loaded){let h=Xa(m.module);if(!h)continue;let _=d.length,y=ma({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await h.activate(zp(m,n,r,o,i,s,a,c,l,d,t)),d.length>_&&(y(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(T){y(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let L=xp(T);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:tr(T),trace:L})}}let f=[...qp(r),...Vp(o),...Wp(i),...Kp(s),...Bp(a)],p=[...new Set([...l,...f])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:p,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.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:Up(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]="bd9832a9-f6a2-5351-a929-0a0d2766df88")}catch{}})();function VS(e){return{...e,hooks:Vt(),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]="3239b2c7-3ae3-5d4e-9005-b61000362304")}catch{}})();function HS(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let o=Promise.all([e,...t]).then(()=>n());return e=o.then(()=>{},()=>{}),o}}}function Gp(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.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]="3f347c0d-2e1f-5d17-9e38-bae834f845d3")}catch{}})();var Xp={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"]},Qa=":";function Za(e,t){return`${e}${Qa}${oi(t)}`}function Yp(e){return e.slice(e.indexOf(Qa)+1)}function oi(e){return e.trim().toLowerCase()}function Jp(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=Zs(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function ec(e){let t=new Map,n=(l,f)=>{for(let p of l){let m=Za(p.layer,p.name),h=t.get(m);h===void 0&&(h=new Set,t.set(m,h)),h.add(f)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function Qp(e,t={}){let n=ec(e),r=new Set;t.extensionName!==void 0&&r.add(oi(t.extensionName));for(let i of t.extensionNames??[])r.add(oi(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(Yp(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function Zp(e,t){let n=ec(t),r=[];for(let o of e){let i=Jp(o.capabilities);if(i.length===0)continue;let s=n.get(Za(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as e_}from"node:fs";import{AsyncLocalStorage as t_}from"node:async_hooks";import xe 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]="38024e6c-c1ef-5c15-8421-ac18d317e330")}catch{}})();var Me=null,Jt=null,rr=null,or=null,Qt=null,ir=null,sr=null,Ze=null,ar,nr=[],nc=new t_;function D(){return nc.getStore()}function ex(e){return nc.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var n_=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function tc(e){let t=xe.resolve(e);for(;;){if(e_(xe.join(t,".git")))return t;let n=xe.dirname(t);if(n===t)return;t=n}}function cr(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=tc(t)??xe.resolve(t),r=tc(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=xe.relative(n,xe.resolve(e)),i=o.length>0&&!o.startsWith(`..${xe.sep}`)&&o!==".."&&!xe.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(xe.sep).join("/")}:{}}}function tx(e){let t=D();if(t){t.hooks=e;return}Me=e}function nx(e){let t=D();if(t){t.commands=e;return}Jt=e}function rx(e){let t=D();if(t){t.parsers=e;return}rr=e}function ox(e){let t=D();if(t){t.preflight=e;return}or=e}function ix(e){let t=D();if(t){t.services=e;return}Qt=e}function sx(e){let t=D();if(t){t.renderers=e;return}ir=e}function ax(e){let t=D();if(t){t.registrations=e;return}sr=e}function Zt(){let e=D();return e?e.registrations:sr}function cx(){let e=D();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,Jt=null,rr=null,or=null,Qt=null,ir=null,sr=null,Ze=null,ar=null}function dx(e){let t=e?{...e,...cr(e.pm_root)}:null,n=D();if(n){n.commandContext=t;return}Ze=t}function rc(){let e=D(),t=e?e.commandContext:Ze;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function oc(e){let t=D();if(t){t.commandResult=e;return}ar=e}function lx(){let e=D();return e?e.commandResult:ar}function ii(e){if(!e)return;let t=D();t?t.affectedItems.push(e):nr.push(e)}function dr(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=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"||n_.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function ux(){let e=D(),t=e?.affectedItems??nr;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:nr=[],n}function fx(){let e=D();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,Jt=null,rr=null,or=null,Qt=null,ir=null,sr=null,Ze=null,ar=void 0,nr=[]}async function ue(e){let t=D(),n=t?t.hooks:Me;return n?Lo(n,e):[]}async function si(e){let t=D(),n=t?t.hooks:Me;n&&await Mo(n,e)}async function ge(e){let t=D(),n=t?t.hooks:Me;return n?$o(n,e):[]}function ai(){let e=D();return((e?e.hooks:Me)?.onRead?.length??0)>0}async function mx(e){let t=D(),n=t?t.hooks:Me;return n?Fo(n,e):[]}function ic(e){let t=D(),n=t?t.commands:Jt,r=t?t.commandContext:Ze;return!n||!r?{overridden:!1,result:e,warnings:[]}:Vo(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function px(e){let t=D(),n=t?t.commands:Jt;return n?jo(n,{...e,...cr(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function _x(e){let t=D(),n=t?t.parsers:rr;return n?zo(n,{...e,...cr(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 yx(e){let t=D(),n=t?t.preflight:or;return n?Uo(n,{...e,...cr(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 sc(e,t){let n=D(),r=n?n.renderers:ir,o=n?n.commandContext:Ze;return r?Wo(r,{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 ac(e,t){let n=D(),r=n?n.commandContext:Ze;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function Ie(e,t){let n=D(),r=n?n.services:Qt;return r?Bo(r,ac(e,t)):{handled:!1,result:t,warnings:[]}}function ci(e,t){let n=D(),r=n?n.services:Qt;return r?qo(r,ac(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]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var et=new Set(ye),lr=Object.freeze({get size(){return et.size},has(e){return et.has(e)},entries(){return et.entries()},keys(){return et.keys()},values(){return et.values()},forEach(e,t){et.forEach(n=>e.call(t,n,n,lr))},[Symbol.iterator](){return et.values()}});function cc(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function dc(e){return typeof e!="string"?null:Yn(e)}function r_(e){try{return structuredClone(e)}catch{return e}}function o_(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new w(`--field entries must use name=value syntax, received: ${e}`,b.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function i_(e){return`--${e.replaceAll("_","-")}`}function s_(e,t,n){try{let r=JSON.parse(e);if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r}catch{}throw new w(`--field ${t}=... must be valid JSON ${n}`,b.USAGE)}function a_(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new w(`--field ${e}=... must be a number`,b.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new w(`--field ${e}=... must be a number`,b.USAGE);return o}if(t==="boolean"){let r=n.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new w(`--field ${e}=... must be one of true|false|1|0|yes|no`,b.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):s_(n,e,t)}function di(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=cc(r.name),i=dc(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new w(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,b.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function lc(e){if(lr.has(e))throw new w(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...lr].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,b.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function ur(e){return[...di(e).keys()].sort((t,n)=>t.localeCompare(n))}function xx(e,t){if(!e||e.length===0)return{};let n=di(t),r={};for(let o of e){let{key:i,value:s}=o_(o),a=n.get(i);if(!a){if(lr.has(i)){let d=i_(i);throw new w(`--field ${i} is a core item field, not an extension field`,b.USAGE,{code:"core_item_field_requires_dedicated_flag",field:i,recovery:{provided_fields:[i],suggested_flags:[d]},nextSteps:[`Set the core field with its dedicated flag: pm update <id> ${d} <value>`,`When closing an item, pm close <id> also accepts ${d} <value>.`]})}let c=[...n.keys()].sort((d,l)=>d.localeCompare(l));throw new w(`--field ${i} is not declared by an active extension item-field registration`,b.USAGE,{code:"extension_item_field_unknown",recovery:{provided_fields:c},nextSteps:c.length>0?[`Use one of the declared fields: ${c.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}lc(a.name),r[a.name]=a_(a.name,a.type,s)}return r}function c_(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function d_(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Ix(e,t,n={}){if(t){di(t);for(let r of t.item_fields)for(let o of r.fields){let i=cc(o.name);if(!i)continue;lc(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=r_(o.default));let s=e[i];if(s===void 0)continue;let a=dc(o.type);if(a&&!c_(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!d_(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}import uc 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]="febba42b-dfd0-549a-a6d9-c30edb321d9d")}catch{}})();var K=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),pc=fo,fi=uo,l_=["create","update"],u_=new Set(Mn),f_=new Set(mt),m_=new Set(Ln),p_=new Set($n);function en(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function tt(e){return typeof e=="string"?e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_"):""}function fe(e){if(typeof e!="string"||e.length===0)return;let t=tt(e);return t.length>0?t:void 0}function __(e){return e.startsWith("--")?e.slice(2):e}function fc(e){return typeof e=="string"?__(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function _c(e){return e.replaceAll("_","-")}function y_(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function ui(e,t){let n=fe(e.id);if(!n)return null;let r=[...new Set(en(e.aliases).map(tt).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=en(e.roles).filter(a=>u_.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function g_(e){return{draft_status:fe(e?.draft_status),open_status:fe(e?.open_status),in_progress_status:fe(e?.in_progress_status),blocked_status:fe(e?.blocked_status),close_status:fe(e?.close_status),canceled_status:fe(e?.canceled_status)}}function yc(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=tt(t[0]),r=tt(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function h_(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)yc(n,r);return{typeKey:t.toLowerCase(),record:n}}function b_(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=h_(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)yc(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function gc(e){let t=tt(e.key??"");if(!t)return null;let n=tt(e.metadata_key??e.front_matter_key??t),r=fc(e.cli_flag??_c(t));if(!r)return null;let o=en(e.cli_aliases).map(l=>fc(l)).filter(l=>l.length>0&&l!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=f_.has(i)?i:"string",a=(()=>{let l=en(e.commands).filter(f=>m_.has(f));return l.length>0?l:[...l_]})(),c=e.description?.trim(),d=en(e.required_types);return{key:t,metadata_key:n,cli_flag:r,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:e.repeatable===!0||s==="string_array",required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1}}function w_(e){let t=new Map;for(let[r,o]of e.entries()){let i=ui(o,r);i&&t.set(i.id,i)}let n=mc([...t.values()]);return n.length>0?n:mc(fi.map((r,o)=>ui(r,o)).filter(r=>r!==null))}function mc(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function E_(e){let t=new Map;for(let n of e??[]){let r=gc(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function k_(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 v_(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==_c(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}}function S_(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return p_.has(t)?t:"allow"}function he(e){let t={...K,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:fi,r=w_(n),o=E_(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(k_),fields:o.map(v_),workflow:{...pc,...g_(e?.workflow)},type_workflows:b_(e?.type_workflows),unknown_field_policy:S_(e?.unknown_field_policy)}}function x_(e){return`${JSON.stringify(e,null,2)}
|
|
4
|
-
`}function I_(){return{definitions:[]}}function T_(){return{statuses:fi}}function A_(){return{fields:[]}}function C_(){return{workflow:pc}}function O_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function R_(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 n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function N_(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 D_(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 P_(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 M_(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 X(e,t,n){let r=t?.trim()||n;return uc.isAbsolute(r)?r:uc.join(e,r)}function Nx(e,t){return X(e,t.files.types,K.types)}async function hc(e,t){let n=he(t),r=[{path:X(e,n.files.types,K.types),seed:I_()},{path:X(e,n.files.statuses,K.statuses),seed:T_()},{path:X(e,n.files.fields,K.fields),seed:A_()},{path:X(e,n.files.workflows,K.workflows),seed:C_()}],o=[];for(let i of r)await ke(i.path)||(await Q(i.path,x_(i.seed)),o.push(i.path));return{created_paths:o}}async function bc(e,t){let n=he(t),r=[],o=X(e,n.files.types,K.types),i=X(e,n.files.statuses,K.statuses),s=X(e,n.files.fields,K.fields),a=X(e,n.files.workflows,K.workflows),c,d,l,f,p,m=async(J,q)=>{let dt=await Ce(J);if(dt!==null)return O_(dt,q,r)},h=await m(o,"runtime_schema_types_invalid_json");h!==void 0&&(c=R_(h),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let _=await m(i,"runtime_schema_statuses_invalid_json");_!==void 0&&(d=N_(_),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let y=await m(s,"runtime_schema_fields_invalid_json");y!==void 0&&(l=D_(y),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let T=await m(a,"runtime_schema_workflows_invalid_json");return T!==void 0&&(f=P_(T),f===void 0&&r.push("runtime_schema_workflows_invalid_shape"),p=M_(T)),{schema:he({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...f},type_workflows:[...n.type_workflows??[],...p??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function li(e,t,n){let r=e.filter(i=>i.roles.includes(t));if(r.length>0)return r[0].id;let o=n.map(i=>fe(i)).filter(i=>typeof i=="string");for(let i of o)if(e.some(s=>s.id===i))return i;return e[0]?.id}function wc(e){let t=he(e),n=t.statuses.map((_,y)=>ui(_,y)).filter(_=>_!==null),r=new Map,o=new Map;for(let _ of n){o.set(_.id,_),r.set(_.id,_.id),r.set(_.id.replaceAll("_","-"),_.id),r.set(_.id.replaceAll("_"," "),_.id);for(let y of _.aliases)r.set(y,_.id),r.set(y.replaceAll("_","-"),_.id),r.set(y.replaceAll("_"," "),_.id)}let i=new Set,s=new Set,a=new Set,c=new Set,d=new Set,l=new Set;for(let _ of n){let y=new Set(_.roles);(y.has("terminal")||y.has("terminal_done")||y.has("terminal_canceled"))&&i.add(_.id),y.has("terminal_done")&&s.add(_.id),y.has("terminal_canceled")&&a.add(_.id),y.has("active")&&c.add(_.id),y.has("blocked")&&d.add(_.id),y.has("draft")&&l.add(_.id)}let f=t.workflow,p=fe(f.open_status)??li(n,"default_open",["open","in_progress",ft[0]]),m=fe(f.close_status)??li(n,"default_close",["closed","done","complete"]),h=fe(f.canceled_status)??li(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:i,terminal_done_statuses:s,terminal_canceled_statuses:a,active_statuses:c,blocked_statuses:d,draft_statuses:l,open_status:p,close_status:m,canceled_status:h}}function mi(e,t){let n=tt(e);if(n)return t.alias_to_id.get(n)}function Ec(e){let t=he(e),n=new Map,r=t.fields.map(c=>gc(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.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,f)=>l.key.localeCompare(f.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function kc(e){return y_(e.key)}function Dx(e,t){let n=mi(e,t);return n?t.terminal_statuses.has(n):!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]="9bef4fe4-11a8-51ae-a42a-a93cc9c57384")}catch{}})();function pi(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function L_(e){return[...new Set([kc(e),pi(e.key),pi(e.cli_flag),...e.cli_aliases.map(t=>pi(t))])]}function xc(e,t){for(let n of L_(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function Ic(e){return Array.isArray(e)?e.flatMap(t=>Ic(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 vc(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 n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new w(`${t} must be one of true|false|1|0|yes|no`,b.USAGE)}function Sc(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new w(`${t} must be a number`,b.USAGE);return r}function $_(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new w(`${t} must be valid JSON ${n}`,b.USAGE)}function tn(e,t,n){let r=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object"){let i=Array.isArray(t)?t[t.length-1]:t;return i===void 0?void 0:$_(i,r,e.type)}if(e.repeatable||e.type==="string_array"){let i=Ic(t);return e.type==="number"?i.map(s=>Sc(s,r)):e.type==="boolean"?i.map(s=>vc(s,r)):i}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?Sc(o,r):e.type==="boolean"?vc(o,r):typeof o=="string"?o:String(o)}function F_(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Fx(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=xc(e,i);if(s===void 0){F_(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=tn(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function jx(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=xc(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=tn(s,a)))}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]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var ht=1,Tc=1;function Ux(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=ht?t:ht}function Ac(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=ht))return e}function j_(e,t=Tc){return e<t?"outdated":e>t?"ahead":"current"}function qx(e,t=Tc){let n=[],r=[];for(let o of e){let i=j_(o.version,t);i==="outdated"?n.push(o.ref):i==="ahead"&&r.push(o.ref)}return{outdated:n.sort((o,i)=>o.localeCompare(i)),ahead:r.sort((o,i)=>o.localeCompare(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]="d7501aa2-d3d9-5fbe-a1c0-d4bc145f5563")}catch{}})();var z_={"in-progress":"in_progress",cancelled:"canceled"};function fr(e,t){if(t){let o=mi(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=z_[n]??n;if(ft.includes(r))return r}function U_(e,t){return fr(e,t)??e}function Hx(e,t){return t.terminal_statuses.has(U_(e,t))}import{encode as W_}from"@toon-format/toon";import{isDeepStrictEqual as Cc}from"node:util";import{decode as q_}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]="2840e12e-7444-5d36-9f54-5a56267bbb75")}catch{}})();function _i(e){return{value:q_(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]="fedb7b50-6946-589d-b240-9f074e09e467")}catch{}})();var B_=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function V_(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(B_);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function mr(e){return V_(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]="c9225594-bc3b-5b07-8703-1debd1a98693")}catch{}})();var H_=new Set(["schema","tracker","auto"]),K_=new Set(["passed","failed","stopped","canceled"]),G_=new Set(Fs);function Et(e){return e.replaceAll("\\","/")}function ki(e){for(let t of e)if(t!==0)return t;return 0}function _r(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Dc=["id","title","description","created_at","updated_at"],X_=new Set(ye);function Pc(e){if(e?.schema)return{statusRegistry:wc(e.schema),fieldRegistry:Ec(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Y_(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function nt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new w(`Invalid item metadata: ${e}`,b.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function on(e,t){throw new w(t,b.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 Mc(e){let t=new Set(X_);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function v(e,t){e||nt(t)}function yi(e,t){let n=e[t];v(typeof n=="string",`${t} must be a string`),v(Oe(n),`${t} must be a valid ISO timestamp`)}function Oc(e,t,n){let r=e[t];r!==void 0&&v(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function bi(e,t,n){let r=e[t];r!==void 0&&(v(typeof r=="string",`${n} must be a string`),v(Oe(r),`${n} must be a valid ISO timestamp`))}function J_(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){v(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();v($t.includes(n),`event.recurrence.by_weekday entries must be one of: ${$t.join(", ")}`)}}}function Q_(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)v(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function Z_(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)v(typeof t=="string","event.recurrence.exdates entries must be strings"),v(Oe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function ey(e){v(typeof e=="object"&&e!==null&&!Array.isArray(e),"event.recurrence must be an object");let t=e;v(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();v(zn.includes(n),`event.recurrence.freq must be one of: ${zn.join(", ")}`),Oc(t,"interval","event.recurrence.interval"),Oc(t,"count","event.recurrence.count"),bi(t,"until","event.recurrence.until"),J_(t.by_weekday),Q_(t.by_month_day),Z_(t.exdates)}function ty(e){for(let r of Dc)v(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;v(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&v(typeof n=="number"&&Number.isInteger(n)&&n>=ht,`pm_format_version must be an integer >= ${ht}`),t}function ny(e,t){let n=e.status;v(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=fr(n,r),i=r?r.definitions.map(s=>s.id):[...ft];v(o!==void 0,`status must be one of: ${i.join(", ")}`)}function ry(e){let t=e.priority;v(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;v(Array.isArray(n),"tags must be an array");for(let r of n)v(typeof r=="string","tags entries must be strings")}function oy(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){v(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||jn.includes(n);v(r,`confidence string value must be one of: ${[...jn,"med"].join(", ")}`);return}v(!1,"confidence must be a number or string")}}function iy(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&nt("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Fn.includes(n);v(r,`severity value must be one of: ${[...Fn,"med"].join(", ")}`)}function sy(e){e.regression!==void 0&&typeof e.regression!="boolean"&&nt("regression must be a boolean")}function ay(e){let t=e.reminders;if(t!==void 0){v(Array.isArray(t),"reminders must be an array");for(let n of t){v(typeof n=="object"&&n!==null&&!Array.isArray(n),"reminders entries must be objects");let r=n;v(typeof r.at=="string","reminder.at must be a string"),v(Oe(r.at),"reminder.at must be a valid ISO timestamp"),v(typeof r.text=="string","reminder.text must be a string"),v(r.text.trim().length>0,"reminder.text must not be empty")}}}function cy(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(v(typeof e[t]=="string",`event.${t} must be a string`),v(e[t].trim().length>0,`event.${t} must not be empty`))}function dy(e){e.recurrence!==void 0&&(ey(e.recurrence),e.recurrence.until!==void 0&&v(W(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function ly(e){v(typeof e=="object"&&e!==null&&!Array.isArray(e),"events entries must be objects");let t=e;v(typeof t.start_at=="string","event.start_at must be a string"),v(Oe(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(v(typeof t.end_at=="string","event.end_at must be a string"),v(Oe(t.end_at),"event.end_at must be a valid ISO timestamp"),v(W(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),cy(t),t.all_day!==void 0&&v(typeof t.all_day=="boolean","event.all_day must be a boolean"),dy(t)}function uy(e){let t=e.events;if(t!==void 0){v(Array.isArray(t),"events must be an array");for(let n of t)ly(n)}}function fy(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&v(typeof n=="string",`${t} must be a string`)}}function my(e){let t=e.type_options;if(t!==void 0){v(typeof t=="object"&&t!==null&&!Array.isArray(t),"type_options must be an object");for(let[n,r]of Object.entries(t))v(n.trim().length>0,"type_options keys must be non-empty"),v(typeof r=="string","type_options values must be strings"),v(r.trim().length>0,"type_options values must be non-empty strings")}}function py(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Y_(r,t)&&nt(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=tn(r,o,`metadata field "${r.metadata_key}"`)}catch(i){nt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function _y(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Mc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?nt(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function wi(e,t){v(typeof e=="object"&&e!==null&&!Array.isArray(e),"item metadata must be an object");let n=e,r=ty(n);ny(n,t),ry(n),oy(n),iy(n),sy(n),yi(n,"created_at"),yi(n,"updated_at"),n.deadline!==void 0&&yi(n,"deadline"),ay(n),uy(n),bi(n,"closed_at","closed_at"),bi(n,"completed_at","completed_at"),fy(n),my(n),py(n,r,t),_y(n,t)}function yy(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim().toLowerCase(),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,n)=>{let r=W(t.created_at,n.created_at);if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function gi(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=W(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function gy(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=W(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function hy(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!zn.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>$t.includes(s)))).sort((s,a)=>go(s)-go(a)),r=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=>Oe(s)))).sort((s,a)=>W(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:n.length>0?n:void 0,by_month_day:r.length>0?r: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 by(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(wy).sort(Ey)}function wy(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:hy(e.recurrence)};return _r(t),t}function Ey(e,t){return ki([W(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 ky(e){if(!(!e||e.length===0))return e.map(t=>({path:Et(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function vy(e){if(!e||e.length===0)return;let t=e.map(Iy).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>ki([W(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function bt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Sy(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function hi(e){return typeof e=="string"?e:""}function xy(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function Iy(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=K_.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:hi(e.started_at),finished_at:hi(e.finished_at),recorded_at:hi(e.recorded_at),attempt:Sy(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:bt(e.passed)??0,failed:bt(e.failed)??0,skipped:bt(e.skipped)??0,items:bt(e.items),linked_tests:bt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:xy(e.measurements)};return _r(o),o}function Ty(e){if(!(!Array.isArray(e)||e.length===0))return[...e].map(Oy).sort(Ry)}function nn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Lc(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function vi(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Rc(e){if(!Lc(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!vi(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Ay(e){if(!Lc(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!vi(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Cy(e){let t=e?.trim().toLowerCase();if(!(!t||!H_.has(t)))return t}function Oy(e){let t={command:e.command?.trim()||void 0,path:e.path?Et(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:Cy(e.pm_context_mode),env_set:Rc(e.env_set),env_clear:nn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:nn(e.assert_stdout_contains),assert_stdout_regex:nn(e.assert_stdout_regex),assert_stderr_contains:nn(e.assert_stderr_contains),assert_stderr_regex:nn(e.assert_stderr_regex),assert_stdout_min_lines:bt(e.assert_stdout_min_lines),assert_json_field_equals:Rc(e.assert_json_field_equals),assert_json_field_gte:Ay(e.assert_json_field_gte),note:e.note?.trim()||void 0};return _r(t),t}function Ry(e,t){return ki([e.scope.localeCompare(t.scope),pr(e.path,t.path),pr(e.command,t.command),Nc(e.timeout_seconds,t.timeout_seconds),pr(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,Le(e.env_clear,t.env_clear,[]),Le(e.env_set,t.env_set,{}),Le(e.assert_stdout_contains,t.assert_stdout_contains,[]),Le(e.assert_stdout_regex,t.assert_stdout_regex,[]),Le(e.assert_stderr_contains,t.assert_stderr_contains,[]),Le(e.assert_stderr_regex,t.assert_stderr_regex,[]),Nc(e.assert_stdout_min_lines,t.assert_stdout_min_lines),Le(e.assert_json_field_equals,t.assert_json_field_equals,{}),Le(e.assert_json_field_gte,t.assert_json_field_gte,{}),pr(e.note,t.note)])}function pr(e,t){return(e??"").localeCompare(t??"")}function Nc(e,t){return(e??0)-(t??0)}function Le(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function Ny(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Et(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function k(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Dy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.id),i=k(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=k(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function Py(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.path);if(!o)continue;let i={path:Et(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=k(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function My(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.command),i=k(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Et(i));let a=k(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function Ly(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.path);if(!o)continue;let i={path:Et(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=k(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function $y(e){if(e===null||typeof e!="object")return;let t=e,n=k(t.id),r=k(t.title),o=k(t.status),i=o&&G_.has(o)?o:void 0,s=Rn(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return Fy(d,t),d}function Fy(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=k(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",Dy],["files","files",Py],["tests","tests",My],["docs","docs",Ly]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function jy(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=$y(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function zy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=k(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=k(r.rationale);c&&(a.rationale=c);let d=k(r.evidence);d&&(a.evidence=d);let l=k(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function Uy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=k(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=k(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function qy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.text);if(!o)continue;let i={text:o},s=k(r.command);s&&(i.command=s);let a=k(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function By(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function wt(e){let t=0;for(;t<e.length&&e[t]===`
|
|
5
|
-
`;)t+=1;return e.slice(t).trimEnd()}function
|
|
6
|
-
`,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function
|
|
1
|
+
import*as z from"node:fs/promises";import kn from"node:path";import pu 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]="74d24458-0685-5354-b62f-5323ee72ffd6")}catch{}})();var _u=[10,25,50,100];async function vn(e){await z.mkdir(e,{recursive:!0})}async function ke(e){try{return await z.access(e),!0}catch{return!1}}async function Ce(e){try{return await z.readFile(e,"utf8")}catch(t){if(He(t,"ENOENT"))return null;throw t}}async function Q(e,t){let n=kn.dirname(e);await vn(n);let r=kn.join(n,`.${kn.basename(e)}.${process.pid}.${Date.now()}.${pu.randomBytes(4).toString("hex")}.tmp`);await z.writeFile(r,t,"utf8");try{await z.rename(r,e)}catch(o){if(process.platform==="win32"&&(He(o,"EPERM")||He(o,"EBUSY"))){let i=o;for(let s of _u){await new Promise(a=>setTimeout(a,s));try{await z.rename(r,e);return}catch(a){if(i=a,!He(a,"EPERM")&&!He(a,"EBUSY"))break}}try{await z.unlink(r)}catch{}throw i}if(He(o,"EXDEV")){try{await z.copyFile(r,e)}finally{try{await z.unlink(r)}catch{}}return}try{await z.unlink(r)}catch{}throw o}}async function Pt(e,t){let n=kn.dirname(e);await vn(n);let r=await z.open(e,"a");try{await r.writeFile(`${t}
|
|
2
|
+
`,"utf8")}finally{await r.close()}}async function lk(e){try{await z.unlink(e)}catch(t){if(!He(t,"ENOENT"))throw t}}function He(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===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]="938c39a8-6545-5d8b-b717-69138932d528")}catch{}})();var _e=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],Sn=2,lo=Object.freeze({migration:"schema",validation:"schema"}),fk=Object.freeze({version:Sn,capabilities:[..._e],legacy_aliases:{...lo}}),xn=["off","warn","enforce"],In=["off","warn","enforce"],Tn=["none","restricted","strict"],Ss=["block","warn"],An=["commands.override","commands.handler","hooks.beforecommand","hooks.beforemutation","hooks.aftercommand","hooks.onwrite","hooks.onread","hooks.onindex","schema.flags","schema.itemfields","schema.itemtypes","schema.relationshipkinds","schema.migrations","schema.profiles","parser.override","preflight.override","services.override","renderers.override","importers.importer","importers.exporter","search.provider","search.vectorstore"],Mt=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function Cn(){return{mode:"off",trust_mode:"off",require_provenance:!1,trusted_extensions:[],default_sandbox_profile:"none",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:[]}}(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]="46d7e58b-d1b6-5f9d-86cb-76ca671ed127")}catch{}})();var fo=Object.freeze([{id:"draft",roles:["draft"]},{id:"open",roles:["active","default_open"]},{id:"in_progress",aliases:["in-progress"],roles:["active"]},{id:"blocked",roles:["blocked"]},{id:"closed",roles:["terminal","terminal_done","default_close"]},{id:"canceled",aliases:["cancelled"],roles:["terminal","terminal_canceled","default_cancel"]}]),mo=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),On=".agents/pm",Rn="settings.json",_k="Closed at creation via pm create",yu=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],gu=["decisions","events","reminders","milestones","meetings","plans"],yk=[...yu,...gu],se={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},hu=["goal","objective","value","impact","outcome","why_now","parent","reviewer","risk","confidence","sprint","release","blocked_by","blocked_reason","unblock_note","reporter","severity","environment","repro_steps","resolution","expected_result","actual_result"],ye=["id","title","description","type","pm_format_version","source_type","type_options","status","priority","tags","created_at","updated_at","deadline","reminders","events","closed_at","completed_at","assignee","claim_principal","source_owner","author","estimated_minutes","acceptance_criteria","design","external_ref","definition_of_ready","order",...hu,"affected_version","fixed_version","component","regression","customer_impact","dependencies","comments","notes","learnings","files","tests","test_runs","docs","close_reason","duplicate_of","plan_mode","plan_scope","plan_harness","plan_resume_context","plan_validation","plan_decisions","plan_discoveries","plan_steps"],po={minimal:{ownership_enforcement:"none",create_mode_default:"progressive",close_validation_default:"off",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!1,duplicate_detection_mode:"off",duplicate_detection_threshold:.8,duplicate_detection_limit:3},default:{ownership_enforcement:"warn",create_mode_default:"progressive",close_validation_default:"warn",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"core",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3},strict:{ownership_enforcement:"strict",create_mode_default:"strict",close_validation_default:"strict",require_close_reason:!0,parent_reference:"strict_error",metadata_profile:"strict",force_required_for_stale_lock:!0,duplicate_detection_mode:"strict",duplicate_detection_threshold:.8,duplicate_detection_limit:3}},bu=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],uo={blocked_reason:["no active blocker because work is closed","work is closed"],resolution:["closed with implementation evidence","closed with verification evidence","work completed and recorded","work is closed"],actual_result:["closed and recorded","work completed","work completed and recorded"]};function xs(e){return e?[...e]:void 0}var S={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...bu],lifecycle_closure_like_blocked_reason_patterns:[...uo.blocked_reason],lifecycle_closure_like_resolution_patterns:[...uo.resolution],lifecycle_closure_like_actual_result_patterns:[...uo.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...po.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:fo.map(e=>({...e,aliases:xs(e.aliases),roles:xs(e.roles)})),fields:[],workflow:{...mo},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:Cn()},search:{score_threshold:0,hybrid_semantic_weight:.7,max_results:50,embedding_model:"",embedding_batch_size:32,embedding_timeout_ms:3e4,scanner_max_batch_retries:3,provider:"",mutation_refresh_policy:"semantic_configured",query_expansion:{enabled:!1,provider:""},rerank:{enabled:!1,model:"",top_k:20}},providers:{openai:{base_url:"",api_key:"",model:""},ollama:{base_url:"",model:""}},context:{default_depth:"brief",activity_limit:10,stale_threshold_days:7,sections:{hierarchy:!0,activity:!0,progress:!0,recently_created:!0,unparented:!0,blockers:!0,files:!0,workload:!0,staleness:!0,tests:!0}},vector_store:{adapter:"",collection_name:"pm_items",qdrant:{url:"",api_key:""},lancedb:{path:""}}},Lt={metadata:{},body:""},b={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5},wu=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});function gk(e){let t=(e??"").trim().toLowerCase();if(t.length===0)return"unknown";let n=wu[t];return typeof n=="string"?n:t.includes("conflict")||t.includes("locked")?"conflict":t.startsWith("unknown_")||t.startsWith("missing_required_")?"usage":t.startsWith("invalid_")||t.endsWith("_not_found")||t.includes("validation")?"validation":t.endsWith("_error")||t.endsWith("_failed")?"runtime":"unknown"}(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]="c2c9251e-86bf-5a92-acdb-581e59d269d8")}catch{}})();var w=class extends Error{exitCode;code;context;constructor(t,n,r={}){super(t),this.name="PmCliError",this.exitCode=n,this.context=r,this.code=r.code}};(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]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function Eu(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function wk(e){return Eu(e)??void 0}function Ek(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 kk(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function Ts(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Nn(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 vk(e){let t=Nn(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function Sk(e,t,n){let r=Nn(e);return r===null||r<t||r>n?null:r}function xk(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function lt(e){return typeof e!="object"||e===null?null:e}function Is(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function As(e){let t=Is(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=Is(t.default);return typeof n?.activate=="function"?n:null}function Ik(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]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function Dn(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import ku from"node:crypto";import{AsyncLocalStorage as vu}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]="cc84ae55-6dc4-57d4-b7de-c43ae1fb4603")}catch{}})();var _o=new vu,Cs=1024;function Su(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.length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}async function Rk(e,t){let n=Su(e);return _o.run({...n,clockReads:0,tokenReads:0},t)}function Os(){let e=_o.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 Rs(e){let t=_o.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Cs)throw new Error(`Reproducible token length must be an integer between 0 and ${Cs}`);let n="";for(;n.length<e;){let r=ku.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}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]="6be1497f-a0d5-518b-bf6a-e549b18fad8a")}catch{}})();var xu=/^([+-]?)(\d+)([hdwm])$/i,Iu=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Tu=/^(\d{4})(\d{2})(\d{2})$/,Au=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Cu=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Ou=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i;function Ke(){return Os()??new Date().toISOString()}function Oe(e){return Number.isFinite(Date.parse(e))}var Ru=1e4,Pn=new Map;function Ns(e){let t=Pn.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Pn.size>=Ru&&Dn(Pn),Pn.set(e,n),n}function W(e,t){let n=Ns(e),r=Ns(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function $k(e,t){return!(t.deadlineBefore&&(!e.deadline||W(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||W(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&W(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&W(e.updated_at,t.updatedBefore)>0||t.createdAfter&&W(e.created_at,t.createdAfter)<0||t.createdBefore&&W(e.created_at,t.createdBefore)>0)}function yo(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function go(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 Nu(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function Du(e){let t=[],n=d=>Nu(t,e,d),r=Tu.exec(e);if(r){let[,d,l,f]=r;n(`${d}-${l}-${f}`)}let o=Au.exec(e);if(o){let[,d,l,f,p,m,h,_,y]=o,T=h?`:${h}`:"";n(`${d}-${l}-${f}T${p}:${m}${T}${yo(_)}${go(y)}`)}let i=Cu.exec(e);if(i){let[,d,l,f,p,m,h]=i,_=p?`:${p}`:"";n(`${d}T${l}:${f}${_}${yo(m)}${go(h)}`)}let s=Ou.exec(e);if(s){let[,d,l,f,p,m,h]=s,_=p?`:${p}`:"";n(`${d}T${l}:${f}${_}${yo(m)}${go(h)}`)}let a=10,c=e.slice(0,a);if(Mu(c)){let d=a;for(;d<e.length&&Lu(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Pu(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of Du(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Mu(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function Lu(e){return e?e===" "||e===" "||e===`
|
|
3
|
+
`||e==="\r"||e==="\f"||e==="\v":!1}function Ds(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var $u=["January","February","March","April","May","June","July","August","September","October","November","December"],Fu=/^(\d{4})-(\d{2})-(\d{2})/,ju=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function zu(e,t,n){let r=Fu.exec(t)??ju.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new w(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,b.USAGE);let c=Ds(o,i-1);if(s<1||s>c)throw new w(`Invalid ${a} value "${e}". ${$u[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,b.USAGE)}function Uu(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,Ds(i,s));return n.setUTCFullYear(i,s,a),n}function Fk(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=xu.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return Uu(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()}zu(e,r,n);let i=Pu(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Iu.test(r)?"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 w(`Invalid ${s} value "${e}". ${a}`,b.USAGE)}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]="8a7dca67-8f1e-5451-b45c-4a75b1117d72")}catch{}})();var qu=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function Ps(e){return typeof e!="string"?null:qu[e.trim().toLowerCase()]??null}function Ms(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function Ls(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())}import ut from"node:fs";import ve from"node:path";import{fileURLToPath as Bu}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]="dffcc28d-16a3-53d4-ba02-5298ae7a6d63")}catch{}})();var Vu="@unbrained/pm-cli";function Wu(e){try{return JSON.parse(ut.readFileSync(e,"utf8")).name===Vu}catch{return!1}}function Hu(e){let t=ut.existsSync(e)&&ut.statSync(e).isDirectory()?ve.resolve(e):ve.dirname(ve.resolve(e));for(;;){let n=ve.join(t,"package.json");if(ut.existsSync(n)&&Wu(n))return t;let r=ve.dirname(t);if(r===t)return;t=r}}function Mn(e,t=[]){let n=Bu(e),r=Hu(n);return r||ve.resolve(ve.dirname(n),...t)}function Vk(e,t=[]){try{let n=ve.join(Mn(e,t),"package.json");if(!ut.existsSync(n))return;let r=JSON.parse(ut.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function Wk(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?ve.resolve(o.trim()):n?Mn(n,r):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]="2a2072c1-f4a7-579e-ac11-4c75758d76d3")}catch{}})();var Ku=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],$s=Ku,ft=["draft","open","in_progress","blocked","closed","canceled"],Ln=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],mt=["string","number","boolean","string_array","array","object"],$n=["create","update","update_many","list","search","calendar","context"],Fn=["allow","warn","reject"],Kk=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","supersedes","task","verifies"],Gk=["project","global"],Xk=["low","medium","high","critical"],jn=["low","medium","high","critical"],zn=["low","medium","high"];var Fs=["minimal","default","strict","custom"],Yk=["none","warn","strict"],Jk=["progressive","strict"],Qk=["off","warn","strict"],Zk=["off","warn","strict"];var Un=["daily","weekly","monthly","yearly"],$t=["mon","tue","wed","thu","fri","sat","sun"];function ho(e){return $t.indexOf(e)}var ev=["draft","research","review","approved","executing","paused","completed","superseded"],js=["pending","in_progress","completed","blocked","skipped","superseded"],tv=["codex","claude-code","cursor","generic"],nv=["related","blocks","blocked_by","depends_on","discovered_from","implements","verifies","supersedes"],rv=["brief","standard","deep","full"],ov=["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]="f6e82c93-54e8-53a7-94df-10a573aae933")}catch{}})();import Qu 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]="815165a9-27a7-5933-adae-c7e55330c8e4")}catch{}})();function Re(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Gu(e){let t=e.key.trim();if(t.length===0)return null;let n=Re(e.aliases),r=e.description?.trim();return{key:t,values:Re(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var Xu=e=>e,Us=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function Yu(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function Ju(e,t){let n=new Map;for(let r of e??[]){let o=Yu(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function zs(e,t){return t?Re(e):void 0}function bo(e){let t=e?.trim();return t&&t.length>0?t:void 0}function qn(e,t={}){let n=t.resolvePolicyCommand??Xu,r=e.name.trim();if(r.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=Re(e.aliases),d=(e.options??[]).map(f=>Gu(f)).filter(f=>f!==null).sort((f,p)=>f.key.localeCompare(p.key)),l=Ju(e.command_option_policies,n);return{name:r,description:bo(e.description),default_status:bo(e.default_status),folder:bo(e.folder),aliases:c.length>0?c:void 0,required_create_fields:zs(e.required_create_fields,o),required_create_repeatables:zs(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]="88b2ed4e-b5fd-5014-abf1-c163db033abf")}catch{}})();var Zu=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],ef=["dep","comment","note","learning","file","test","doc"],Bs=["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"],tf=["title","description","type","status","priority","tags","body",...Bs,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],nf=["title","description","body","status","closeReason","priority","type","tags",...Bs,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],Vs={"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"},rf={...Vs},of={...Vs},Ws=[["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"]],Hs=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function Ks(e){return Object.fromEntries(e)}var sf=Ks([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...Ws,["author","--author"],["message","--message"],["dep","--dep"],...Hs]),af=Ks([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...Ws,...Hs,["author","--author"],["message","--message"],["force","--force"]]);function cf(e){return e.trim().replace(/^--+/,"").toLowerCase()}function df(e){return e==="create"?tf:nf}function lf(e){return e==="create"?rf:of}function Gs(e,t){let n=cf(t);if(n.length===0)return;let r=lf(e)[n];return r||df(e).find(o=>o.toLowerCase()===n)}function mv(e,t){return(e==="create"?sf:af)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Eo(e){let t=ff(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function uf(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=Qu.posix.normalize(r);if(t.includes("\0")||/^[A-Za-z]:/.test(o)||o==="."||o===".."||o.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return o}function ff(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function mf(e){return qn(e,{resolvePolicyCommand:Us})}function Ft(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function pf(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:Ft(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Ft(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function _f(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 n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,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 yf(e){if(Array.isArray(e.options))return e.options.map(t=>pf(t)).filter(t=>t!==null)}function gf(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>_f(t)).filter(t=>t!==null)}function hf(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=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:n,description:o,default_status:i,folder:r,aliases:Ft(t,"aliases"),required_create_fields:Ft(t,"required_create_fields"),required_create_repeatables:Ft(t,"required_create_repeatables"),options:yf(t),command_option_policies:gf(t)}}function bf(e,t){return e.required_create_fields?Re(e.required_create_fields):t?.required_create_fields??[]}function wf(e,t){return e.required_create_repeatables?Re(e.required_create_repeatables):t?.required_create_repeatables??[]}function Ef(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function kf(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function vf(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=uf(e.folder??t?.folder??Eo(n)),s={name:n,folder:i,aliases:Re([...t?.aliases??[],...e.aliases??[]]),required_create_fields:bf(e,t),required_create_repeatables:wf(e,t),options:Ef(e,t),command_option_policies:kf(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function qs(e,t){for(let n of e){let r=mf(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,vf(r,i))}}function Sf(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=hf(o);i&&t.push(i)}}return t}function Xs(e,t=null){let n=new Map;for(let c of $s)n.set(c.toLowerCase(),{name:c,folder:se[c],aliases:[],required_create_fields:[...Zu],required_create_repeatables:[...ef],options:[],command_option_policies:[]});qs(e.item_types?.definitions??[],n),qs(Sf(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){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(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function xf(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function If(e,t){let n=xf(e,t);if(n)return t.by_type[n]}function Tf(e,t,n,r){for(let o of r){let i=Gs(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function wo(e,t,n){if(n){e.add(t);return}e.delete(t)}function Af(e,t,n,r){let o=Gs(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&wo(e.required,o,r.required),r.visible!==void 0&&wo(e.hidden,o,!r.visible),r.enabled!==void 0&&wo(e.disabled,o,!r.enabled)}function Cf(e,t,n){for(let r of t.command_option_policies)r.command===n&&Af(e,t,n,r)}function Of(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function pv(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Tf(a,e,t,n),Cf(a,e,t),Of(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function Rf(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function Nf(e,t,n){let r=e.values;if(r.length===0)return t;let i=new Map(r.map(s=>[s.toLowerCase(),s])).get(t.toLowerCase());if(!i){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return i}function _v(e,t,n){let r=If(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Rf(r),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),f=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(f.length===0){o.push(`type option "${l}" must not be empty`);continue}let p=i.get(l.toLowerCase());if(!p){let h=r.options.map(_=>_.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${h}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=Nf(p,f,o);m!==void 0&&(s[p.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.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 Df,readdirSync as Pf,statSync as Mf}from"node:fs";import Lf from"node:os";import A 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]="c155ccd1-cf4c-57fd-9d0e-5274eb29a764")}catch{}})();var $f={json_markdown:".md",toon:".toon"},Ff={".md":"json_markdown",".toon":"toon"},jf=new Set([".git","coverage","dist","node_modules"]),Bn=[".md",".toon"];function jt(e){try{return Mf(e),!0}catch{return!1}}function Ys(e){try{let t=JSON.parse(Df(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function zf(e){let t=A.resolve(e);for(;;){let n=A.join(t,On),r=A.join(n,Rn);if(jt(r))return n;let o=A.join(t,Rn);if(jt(o)&&Ys(o))return t;let i=A.dirname(t);if(i===t)return;t=i}}function Uf(e){return zf(e)??A.resolve(e,On)}function kv(e,t){let n=t?A.resolve(t):void 0;try{return Pf(A.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!jf.has(r.name)).map(r=>A.join(A.resolve(e),r.name)).filter(r=>r!==n).filter(r=>jt(Ge(r))).filter(r=>Ys(Ge(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function vv(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=A.resolve(e,r);if(!jt(Ge(o))){let i=A.join(o,On);if(jt(Ge(i)))return i}return o}return Uf(e)}function Sv(e){let t=A.resolve(e),n=A.dirname(t);return A.basename(t)==="pm"&&A.basename(n)===".agents"?A.dirname(n):t}function Js(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:A.join(Lf.homedir(),".pm-cli");return A.resolve(e,n)}function Ge(e){return A.join(e,Rn)}function qf(e,t,n=se){let r=n[t]??Eo(t);return A.join(e,r)}function ko(e,t,n,r="toon",o=se){return A.join(qf(e,t,o),`${n}${$f[r]}`)}function vo(e){let t=e.replaceAll("\\","/"),n=A.posix.extname(t).toLowerCase();return Ff[n]??null}function zt(e,t){return A.join(e,"history",`${t}.jsonl`)}function Qs(e,t){return A.join(e,"locks",`${t}.lock`)}function Bf(e){return A.join(e,"runtime")}function Vn(e){return A.join(Bf(e),"test-runs")}function Vf(e){return A.join(Vn(e),"runs")}function xv(e,t){return A.join(Vf(e),`${t}.json`)}function Wf(e){return A.join(Vn(e),"stdout")}function Hf(e){return A.join(Vn(e),"stderr")}function Iv(e,t){return A.join(Wf(e),`${t}.log`)}function Tv(e,t){return A.join(Hf(e),`${t}.log`)}function Kf(e){return A.join(Vn(e),"results")}function Av(e,t){return A.join(Kf(e),`${t}.json`)}(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]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function pt(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;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 f=e[c-1]===t[l-1]?0:1,p=i[l-1]+f,m=s[l-1]+1,h=i[l]+1,_=Math.min(p,m,h);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(_=Math.min(_,o[l-2]+1)),s[l]=_,_<d&&(d=_)}if(d>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?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]="a89f0df7-e280-5ce4-8515-1f107a4aeaab")}catch{}})();var Gf=[{kind:"blocked_by",direction:"directed",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",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",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",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",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];function Kn(e){return e.trim().toLowerCase().replaceAll("-","_")}function Xf(e){if(e===void 0)return;let t=Kn(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function xo(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)xo(n,t);return Object.freeze(e)}for(let n of Object.values(e))xo(n,t);return Object.freeze(e)}function Yf(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 Jf(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 Qf(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=Kn(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 Zf(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}`)}function em(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(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}var Io=class{#e=new Map;#n=new Map;constructor(t=Gf){for(let n of t)this.register(n)}register(t){let n=Qf(t);if(Zf(t,n),em(t,n),Yf(t,n),Jf(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Xf(t.inverse),o=[...new Set((t.aliases??[]).map(Kn))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,hierarchy:t.hierarchy??!1,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?xo(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Kn(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function To(){return new Io}var Ut=To();function Rv(e,t=Ut){return t.resolve(e)?.ordering===!0}function tm(e,t,n,r=Ut){let o=qt(e),i=qt(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function Wn(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function nm(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=tm(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function Hn(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function qt(e){return typeof e=="string"?e.trim():""}function So(e,t){let n=qt(e);return n&&t.has(n)?n:void 0}function rm(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Zs=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=Ut){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=nm(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(Wn));for(let i of this.#r)Hn(this.#s,i.source,i),Hn(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(Hn(this.#s,i.target,i),Hn(this.#a,i.source,i))}static fromItems(t,n=Ut){let r=new Set(t.map(i=>qt(i.id)).filter(Boolean)),o=[];for(let i of t){let s=qt(i.id);if(!s)continue;let a=So(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=So(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=So(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||Wn(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.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||Wn(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.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,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,f=0,p=!1;e:for(let m=0;m<d.length;m+=1){n.signal?.throwIfAborted();let h=d[m];l+=1;let _=this.#t(h.id,o,r);if(f+=_.length,h.depth>=s){_.some(y=>!a.has(y.id))&&(p=!0);continue}for(let y of _)if(!a.has(y.id)){if(c.length>=i){p=!0;break e}a.add(y.id),c.push(y.id),d.push({id:y.id,depth:h.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:f,truncated:p,nextCursor:c.at(-1)}}}shortestPath(t,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,f=0,p=!1;for(let m=0;m<a.length;m+=1){r.signal?.throwIfAborted();let h=a[m];l+=1;let _=this.#t(h.id,i,o);if(f+=_.length,h.depth>=s){_.some(y=>!d.has(y.id))&&(p=!0);continue}for(let y of _)if(!d.has(y.id)){if(c.set(y.id,h.id),y.id===n)return{value:rm(t,n,c),meta:{visitedNodes:l,inspectedEdges:f,truncated:!1}};d.add(y.id),a.push({id:y.id,depth:h.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:f,truncated:p}}}subgraph(t,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.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(Wn)},meta:r.meta}}};function Nv(e,t,n=Ut){return{source:e,target:t.id,kind:n.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]="3225f4de-aa48-55b7-a704-d93ccb3ee0f4")}catch{}})();function Bt(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ne(e){return _e.includes(e)}function ea(e){let t=e.trim().toLowerCase();return Ne(t)?t:null}function ta(e){return e.filter(t=>!Ne(t))}function Ao(e){let t=e.trim().toLowerCase();return t.length===0?null:lo[t]??null}function na(e){let t=Bt([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Ao(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:Bt(n),legacy_aliases:o}}function om(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Ao(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of _e){let a=pt(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function ra(e,t,n){let r=_e.join(","),o=om(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function oa(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function im(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(m=>m.trim()).filter(m=>m.length>0),d=Ao(o),f=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:Sn,suggested_capability:f,suggestion_source:f?d===f?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function sm(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[..._e],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),f=d?.trim(),p=l?.trim().toLowerCase();!f||!p||!Ne(p)||a.push({layer:i,name:r,capability:f,allowed_capabilities:s,capability_contract_version:Sn,suggested_capability:p,suggestion_source:"legacy_alias",legacy_alias_target:p})}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]="baa8b608-7f1e-5382-abe3-b1af79e46da4")}catch{}})();function Vt(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Co(){return{overrides:[],handlers:[]}}function Oo(){return{overrides:[]}}function Ro(){return{overrides:[]}}function No(){return{overrides:[]}}function Do(){return{overrides:[]}}function Po(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[]}}(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]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function j(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function am(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function Z(e){return e?C(e):{}}function ee(e){return e?C(e):am()}function C(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]="8ba4e82a-ab38-5527-84cf-ec553f434a22")}catch{}})();var cm=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),dm=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","parser_overrides","service_overrides","renderer_overrides"];function lm(e,t){for(let n of dm){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>cm.has(n)?j(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function um(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>j(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function Mo(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 n={schema_version:1};if(!lm(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let i=um(o);if(i===null)return null;n.renderer_ownership=i}return n}function zv(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,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}}import fm 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]="83232698-197a-5aef-be7c-aa37f3c56822")}catch{}})();function mm(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 pm(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Gn(o))}return n}function Gn(e){let t=mm(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Gn(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Gn(r)}return pm(e)}function ae(e){return JSON.stringify(Gn(e))}function ia(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function _m(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function ym(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function gm(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!ia(o,n,r,te))return!1;return!0}function hm(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!ia([o,i],n,r,([a,c],[d,l])=>te(a,d)&&te(c,l)))return!1;return!0}function bm(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>te(n,t[r]))}function wm(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!te(e[i],t[i]))return!1}return!0}var Em=[_m,ym,gm,hm,bm];function te(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of Em){let r=n(e,t);if(r!==void 0)return r}return wm(e,t)}function Xe(e){return fm.createHash("sha256").update(e,"utf8").digest("hex")}function x(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}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]="4c40667c-1e20-5813-b2f3-eb4cb966b246")}catch{}})();var km=5e3;async function Wt(e,t,n){let r=[];for(let o of e)try{await o.run(C(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function vm(e,t){return Wt(e.beforeCommand,"beforeCommand",t)}function Sm(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new w(`Extension mutation guard ${t.name} returned an invalid decision.`,b.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 r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new w(`Extension mutation guard ${t.name} returned an invalid denial.`,b.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 r.message=="string"?r.message.trim():"";throw new w(s||`Extension mutation guard ${t.name} denied ${n}.`,b.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Lo(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:C(t.before),after:t.after===null?null:C(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new w(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,b.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},km),o.unref?.()})])}catch(i){throw i instanceof w?i:new w(`Extension mutation guard ${n.name} failed before ${t.operation}.`,b.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Sm(r,n,t.operation)}}async function xm(e,t){return Wt(e.afterCommand,"afterCommand",t)}async function $o(e,t){return Wt(e.onWrite,"onWrite",t)}async function Fo(e,t){return Wt(e.onRead,"onRead",t)}async function jo(e,t){return Wt(e.onIndex,"onIndex",t)}function Im(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 n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${n.slice(0,r-1)}\u2026`:n}function Xn(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?n.slice(0,300):void 0}function Tm(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 zo(e,t){let n=j(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,args:C(t.args),options:C(t.options),global:C(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",Tm(o)],["errorCode",Xn(o,"code")],["remediation",Xn(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:${r.layer}:${r.name}:${r.command}`],errorMessage:Im(o),...Object.fromEntries([["errorCode",Xn(o,"code")],["remediation",Xn(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function Uo(e,t){let n=j(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:C(t.args),options:Z(t.options),global:ee(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 r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:C(t.args),options:Z(t.options),global:ee(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(r.run({command:n,args:C(t.args),options:Z(t.options),global:ee(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)?C(o.args):C(t.args),s=o.options?Z(o.options):Z(t.options),a=o.global?ee(o.global):ee(t.global);return{overridden:!0,context:{command:n,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:n,args:C(t.args),options:Z(t.options),global:ee(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:${r.layer}:${r.name}:${r.command}`]}}}async function qo(e,t){let n=[...e.overrides].reverse()[0],r={command:j(t.command),args:C(t.args),options:Z(t.options),global:ee(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},o=C(t.decision);if(!n)return{overridden:!1,context:r,decision:o,warnings:[]};try{let i=await Promise.resolve(n.run({command:r.command,args:C(r.args),options:Z(r.options),global:ee(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:C(o)}))??{},s={command:r.command,args:Array.isArray(i.args)?C(i.args):r.args,options:i.options?Z(i.options):r.options,global:i.global?ee(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:o.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:o.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:o.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:o.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:r,decision:o,warnings:[`extension_preflight_override_failed:${n.layer}:${n.name}`]}}}function sa(e){return{handled:!1,result:e.payload,warnings:[]}}function aa(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function ca(e){return{service:e.service,command:e.command?j(e.command):void 0,args:e.args?C(e.args):void 0,options:e.options?Z(e.options):void 0,global:e.global?ee(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:C(e.payload)}}function Am(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 da(e,t){return Am(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 la(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&te(e,n.payload)}function Bo(e,t){let n=aa(e,t.service);if(n.length===0)return sa(t);let r=[];for(let o of n)try{let i=ca(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(la(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=da(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Vo(e,t){let n=aa(e,t.service);if(n.length===0)return sa(t);let r=[];for(let o of n)try{let i=ca(t),s=await Promise.resolve(o.run(i));if(la(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=da(s,t);if(!a.handled)continue;return{handled:!0,result:a.result,warnings:r}}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function Wo(e,t){let n=j(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=Z(t.options),i=ee(t.global),s=r.run({command:n,args:C(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:C(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function Cm(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(C(n))}catch{return!1}}function Ho(e,t){let n=typeof t.command=="string"?j(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&Cm(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?C(t.args):[],i=Z(t.options),s=ee(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,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:C(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import Ze from"node:fs/promises";import Qe from"node:path";import{pathToFileURL as Km}from"node:url";import ua 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]="624aced5-552c-5354-9e34-b96e267d34d1")}catch{}})();function Ko(e,t){let n=ua.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!ua.isAbsolute(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]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var Yn=mt;function Jn(e){let t=e.trim().toLowerCase();return Yn.includes(t)?t:null}function fa(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Yn)if(pt(t,r,n)!==null)return r;return null}import Om from"node:fs/promises";import Ht 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]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}catch{}})();async function ma(e,t){let n=Ht.dirname(t.manifest_path),r=Ht.relative(n,t.entry_path);if(r.startsWith("..")||Ht.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Ht.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Om.cp(n,o,{recursive:!0,force:!0}),Ht.join(o,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]="1558713a-91ea-5eef-8426-d910e0b77045")}catch{}})();function pa(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(([n,r])=>[n,r.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[n,r]of Object.entries(t.registrations))e.registrations[n].length=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]="dc9a3977-a78a-501e-b600-45e7031dcebd")}catch{}})();function Se(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function G(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 _a(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function Ye(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[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function Kt(e,t){if(Ye(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}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]="45d00ef3-870c-5f3f-89c1-6abd54c518fe")}catch{}})();function ya(e){H("registerCommand definition.action",e.action),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")}(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]="875ac35b-c6ce-5690-a05a-8e4d279a49bf")}catch{}})();var Rm=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:"--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"}]),Go=new Set(Rm.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]="4eccf02f-7401-539f-b843-f55b63ed878c")}catch{}})();var Nm=/^--[a-z0-9][a-z0-9_-]*(?:[ =](?:<[^<>]+>|\[[^[\]]+\]))?$/;function Dm(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return Go.has(n)?"host_owned_flag_collision":Nm.test(t)?null:"malformed_long_flag"}function ga(e,t){let n=[e,t].find(i=>typeof i=="string"&&Go.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=Dm(r);return o===null?null:{token:r,failure:o}}function ha(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]="849502d0-2616-500c-96de-228c0759459d")}catch{}})();function ba(e){return typeof e=="string"?e:String(e)}function Gt(e){let n=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(n)?n.split(/[.-]/).map(r=>Number(r)):null}function Xo(e,t){let n=Gt(e),r=Gt(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function wa(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=ba(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!Gt(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=Xo(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function Ea(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=ba(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!Gt(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=Xo(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,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]="24383c0a-592e-5105-84a3-a6cfb7801281")}catch{}})();function ce(e){return typeof e!="string"?"":e.trim().toLowerCase()}function R(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function Pm(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function _t(e){return new Set((e??[]).map(t=>Pm(t)).filter(t=>t.length>0))}function ka(e){let t=ce(e);return xn.includes(t)?t:"off"}function va(e){let t=ce(e);return In.includes(t)?t:"off"}function Xt(e){let t=ce(e);return Tn.includes(t)?t:"none"}function Yo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Ss.includes(t)?t:void 0}function Sa(e){if(typeof e=="string"){let t=Yo(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Yo(e.global)??"block",project:Yo(e.project)??"block"}:{global:"block",project:"block"}}function Mm(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function P(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Lm(e){let t=ce(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?Xt(e.sandbox_profile):void 0,allowedCapabilities:R(e.allowed_capabilities),blockedCapabilities:R(e.blocked_capabilities),allowedSurfaces:_t(e.allowed_surfaces),blockedSurfaces:_t(e.blocked_surfaces),allowedCommands:R(e.allowed_commands),blockedCommands:R(e.blocked_commands),allowedActions:R(e.allowed_actions),blockedActions:R(e.blocked_actions),allowedServices:R(e.allowed_services),blockedServices:R(e.blocked_services)}}}function xa(e){let t=new Map;for(let n of e??[]){let r=Lm(n);r&&t.set(r.name,r.normalized)}return t}function $m(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of P([...e.allowedCapabilities,...e.blockedCapabilities]))Ne(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of P([...o.allowedCapabilities,...o.blockedCapabilities]))Ne(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(An);for(let o of P([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of P([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function Ia(e){let t=e.extensions?.policy??{},n=R(t.allowed_capabilities),r=R(t.blocked_capabilities),o=_t(t.allowed_surfaces),i=_t(t.blocked_surfaces),s=xa(t.extension_overrides);return{mode:ka(t.mode),trustMode:va(t.trust_mode),pmMaxVersionExceededMode:Sa(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:R(t.trusted_extensions),defaultSandboxProfile:Xt(t.default_sandbox_profile),allowedExtensions:R(t.allowed_extensions),blockedExtensions:R(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:R(t.allowed_commands),blockedCommands:R(t.blocked_commands),allowedActions:R(t.allowed_actions),blockedActions:R(t.blocked_actions),allowedServices:R(t.allowed_services),blockedServices:R(t.blocked_services),overridesByName:s,warnings:$m({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function Ta(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:P(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:P(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:P(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:P(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:P(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:P(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:P(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:P(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:P(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:P(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:Mm(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:P(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:P(e.allowedExtensions),blocked_extensions:P(e.blockedExtensions),allowed_capabilities:P(e.allowedCapabilities),blocked_capabilities:P(e.blockedCapabilities),allowed_surfaces:P(e.allowedSurfaces),blocked_surfaces:P(e.blockedSurfaces),allowed_commands:P(e.allowedCommands),blocked_commands:P(e.blockedCommands),allowed_actions:P(e.allowedActions),blocked_actions:P(e.blockedActions),allowed_services:P(e.allowedServices),blocked_services:P(e.blockedServices),extension_overrides:t}}function Aa(e){let t=xa(e.extension_overrides);return{mode:ka(e.mode),trustMode:va(e.trust_mode),pmMaxVersionExceededMode:Sa(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:R(e.trusted_extensions),defaultSandboxProfile:Xt(e.default_sandbox_profile),allowedExtensions:R(e.allowed_extensions),blockedExtensions:R(e.blocked_extensions),allowedCapabilities:R(e.allowed_capabilities),blockedCapabilities:R(e.blocked_capabilities),allowedSurfaces:_t(e.allowed_surfaces),blockedSurfaces:_t(e.blocked_surfaces),allowedCommands:R(e.allowed_commands),blockedCommands:R(e.blocked_commands),allowedActions:R(e.allowed_actions),blockedActions:R(e.blocked_actions),allowedServices:R(e.allowed_services),blockedServices:R(e.blocked_services),overridesByName:t,warnings:[]}}function De(e,t){return e.overridesByName.get(ce(t))??null}function yt(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function Ca(e,t,n){let r=n.trim().toLowerCase(),o=De(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return yt(i,s,r,"capability_not_allowlisted","capability_blocked")}function Fm(e,t,n){let r=De(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return yt(o,i,n,"surface_not_allowlisted","surface_blocked")}function jm(e,t,n){let r=j(n);if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return yt(i,s,r,"command_not_allowlisted","command_blocked")}function zm(e,t,n){let r=ce(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return yt(i,s,r,"action_not_allowlisted","action_blocked")}function Um(e,t,n){let r=ce(n);if(r.length===0)return null;let o=De(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return yt(i,s,r,"service_not_allowlisted","service_blocked")}function qm(e,t){let n=ce(t.name);return De(e,t.name)?.disabled===!0?"extension_override_disabled":yt(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Bm(e,t){if(e.trustMode==="off")return null;let n=De(e,t.name),r=ce(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Vm(e,t){if(e.mode==="off")return null;let r=De(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(r==="none")return null;let o=t.permissions;if(!o)return"sandbox_permissions_missing";let i=s=>o[s]===!0;return r==="restricted"?i("process_spawn")?"sandbox_restricted_disallows_process_spawn":i("env_write")?"sandbox_restricted_disallows_env_write":null:i("process_spawn")?"sandbox_strict_disallows_process_spawn":i("network")?"sandbox_strict_disallows_network":i("fs_write")?"sandbox_strict_disallows_fs_write":i("env_write")?"sandbox_strict_disallows_env_write":null}function Qn(e,t,n,r,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}:${n.layer}:${n.name}:reason=${r}${s}`}function Oa(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=qm(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Bm(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=Vm(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:Qn("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:Qn("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function Ra(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=Ca(e,t,n);return r?{allowed:e.mode==="warn",warning:Qn(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Wm(e,t,n,r,o){let i=typeof r=="string"?Ca(e,t,r):null,s=Fm(e,t,n),a=o.command?jm(e,t,o.command):null,c=o.action?zm(e,t,o.action):null,d=o.service?Um(e,t,o.service):null;return i??s??a??c??d}function Hm(e,t,n,r){let o={method:ce(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=j(r.command)),r.action&&(o.action=ce(r.action).replace(/\s+/g,"-")),r.service&&(o.service=ce(r.service)),o}function Na(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Wm(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=Qn(e.mode==="warn"?"violation":"blocked","registration",t,a,Hm(r,n,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]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();function Da(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]="ed58c949-c3d3-5a74-9146-05b0a04b58c4")}catch{}})();var Gm=100,Pa=null,Xm=Object.freeze(Cn()),Ma=0;function Ym(e=Date.now()){return Ma+=1,`${Ma}-${e}`}function La(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function Jm(e){if(e==null)return;let t=lt(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function Jo(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Ka(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function Je(e){if(e!=null)return typeof e!="boolean"?null:e}function Qm(e){let t=Ka(e.priority);return t===void 0?Gm:t}function Zm(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=Xt(t);return n!==t.trim().toLowerCase()?null:n}function Qo(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function ep(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=Qo(t.source),r=Qo(t.signature),o=Qo(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function tp(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=Je(t.fs_read),r=Je(t.fs_write),o=Je(t.network),i=Je(t.env_read),s=Je(t.env_write),a=Je(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function np(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=na(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function rp(e){if(e==null)return;let t=lt(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>j(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function op(e){let t=Ka(e.manifest_version);if(t===null)return null;let n=La(e,"pm_min_version");if(n===null)return null;let r=La(e,"pm_max_version");if(r===null)return null;let o=Jm(e.engines);if(o===null)return null;let i=Je(e.trusted);if(i===null)return null;let s=Zm(e);if(s===null)return null;let a=ep(e.provenance);if(a===null)return null;let c=tp(e.permissions);if(c===null)return null;let d=np(e.capabilities);if(d===null)return null;let l=rp(e.activation);if(l===null)return null;let f=Mo(e.contributions);return f===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:f}}function ip(e){if(typeof e!="object"||e===null)return null;let t=e,n=Jo(t,"name");if(n===null)return null;let r=Jo(t,"version");if(r===null)return null;let o=Jo(t,"entry");if(o===null)return null;let i=Qm(t);if(i===null)return null;let s=op(t);return s===null?null:{name:n,version:r,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}}function sp(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function ap(e,t){let[n,r]=await Promise.all([Ze.realpath(e),Ze.realpath(t)]);return Ko(n,r)}function cp(e,t=process.cwd()){return{global:Qe.join(Js(t),"extensions"),project:Qe.join(e,"extensions")}}async function dp(e){try{return(await Ze.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort((n,r)=>n.localeCompare(r))}catch{return[]}}function lp(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 $a(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function up(e){let t=new Map;try{let n=JSON.parse(await Ze.readFile(Qe.join(e,".managed-extensions.json"),"utf8")),o=lt(n)?.entries;if(!Array.isArray(o))return t;for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=$a(s.source?.package),c=[s.source?.input,s.source?.name,a].map(f=>$a(f)).filter(f=>f!==void 0),d=Mo(s.contributions),l={aliases:[...new Set(c)],...a?{package_name:a}:{},...d?{contributions:d}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&t.set(`directory:${s.directory.trim()}`,l),typeof s.name=="string"&&s.name.trim().length>0&&t.set(`name:${s.name.trim()}`,l)}}catch{return t}return t}function Fa(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function fp(e,t){let n=[...Fa(e),...Fa(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function ja(e,t,n,r,o){let i=[],s=[],a=[],c=await dp(t),d=await up(t);for(let l of c){let f=await _p(e,t,l,n,r,d,o);i.push(f.diagnostic),s.push(...f.warnings),f.candidate&&a.push(f.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function mp(){return{diagnostics:[],warnings:[],candidates:[]}}function za(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function pp(e,t,n,r,o,i){let s=[];Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&s.push(oa(e,t.name,t.legacy_capability_aliases));for(let a of ta(t.capabilities))s.push(ra(e,t.name,a));return n?r||s.push(`extension_entry_missing:${e}:${t.name}`):s.push(`extension_entry_outside_extension:${e}:${t.name}`),o.warning&&s.push(o.warning),i.warning&&s.push(i.warning),s}async function _p(e,t,n,r,o,i,s){let a=Qe.join(t,n),c=Qe.join(a,"manifest.json");if(!await ke(c))return za(e,n,c,`extension_manifest_missing:${e}:${n}`);let d;try{let q=JSON.parse(await Ze.readFile(c,"utf8"));d=ip(q)}catch{d=null}if(!d)return za(e,n,c,`extension_manifest_invalid:${e}:${n}`);let l=Qe.resolve(a,d.entry),f=Ko(a,l),p=f?await ke(l):!1,m=f&&p?await ap(a,l):f,h=sp(d.name,r,o),_=await hp(e,d),y=await bp(e,d,s),T=pp(e,d,m,p,_,y),L=m&&p&&_.allowed&&y.allowed,J=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:l,enabled:h,status:L?"ok":"warn"},warnings:T,candidate:Da({layer:e,directory:n,manifestPath:c,entryPath:l,manifest:d,sourceIdentity:J,extensionReady:L,enabledForLoad:h})}}async function yp(e){let t=cp(e.pmRoot,e.cwd??process.cwd()),n=Bt(e.settings.extensions.enabled),r=Bt(e.settings.extensions.disabled),o=Ia(e.settings),i=Ta(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?mp():await ja("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await ja("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],f=fp(c.candidates,d.candidates),p=[];for(let m of f){let h={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},_=Oa(o,h);if(_.warning&&l.push(_.warning),!!_.allowed){for(let y of m.manifest.capabilities){let T=Ra(o,h,y);T.warning&&l.push(T.warning)}p.push(lp(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:p,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function nr(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function gp(){try{let e=Mn(import.meta.url,["../../.."]),t=await Ze.readFile(Qe.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Ga(){return Pa??=gp(),Pa}function Xa(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function hp(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=wa(t.pm_min_version,await Ga()),r=Xa(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function bp(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=Ea(t.pm_max_version,await Ga(),n),o=Xa(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Ua(e){try{let t=await Ze.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function wp(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await ma(t.module_graph_snapshot_root,e));let r=new URL(Km(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[i,s]=await Promise.all([Ua(e.entry_path),Ua(e.manifest_path)]),a=t.reload_token??Ym();return r.searchParams.set("pm_ext_reload",a),r.searchParams.set("pm_ext_entry",i),r.searchParams.set("pm_ext_manifest",s),r.href}async function zS(e){let t=await yp(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let c=await import(await wp(s,e));n.push({...s,module:c})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:nr(a)})}return{...t,warnings:o,loaded:n,failed:r}}var qa=5e3,Ep=2147483647;function kp(e){let n={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let r=e.deactivate;n.deactivate=r.bind(e)}return n}function Ya(e){let t=As(e);return t?kp(t):null}async function US(e,t,n={}){let r=vp(n?.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 f=Ya(l.module);!f||typeof f.deactivate!="function"||i.push({extension:l,deactivate:f.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:f})=>{try{return await Sp(f,r),{ok:!0}}catch(p){return{ok:!1,layer:l.layer,name:l.name,error:nr(p)}}})),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 vp(e){return typeof e!="number"||e<0?qa:e===0||e===1/0?0:Number.isFinite(e)?Math.min(Ep,Math.max(1,Math.floor(e))):qa}async function Sp(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function xp(e){return e==="toon"||e==="json"}function Ip(e){return Mt.includes(e)}function gt(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}function ne(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function Yt(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Ba(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Va(e,t){return j(`${e} ${t}`)}function er(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>er(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={},r=Object.keys(t).sort((o,i)=>o.localeCompare(i));for(let o of r)n[o]=er(t[o]);return n}return e}function tr(e){if(Array.isArray(e))return e.map(t=>tr(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=tr(t[r]);return n}return e}var Ja=Symbol("extension_registration_trace");function Pe(e,t){let n=new TypeError(e);return Object.defineProperty(n,Ja,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function Tp(e){if(e instanceof Error)return e[Ja]}function Zn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return er(t)}function Zo(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return tr(t)}function ri(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>Zn(e,n))}var Ap=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","visible"]);function ei(e,t){return ri(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function Cp(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Wa(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 n=Cp(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Ha(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[r,o]of e.entries()){let i=Se(`registerCommand definition.arguments[${r}]`,o),s=ne(`registerCommand definition.arguments[${r}].name`,i.name);if(G(`registerCommand definition.arguments[${r}].required`,i.required),G(`registerCommand definition.arguments[${r}].variadic`,i.variadic),H(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].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 n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function ti(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=Se(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!Ap.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=r.long,s=r.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=ga(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${ha(a.token,a.failure)}`);if(H(`registerFlags flags[${t}].value_name`,r.value_name),H(`registerFlags flags[${t}].description`,r.description),G(`registerFlags flags[${t}].required`,r.required),G(`registerFlags flags[${t}].enabled`,r.enabled),G(`registerFlags flags[${t}].visible`,r.visible),G(`registerFlags flags[${t}].list`,r.list),G(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(_a(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Op(`registerFlags flags[${t}]`,r)}}function Op(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=Ps(n);if(r===null)throw new TypeError(`${e} value_type "${n}" 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?Ms(t.default):[t.default];for(let[i,s]of o.entries())if(!Ls(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Rp(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=Se(`registerItemFields fields[${t}]`,n);ne(`registerItemFields fields[${t}].name`,r.name);let o=ne(`registerItemFields fields[${t}].type`,r.type);if(Jn(o)===null){let i=fa(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Yn.join(", ")}).${s}`)}G(`registerItemFields fields[${t}].optional`,r.optional)}}function Np(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=Se(i,o);ne(`${i}.command`,s.command),ne(`${i}.option`,s.option),G(`${i}.enabled`,s.enabled),G(`${i}.required`,s.required),G(`${i}.visible`,s.visible)}}function Dp(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=Se(i,o);ne(`${i}.key`,s.key),Ye(`${i}.values`,s.values),G(`${i}.required`,s.required),Ye(`${i}.aliases`,s.aliases)}}function Pp(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=Se(r,n);ne(`${r}.name`,o.name),H(`${r}.folder`,o.folder),Ye(`${r}.aliases`,o.aliases),Ye(`${r}.required_create_fields`,o.required_create_fields),Ye(`${r}.required_create_repeatables`,o.required_create_repeatables),Np(t,o.command_option_policies),Dp(t,o.options)}}function Mp(e){let t=Se("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(G("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 Qa=["types","statuses","fields","workflows","config","templates","packages"],Lp={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[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] 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 $p(e){let t=Se("registerProfile profile",e);if(ne("registerProfile profile.name",t.name),ne("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 n of Qa){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);Lp[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function Fp(e){e.summary===void 0&&(e.summary="");for(let t of Qa)e[t]===void 0&&(e[t]=[]);return e}function ni(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}function jp(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Ne(r)&&t.add(r)}return t}function F(e,t,n){let r=jp(e);if(r!==null&&!r.has(t))throw Pe(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,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 ${n} registration call.`})}function zp(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>_e.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function Up(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 oi=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,f){this.#e=t,this.extension=zp(t),this.#n=Up(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=f,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.hooks={beforeCommand:p=>this.registerBeforeCommand(p),beforeMutation:p=>this.registerBeforeMutation(p),afterCommand:p=>this.registerAfterCommand(p),onWrite:p=>this.registerOnWrite(p),onRead:p=>this.registerOnRead(p),onIndex:p=>this.registerOnIndex(p)}}allowRegistration(t,n,r,o){let i=Na(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:er(o),hint:i}}registerCommandOverride(t,n){let r=j(t);if(r.length===0)throw Pe("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Pe(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Pe("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Pe("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=j(t.name);if(n.length===0)throw Pe("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Pe(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{ya(t);let o=Wa(n,t.action);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let i=t.description?.trim(),s=t.intent?.trim(),a=Kt("registerCommand definition.examples",t.examples),c=Kt("registerCommand definition.failure_hints",t.failure_hints),d=Ha(t.arguments);t.flags!==void 0&&(F(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(ti(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:ei("registerCommand definition.flags",t.flags)})));let l={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:a,failure_hints:c,arguments:d,tier:t.tier};i&&(l.description=i),s&&(l.intent=s),this.#t.commands.push(l)}catch(o){let i=nr(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Pe(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(F(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(F(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=j(ne("registerParser command",t));Yt("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){F(this.#e,"preflight","registerPreflight"),this.allowRegistration("preflight.override","registerPreflight","preflight")&&(Yt("registerPreflight override",t),this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerService(t,n){F(this.#e,"services","registerService");let r=String(t).trim().toLowerCase();if(!Ip(r))throw new TypeError(`registerService service must be one of: ${Mt.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:r})&&(Yt("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:r,run:n}))}registerRenderer(t,n,r={}){if(F(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!xp(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return j(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(F(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=j(ne("registerFlags targetCommand",t));ti(n);let o=ei("registerFlags flags",n);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:r,flags:o})}registerItemFields(t){if(F(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Rp(t);let n=ri("registerItemFields fields",t);if(n.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:n})}registerItemTypes(t){if(F(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;Pp(t);let n=ri("registerItemTypes types",t);if(n.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:n})}registerRelationshipKinds(t){if(F(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 n=To();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(F(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Mp(t);let n=Zo("registerMigration definition",t);this.#t.migrations.push(ni({layer:this.#e.layer,name:this.#e.name,definition:Zn("registerMigration definition",t)},n))}registerProfile(t){if(F(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=tr(t);$p(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Fp(n)})}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))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={...r,description:r?.description??o,arguments:r?.arguments??i};H(`${t} options.action`,s.action),H(`${t} options.description`,s.description),H(`${t} options.intent`,s.intent);let a=Wa(n,s.action),c=Kt(`${t} options.examples`,s.examples),d=Kt(`${t} options.failure_hints`,s.failure_hints),l=Ha(s.arguments);s.flags!==void 0&&(F(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(ti(s.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:ei(`${t} options.flags`,s.flags)})));let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:a,examples:c,failure_hints:d,arguments:l},p=s.description?.trim();p&&(f.description=p);let m=s.intent?.trim();m&&(f.intent=m),this.#t.commands.push(f)}registerImporter(t,n,r){if(F(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Ba(ne("registerImporter name",t));Yt("registerImporter importer",n);let i=Va(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n({registration:o,action:"import",command:s.command,args:C(s.args),options:C(s.options),global:C(s.global),pm_root:s.pm_root,source_workspace_root:s.source_workspace_root,repo_root:s.repo_root,pm_root_rel:s.pm_root_rel,...s.sdk===void 0?{}:{sdk:s.sdk}})})}registerExporter(t,n,r){if(F(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Ba(ne("registerExporter name",t));Yt("registerExporter exporter",n);let i=Va(o,"export");this.applyImportExportCommandMetadata("registerExporter",i,r),this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n({registration:o,action:"export",command:s.command,args:C(s.args),options:C(s.options),global:C(s.global),pm_root:s.pm_root,source_workspace_root:s.source_workspace_root,repo_root:s.repo_root,pm_root_rel:s.pm_root_rel,...s.sdk===void 0?{}:{sdk:s.sdk}})})}registerSearchProvider(t){if(F(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=Zo("registerSearchProvider provider",t);this.#t.search_providers.push(ni({layer:this.#e.layer,name:this.#e.name,definition:Zn("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(F(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=Zo("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(ni({layer:this.#e.layer,name:this.#e.name,definition:Zn("registerVectorStoreAdapter adapter",t)},n))}registerBeforeCommand(t){F(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){F(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){F(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){F(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){F(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){F(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 qp(e,t,n,r,o,i,s,a,c,d,l){return new oi(e,t,n,r,o,i,s,a,c,d,l)}function Bp(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=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:n,item_fields:r,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}}function Vp(e){let t=[],n=(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 f of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${f.layer}:${f.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.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 Wp(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);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))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Hp(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);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:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}function Kp(e){if(e.overrides.length<=1)return[];let t=e.overrides[e.overrides.length-1];return e.overrides.slice(0,-1).map(n=>`extension_preflight_override_collision:${t.layer}:${t.name}:${n.layer}:${n.name}`)}var Gp=new Set(["output_format"]);function Xp(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Gp.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function qS(e){let t=Aa(e.policy??Xm),n=Vt(),r=Co(),o=Oo(),i=Ro(),s=No(),a=Do(),c=Po(),d=[],l=[];for(let m of e.loaded){let h=Ya(m.module);if(!h)continue;let _=d.length,y=pa({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await h.activate(qp(m,n,r,o,i,s,a,c,l,d,t)),d.length>_&&(y(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(T){y(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let L=Tp(T);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:nr(T),trace:L})}}let f=[...Vp(r),...Hp(o),...Kp(i),...Xp(s),...Wp(a)],p=[...new Set([...l,...f])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:p,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.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:Bp(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]="bd9832a9-f6a2-5351-a929-0a0d2766df88")}catch{}})();function XS(e){return{...e,hooks:Vt(),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]="3239b2c7-3ae3-5d4e-9005-b61000362304")}catch{}})();function JS(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let o=Promise.all([e,...t]).then(()=>n());return e=o.then(()=>{},()=>{}),o}}}function Yp(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.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]="3f347c0d-2e1f-5d17-9e38-bae834f845d3")}catch{}})();var Jp={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"]},Za=":";function ec(e,t){return`${e}${Za}${ii(t)}`}function Qp(e){return e.slice(e.indexOf(Za)+1)}function ii(e){return e.trim().toLowerCase()}function Zp(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=ea(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function tc(e){let t=new Map,n=(l,f)=>{for(let p of l){let m=ec(p.layer,p.name),h=t.get(m);h===void 0&&(h=new Set,t.set(m,h)),h.add(f)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function e_(e,t={}){let n=tc(e),r=new Set;t.extensionName!==void 0&&r.add(ii(t.extensionName));for(let i of t.extensionNames??[])r.add(ii(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(Qp(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function t_(e,t){let n=tc(t),r=[];for(let o of e){let i=Zp(o.capabilities);if(i.length===0)continue;let s=n.get(ec(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as n_}from"node:fs";import{AsyncLocalStorage as r_}from"node:async_hooks";import xe 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]="38024e6c-c1ef-5c15-8421-ac18d317e330")}catch{}})();var Me=null,Jt=null,or=null,ir=null,Qt=null,sr=null,ar=null,et=null,cr,rr=[],rc=new r_;function D(){return rc.getStore()}function ix(e){return rc.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var o_=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function nc(e){let t=xe.resolve(e);for(;;){if(n_(xe.join(t,".git")))return t;let n=xe.dirname(t);if(n===t)return;t=n}}function dr(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=nc(t)??xe.resolve(t),r=nc(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=xe.relative(n,xe.resolve(e)),i=o.length>0&&!o.startsWith(`..${xe.sep}`)&&o!==".."&&!xe.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(xe.sep).join("/")}:{}}}function sx(e){let t=D();if(t){t.hooks=e;return}Me=e}function ax(e){let t=D();if(t){t.commands=e;return}Jt=e}function cx(e){let t=D();if(t){t.parsers=e;return}or=e}function dx(e){let t=D();if(t){t.preflight=e;return}ir=e}function lx(e){let t=D();if(t){t.services=e;return}Qt=e}function ux(e){let t=D();if(t){t.renderers=e;return}sr=e}function fx(e){let t=D();if(t){t.registrations=e;return}ar=e}function Zt(){let e=D();return e?e.registrations:ar}function mx(){let e=D();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,Jt=null,or=null,ir=null,Qt=null,sr=null,ar=null,et=null,cr=null}function px(e){let t=e?{...e,...dr(e.pm_root)}:null,n=D();if(n){n.commandContext=t;return}et=t}function oc(){let e=D(),t=e?e.commandContext:et;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function ic(e){let t=D();if(t){t.commandResult=e;return}cr=e}function _x(){let e=D();return e?e.commandResult:cr}function si(e){if(!e)return;let t=D();t?t.affectedItems.push(e):rr.push(e)}function lr(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=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"||o_.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function yx(){let e=D(),t=e?.affectedItems??rr;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:rr=[],n}function gx(){let e=D();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,Jt=null,or=null,ir=null,Qt=null,sr=null,ar=null,et=null,cr=void 0,rr=[]}async function ue(e){let t=D(),n=t?t.hooks:Me;return n?$o(n,e):[]}async function ai(e){let t=D(),n=t?t.hooks:Me;n&&await Lo(n,e)}async function ge(e){let t=D(),n=t?t.hooks:Me;return n?Fo(n,e):[]}function ci(){let e=D();return((e?e.hooks:Me)?.onRead?.length??0)>0}async function hx(e){let t=D(),n=t?t.hooks:Me;return n?jo(n,e):[]}function sc(e){let t=D(),n=t?t.commands:Jt,r=t?t.commandContext:et;return!n||!r?{overridden:!1,result:e,warnings:[]}:Wo(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function bx(e){let t=D(),n=t?t.commands:Jt;return n?zo(n,{...e,...dr(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function wx(e){let t=D(),n=t?t.parsers:or;return n?Uo(n,{...e,...dr(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 Ex(e){let t=D(),n=t?t.preflight:ir;return n?qo(n,{...e,...dr(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 ac(e,t){let n=D(),r=n?n.renderers:sr,o=n?n.commandContext:et;return r?Ho(r,{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 cc(e,t){let n=D(),r=n?n.commandContext:et;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function Ie(e,t){let n=D(),r=n?n.services:Qt;return r?Vo(r,cc(e,t)):{handled:!1,result:t,warnings:[]}}function di(e,t){let n=D(),r=n?n.services:Qt;return r?Bo(r,cc(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]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var tt=new Set(ye),ur=Object.freeze({get size(){return tt.size},has(e){return tt.has(e)},entries(){return tt.entries()},keys(){return tt.keys()},values(){return tt.values()},forEach(e,t){tt.forEach(n=>e.call(t,n,n,ur))},[Symbol.iterator](){return tt.values()}});function dc(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function lc(e){return typeof e!="string"?null:Jn(e)}function i_(e){try{return structuredClone(e)}catch{return e}}function s_(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new w(`--field entries must use name=value syntax, received: ${e}`,b.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function a_(e){return`--${e.replaceAll("_","-")}`}function c_(e,t,n){try{let r=JSON.parse(e);if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r}catch{}throw new w(`--field ${t}=... must be valid JSON ${n}`,b.USAGE)}function d_(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new w(`--field ${e}=... must be a number`,b.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new w(`--field ${e}=... must be a number`,b.USAGE);return o}if(t==="boolean"){let r=n.trim().toLowerCase();if(r==="true"||r==="1"||r==="yes")return!0;if(r==="false"||r==="0"||r==="no")return!1;throw new w(`--field ${e}=... must be one of true|false|1|0|yes|no`,b.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):c_(n,e,t)}function li(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=dc(r.name),i=lc(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new w(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,b.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(o,{name:o,type:i})}return t}function uc(e){if(ur.has(e))throw new w(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...ur].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,b.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function fr(e){return[...li(e).keys()].sort((t,n)=>t.localeCompare(n))}function Ox(e,t){if(!e||e.length===0)return{};let n=li(t),r={};for(let o of e){let{key:i,value:s}=s_(o),a=n.get(i);if(!a){if(ur.has(i)){let d=a_(i);throw new w(`--field ${i} is a core item field, not an extension field`,b.USAGE,{code:"core_item_field_requires_dedicated_flag",field:i,recovery:{provided_fields:[i],suggested_flags:[d]},nextSteps:[`Set the core field with its dedicated flag: pm update <id> ${d} <value>`,`When closing an item, pm close <id> also accepts ${d} <value>.`]})}let c=[...n.keys()].sort((d,l)=>d.localeCompare(l));throw new w(`--field ${i} is not declared by an active extension item-field registration`,b.USAGE,{code:"extension_item_field_unknown",recovery:{provided_fields:c},nextSteps:c.length>0?[`Use one of the declared fields: ${c.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}uc(a.name),r[a.name]=d_(a.name,a.type,s)}return r}function l_(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(n=>typeof n=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function u_(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Rx(e,t,n={}){if(t){li(t);for(let r of t.item_fields)for(let o of r.fields){let i=dc(o.name);if(!i)continue;uc(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=i_(o.default));let s=e[i];if(s===void 0)continue;let a=lc(o.type);if(a&&!l_(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!u_(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}import fc 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]="febba42b-dfd0-549a-a6d9-c30edb321d9d")}catch{}})();var K=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),_c=mo,mi=fo,f_=["create","update"],m_=new Set(Ln),p_=new Set(mt),__=new Set($n),y_=new Set(Fn);function en(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function nt(e){return typeof e=="string"?e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_"):""}function fe(e){if(typeof e!="string"||e.length===0)return;let t=nt(e);return t.length>0?t:void 0}function g_(e){return e.startsWith("--")?e.slice(2):e}function mc(e){return typeof e=="string"?g_(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function yc(e){return e.replaceAll("_","-")}function h_(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function fi(e,t){let n=fe(e.id);if(!n)return null;let r=[...new Set(en(e.aliases).map(nt).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=en(e.roles).filter(a=>m_.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function b_(e){return{draft_status:fe(e?.draft_status),open_status:fe(e?.open_status),in_progress_status:fe(e?.in_progress_status),blocked_status:fe(e?.blocked_status),close_status:fe(e?.close_status),canceled_status:fe(e?.canceled_status)}}function gc(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=nt(t[0]),r=nt(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function w_(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)gc(n,r);return{typeKey:t.toLowerCase(),record:n}}function E_(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=w_(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)gc(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function hc(e){let t=nt(e.key??"");if(!t)return null;let n=nt(e.metadata_key??e.front_matter_key??t),r=mc(e.cli_flag??yc(t));if(!r)return null;let o=en(e.cli_aliases).map(l=>mc(l)).filter(l=>l.length>0&&l!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=p_.has(i)?i:"string",a=(()=>{let l=en(e.commands).filter(f=>__.has(f));return l.length>0?l:[...f_]})(),c=e.description?.trim(),d=en(e.required_types);return{key:t,metadata_key:n,cli_flag:r,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:e.repeatable===!0||s==="string_array",required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1}}function k_(e){let t=new Map;for(let[r,o]of e.entries()){let i=fi(o,r);i&&t.set(i.id,i)}let n=pc([...t.values()]);return n.length>0?n:pc(mi.map((r,o)=>fi(r,o)).filter(r=>r!==null))}function pc(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function v_(e){let t=new Map;for(let n of e??[]){let r=hc(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function S_(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 x_(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==yc(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}}function I_(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return y_.has(t)?t:"allow"}function he(e){let t={...K,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:mi,r=k_(n),o=v_(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(S_),fields:o.map(x_),workflow:{..._c,...b_(e?.workflow)},type_workflows:E_(e?.type_workflows),unknown_field_policy:I_(e?.unknown_field_policy)}}function T_(e){return`${JSON.stringify(e,null,2)}
|
|
4
|
+
`}function A_(){return{definitions:[]}}function C_(){return{statuses:mi}}function O_(){return{fields:[]}}function R_(){return{workflow:_c}}function N_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function D_(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 n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function P_(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 M_(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 L_(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 $_(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 X(e,t,n){let r=t?.trim()||n;return fc.isAbsolute(r)?r:fc.join(e,r)}function $x(e,t){return X(e,t.files.types,K.types)}async function bc(e,t){let n=he(t),r=[{path:X(e,n.files.types,K.types),seed:A_()},{path:X(e,n.files.statuses,K.statuses),seed:C_()},{path:X(e,n.files.fields,K.fields),seed:O_()},{path:X(e,n.files.workflows,K.workflows),seed:R_()}],o=[];for(let i of r)await ke(i.path)||(await Q(i.path,T_(i.seed)),o.push(i.path));return{created_paths:o}}async function wc(e,t){let n=he(t),r=[],o=X(e,n.files.types,K.types),i=X(e,n.files.statuses,K.statuses),s=X(e,n.files.fields,K.fields),a=X(e,n.files.workflows,K.workflows),c,d,l,f,p,m=async(J,q)=>{let dt=await Ce(J);if(dt!==null)return N_(dt,q,r)},h=await m(o,"runtime_schema_types_invalid_json");h!==void 0&&(c=D_(h),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let _=await m(i,"runtime_schema_statuses_invalid_json");_!==void 0&&(d=P_(_),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let y=await m(s,"runtime_schema_fields_invalid_json");y!==void 0&&(l=M_(y),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let T=await m(a,"runtime_schema_workflows_invalid_json");return T!==void 0&&(f=L_(T),f===void 0&&r.push("runtime_schema_workflows_invalid_shape"),p=$_(T)),{schema:he({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...f},type_workflows:[...n.type_workflows??[],...p??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function ui(e,t,n){let r=e.filter(i=>i.roles.includes(t));if(r.length>0)return r[0].id;let o=n.map(i=>fe(i)).filter(i=>typeof i=="string");for(let i of o)if(e.some(s=>s.id===i))return i;return e[0]?.id}function Ec(e){let t=he(e),n=t.statuses.map((_,y)=>fi(_,y)).filter(_=>_!==null),r=new Map,o=new Map;for(let _ of n){o.set(_.id,_),r.set(_.id,_.id),r.set(_.id.replaceAll("_","-"),_.id),r.set(_.id.replaceAll("_"," "),_.id);for(let y of _.aliases)r.set(y,_.id),r.set(y.replaceAll("_","-"),_.id),r.set(y.replaceAll("_"," "),_.id)}let i=new Set,s=new Set,a=new Set,c=new Set,d=new Set,l=new Set;for(let _ of n){let y=new Set(_.roles);(y.has("terminal")||y.has("terminal_done")||y.has("terminal_canceled"))&&i.add(_.id),y.has("terminal_done")&&s.add(_.id),y.has("terminal_canceled")&&a.add(_.id),y.has("active")&&c.add(_.id),y.has("blocked")&&d.add(_.id),y.has("draft")&&l.add(_.id)}let f=t.workflow,p=fe(f.open_status)??ui(n,"default_open",["open","in_progress",ft[0]]),m=fe(f.close_status)??ui(n,"default_close",["closed","done","complete"]),h=fe(f.canceled_status)??ui(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:i,terminal_done_statuses:s,terminal_canceled_statuses:a,active_statuses:c,blocked_statuses:d,draft_statuses:l,open_status:p,close_status:m,canceled_status:h}}function pi(e,t){let n=nt(e);if(n)return t.alias_to_id.get(n)}function kc(e){let t=he(e),n=new Map,r=t.fields.map(c=>hc(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.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,f)=>l.key.localeCompare(f.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function vc(e){return h_(e.key)}function Fx(e,t){let n=pi(e,t);return n?t.terminal_statuses.has(n):!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]="9bef4fe4-11a8-51ae-a42a-a93cc9c57384")}catch{}})();function _i(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[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function F_(e){return[...new Set([vc(e),_i(e.key),_i(e.cli_flag),...e.cli_aliases.map(t=>_i(t))])]}function Ic(e,t){for(let n of F_(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function Tc(e){return Array.isArray(e)?e.flatMap(t=>Tc(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 Sc(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 n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new w(`${t} must be one of true|false|1|0|yes|no`,b.USAGE)}function xc(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new w(`${t} must be a number`,b.USAGE);return r}function j_(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new w(`${t} must be valid JSON ${n}`,b.USAGE)}function tn(e,t,n){let r=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object"){let i=Array.isArray(t)?t[t.length-1]:t;return i===void 0?void 0:j_(i,r,e.type)}if(e.repeatable||e.type==="string_array"){let i=Tc(t);return e.type==="number"?i.map(s=>xc(s,r)):e.type==="boolean"?i.map(s=>Sc(s,r)):i}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?xc(o,r):e.type==="boolean"?Sc(o,r):typeof o=="string"?o:String(o)}function z_(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Bx(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=Ic(e,i);if(s===void 0){z_(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=tn(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function Vx(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=Ic(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=tn(s,a)))}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]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var ht=1,Ac=1;function Hx(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=ht?t:ht}function Cc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=ht))return e}function U_(e,t=Ac){return e<t?"outdated":e>t?"ahead":"current"}function Kx(e,t=Ac){let n=[],r=[];for(let o of e){let i=U_(o.version,t);i==="outdated"?n.push(o.ref):i==="ahead"&&r.push(o.ref)}return{outdated:n.sort((o,i)=>o.localeCompare(i)),ahead:r.sort((o,i)=>o.localeCompare(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]="d7501aa2-d3d9-5fbe-a1c0-d4bc145f5563")}catch{}})();var q_={"in-progress":"in_progress",cancelled:"canceled"};function mr(e,t){if(t){let o=pi(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=q_[n]??n;if(ft.includes(r))return r}function B_(e,t){return mr(e,t)??e}function Jx(e,t){return t.terminal_statuses.has(B_(e,t))}import{encode as K_}from"@toon-format/toon";import{isDeepStrictEqual as Oc}from"node:util";import{decode as V_}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]="2840e12e-7444-5d36-9f54-5a56267bbb75")}catch{}})();function yi(e){return{value:V_(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]="fedb7b50-6946-589d-b240-9f074e09e467")}catch{}})();var W_=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function H_(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(W_);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function pr(e){return H_(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]="a4c22692-fe27-5178-bba2-190ac3f80628")}catch{}})();var G_=new Set(["schema","tracker","auto"]),X_=new Set(["passed","failed","stopped","canceled"]),Y_=new Set(js);function Et(e){return e.replaceAll("\\","/")}function vi(e){for(let t of e)if(t!==0)return t;return 0}function yr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Pc=["id","title","description","created_at","updated_at"],J_=new Set(ye);function Mc(e){if(e?.schema)return{statusRegistry:Ec(e.schema),fieldRegistry:kc(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function Q_(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function $e(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new w(`Invalid item metadata: ${e}`,b.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function on(e,t){throw new w(t,b.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 Lc(e){let t=new Set(J_);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function v(e,t){e||$e(t)}function sn(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&$e(t),e}function gi(e,t){let n=e[t];v(typeof n=="string",`${t} must be a string`),v(Oe(n),`${t} must be a valid ISO timestamp`)}function Rc(e,t,n){let r=e[t];r!==void 0&&v(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function wi(e,t,n){let r=e[t];r!==void 0&&(v(typeof r=="string",`${n} must be a string`),v(Oe(r),`${n} must be a valid ISO timestamp`))}function Z_(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){v(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();v($t.includes(n),`event.recurrence.by_weekday entries must be one of: ${$t.join(", ")}`)}}}function ey(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)v(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function ty(e){if(e!==void 0){v(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)v(typeof t=="string","event.recurrence.exdates entries must be strings"),v(Oe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function ny(e){let t=sn(e,"event.recurrence must be an object");v(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();v(Un.includes(n),`event.recurrence.freq must be one of: ${Un.join(", ")}`),Rc(t,"interval","event.recurrence.interval"),Rc(t,"count","event.recurrence.count"),wi(t,"until","event.recurrence.until"),Z_(t.by_weekday),ey(t.by_month_day),ty(t.exdates)}function ry(e){for(let r of Pc)v(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;v(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&v(typeof n=="number"&&Number.isInteger(n)&&n>=ht,`pm_format_version must be an integer >= ${ht}`),t}function oy(e,t){let n=e.status;v(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=mr(n,r),i=r?r.definitions.map(s=>s.id):[...ft];v(o!==void 0,`status must be one of: ${i.join(", ")}`)}function iy(e){let t=e.priority;v(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;v(Array.isArray(n),"tags must be an array");for(let r of n)v(typeof r=="string","tags entries must be strings")}function sy(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){v(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||zn.includes(n);v(r,`confidence string value must be one of: ${[...zn,"med"].join(", ")}`);return}v(!1,"confidence must be a number or string")}}function ay(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&$e("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||jn.includes(n);v(r,`severity value must be one of: ${[...jn,"med"].join(", ")}`)}function cy(e){e.regression!==void 0&&typeof e.regression!="boolean"&&$e("regression must be a boolean")}function dy(e){let t=e.reminders;if(t!==void 0){v(Array.isArray(t),"reminders must be an array");for(let n of t){let r=sn(n,"reminders entries must be objects");v(typeof r.at=="string","reminder.at must be a string"),v(Oe(r.at),"reminder.at must be a valid ISO timestamp"),v(typeof r.text=="string","reminder.text must be a string"),v(r.text.trim().length>0,"reminder.text must not be empty")}}}function ly(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(v(typeof e[t]=="string",`event.${t} must be a string`),v(e[t].trim().length>0,`event.${t} must not be empty`))}function uy(e){e.recurrence!==void 0&&(ny(e.recurrence),e.recurrence.until!==void 0&&v(W(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function fy(e){let t=sn(e,"events entries must be objects");v(typeof t.start_at=="string","event.start_at must be a string"),v(Oe(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(v(typeof t.end_at=="string","event.end_at must be a string"),v(Oe(t.end_at),"event.end_at must be a valid ISO timestamp"),v(W(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),ly(t),t.all_day!==void 0&&v(typeof t.all_day=="boolean","event.all_day must be a boolean"),uy(t)}function my(e){let t=e.events;if(t!==void 0){v(Array.isArray(t),"events must be an array");for(let n of t)fy(n)}}function py(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&v(typeof n=="string",`${t} must be a string`)}}function _y(e){let t=e.type_options;if(t===void 0)return;let n=sn(t,"type_options must be an object");for(let[r,o]of Object.entries(n))v(r.trim().length>0,"type_options keys must be non-empty"),v(typeof o=="string","type_options values must be strings"),v(o.trim().length>0,"type_options values must be non-empty strings")}function yy(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){Q_(r,t)&&$e(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=tn(r,o,`metadata field "${r.metadata_key}"`)}catch(i){$e(String(i?.message).replace(/^Invalid\s+/u,""))}}}function gy(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Lc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?$e(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ei(e,t){let n=sn(e,"item metadata must be an object"),r=ry(n);oy(n,t),iy(n),sy(n),ay(n),cy(n),gi(n,"created_at"),gi(n,"updated_at"),n.deadline!==void 0&&gi(n,"deadline"),dy(n),my(n),wi(n,"closed_at","closed_at"),wi(n,"completed_at","completed_at"),py(n),_y(n),yy(n,r,t),gy(n,t)}function hy(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim().toLowerCase(),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,n)=>{let r=W(t.created_at,n.created_at);if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}function hi(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=W(t.created_at,n.created_at);if(r!==0)return r;let o=t.text.localeCompare(n.text);return o!==0?o:t.author.localeCompare(n.author)})}function by(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=W(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function wy(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Un.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>$t.includes(s)))).sort((s,a)=>ho(s)-ho(a)),r=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=>Oe(s)))).sort((s,a)=>W(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:n.length>0?n:void 0,by_month_day:r.length>0?r: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 Ey(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(ky).sort(vy)}function ky(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:wy(e.recurrence)};return yr(t),t}function vy(e,t){return vi([W(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 Sy(e){if(!(!e||e.length===0))return e.map(t=>({path:Et(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function xy(e){if(!e||e.length===0)return;let t=e.map(Ay).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>vi([W(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function bt(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Iy(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function bi(e){return typeof e=="string"?e:""}function Ty(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function Ay(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=X_.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:bi(e.started_at),finished_at:bi(e.finished_at),recorded_at:bi(e.recorded_at),attempt:Iy(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:bt(e.passed)??0,failed:bt(e.failed)??0,skipped:bt(e.skipped)??0,items:bt(e.items),linked_tests:bt(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Ty(e.measurements)};return yr(o),o}function Cy(e){if(!(!Array.isArray(e)||e.length===0))return[...e].map(Ny).sort(Dy)}function nn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function $c(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Si(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Nc(e){if(!$c(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Si(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Oy(e){if(!$c(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Si(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Ry(e){let t=e?.trim().toLowerCase();if(!(!t||!G_.has(t)))return t}function Ny(e){let t={command:e.command?.trim()||void 0,path:e.path?Et(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:Ry(e.pm_context_mode),env_set:Nc(e.env_set),env_clear:nn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:nn(e.assert_stdout_contains),assert_stdout_regex:nn(e.assert_stdout_regex),assert_stderr_contains:nn(e.assert_stderr_contains),assert_stderr_regex:nn(e.assert_stderr_regex),assert_stdout_min_lines:bt(e.assert_stdout_min_lines),assert_json_field_equals:Nc(e.assert_json_field_equals),assert_json_field_gte:Oy(e.assert_json_field_gte),note:e.note?.trim()||void 0};return yr(t),t}function Dy(e,t){return vi([e.scope.localeCompare(t.scope),_r(e.path,t.path),_r(e.command,t.command),Dc(e.timeout_seconds,t.timeout_seconds),_r(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,Le(e.env_clear,t.env_clear,[]),Le(e.env_set,t.env_set,{}),Le(e.assert_stdout_contains,t.assert_stdout_contains,[]),Le(e.assert_stdout_regex,t.assert_stdout_regex,[]),Le(e.assert_stderr_contains,t.assert_stderr_contains,[]),Le(e.assert_stderr_regex,t.assert_stderr_regex,[]),Dc(e.assert_stdout_min_lines,t.assert_stdout_min_lines),Le(e.assert_json_field_equals,t.assert_json_field_equals,{}),Le(e.assert_json_field_gte,t.assert_json_field_gte,{}),_r(e.note,t.note)])}function _r(e,t){return(e??"").localeCompare(t??"")}function Dc(e,t){return(e??0)-(t??0)}function Le(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function Py(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Et(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function k(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function My(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.id),i=k(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=k(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function Ly(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.path);if(!o)continue;let i={path:Et(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=k(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function $y(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.command),i=k(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Et(i));let a=k(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function Fy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.path);if(!o)continue;let i={path:Et(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=k(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function jy(e){if(e===null||typeof e!="object")return;let t=e,n=k(t.id),r=k(t.title),o=k(t.status),i=o&&Y_.has(o)?o:void 0,s=Nn(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return zy(d,t),d}function zy(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=k(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",My],["files","files",Ly],["tests","tests",$y],["docs","docs",Fy]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function Uy(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=jy(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function qy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=k(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=k(r.rationale);c&&(a.rationale=c);let d=k(r.evidence);d&&(a.evidence=d);let l=k(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function By(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=k(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=k(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function Vy(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=k(r.text);if(!o)continue;let i={text:o},s=k(r.command);s&&(i.command=s);let a=k(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function Wy(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function wt(e){let t=0;for(;t<e.length&&e[t]===`
|
|
5
|
+
`;)t+=1;return e.slice(t).trimEnd()}function Hy(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(zn.includes(t))return t}function Ky(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(jn.includes(t))return t}function rn(e){return e||void 0}function Gy(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Si(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function Xy(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=tn(r,o,`metadata field "${r.metadata_key}"`))}}function Yy(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Lc(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&$e(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function gr(e,t={}){let n=Mc(t),r=mr(e.status,n?.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:Cc(e.pm_format_version),source_type:k(e.source_type),type_options:Wy(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:hy(e.dependencies),comments:hi(e.comments),notes:hi(e.notes),learnings:hi(e.learnings),files:Sy(e.files),tests:Cy(e.tests),test_runs:xy(e.test_runs),docs:Py(e.docs),deadline:rn(e.deadline),reminders:by(e.reminders),events:Ey(e.events),closed_at:rn(e.closed_at),completed_at:rn(e.completed_at),assignee:k(e.assignee),claim_principal:k(e.claim_principal),source_owner:k(e.source_owner),author:rn(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:k(e.definition_of_ready),order:e.order,goal:k(e.goal),objective:k(e.objective),value:k(e.value),impact:k(e.impact),outcome:k(e.outcome),why_now:k(e.why_now),parent:k(e.parent),reviewer:k(e.reviewer),risk:e.risk??void 0,confidence:Hy(e.confidence),sprint:k(e.sprint),release:k(e.release),blocked_by:k(e.blocked_by),blocked_reason:k(e.blocked_reason),unblock_note:k(e.unblock_note),reporter:k(e.reporter),severity:Ky(e.severity),environment:k(e.environment),repro_steps:k(e.repro_steps),resolution:k(e.resolution),expected_result:k(e.expected_result),actual_result:k(e.actual_result),affected_version:k(e.affected_version),fixed_version:k(e.fixed_version),component:k(e.component),regression:e.regression,customer_impact:k(e.customer_impact),close_reason:rn(e.close_reason),plan_mode:k(e.plan_mode),plan_scope:k(e.plan_scope),plan_harness:k(e.plan_harness),plan_resume_context:k(e.plan_resume_context),plan_steps:Uy(e.plan_steps),plan_decisions:qy(e.plan_decisions),plan_discoveries:By(e.plan_discoveries),plan_validation:Vy(e.plan_validation)};return Gy(i,e),Xy(i,n),Yy(i,n),yr(i),i}function Fc(e){return x(e,ye)}function Jy(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function Qy(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=Jy(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function Zy(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
|
|
6
|
+
`,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function ki(e,t){return gr(e,{...t,onWarning:void 0})}function eg(e,t,n={}){let r=Zy(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=Qy(r.content);o||(e.trimStart().startsWith("{")&&on("json_markdown","JSON front matter is not valid JSON"),on("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{on("json_markdown","JSON front matter is not valid JSON")}return Ei(s,t),{metadata:ki(s,n),body:wt(i)}}function tg(e,t,n={}){let r;try{r=yi(e).value}catch{on("toon","TOON item document is not valid TOON")}v(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!Pc.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&on("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ei(o.front_matter,t),v(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:ki(o.front_matter,n),body:wt(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return v(i===void 0||typeof i=="string","TOON item document body must be a string"),Ei(s,t),{metadata:ki(s,n),body:wt(typeof i=="string"?i:"")}}function ng(e,t={}){let n=gr(e.metadata,t),r=Fc(n),o=JSON.stringify(r,null,2),i=wt(e.body??"");return i?`${o}
|
|
7
7
|
|
|
8
8
|
${i}
|
|
9
9
|
`:`${o}
|
|
10
|
-
`}function
|
|
11
|
-
`}function
|
|
12
|
-
`).reverse();for(let p of f.slice(0,4096)){let m=lg(p,e);if(m)return m}return}finally{br.closeSync(a)}}catch{return}}function fg(e,t,n,r){let o=Ai.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(Y(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return ug(e,t,n);if(s==="ai_agent_version"){let a=Y(n.AI_AGENT);return a?/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256):void 0}}function Xc(e){return e||(Wc.getStore()??{env:process.env,argv:process.argv})}function mg(e,t,n,r){let o=e.environment_keys.some(a=>Y(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return Bc(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||Bc(r,a));return o||i||s}function pg(e,t,n,r,o){let i=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,s=new Set([...Vc,...Object.keys(r?.provenance_environment_keys??{})]),a,c;s.has(e)&&(a=Y(n[i])?.slice(0,256),c=cg(t.argv??[],e));let d={...r?.provenance_environment_keys,model:r?.model_environment_keys},l={...t.client_info?.provenance,model:t.client_info?.model},f=[a,Ii(o?.provenance,e),Gc(n,d[e]),Ii(l,e),Ii(t.provenance,e),c,fg(e,t,n,r)];return["override","session","environment","mcp_client","host","argv","probe"].map((h,_)=>({value:f[_],source:h})).find(h=>h.value!==void 0)}function _g(e,t,n,r){let o=Object.keys(n?.provenance_environment_keys??{}),i=new Set([...Vc,...o,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),s={};for(let a of i){let c=pg(a,e,t,n,r);c?s[a]=c:n&&(a!=="version"||n.provenance_unavailable_dimensions.includes(a))&&(s[a]=null)}return s}function vI(e){let t=e.map(Er),n=new Map(Hc.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=vt.get(i.harness);if(s&&!ag(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=vt.get(i.harness);vt.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=vt.get(i.harness);!s||s.registrations<=1?vt.delete(i.harness):s.registrations-=1}}}}function SI(e,t){return Wc.run(e,t)}function xI(e,t,n={}){let r=e.map(Er);return Kc(r),Ai.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function Yc(e){let t=Xc(e),n=t.env??{},r=Kc(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(m=>m.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(m=>mg(m,n,o,i)),a=Uc(t,n),c=_g(t,n,s,a),d=c.model,l=[Gc(n,s?.session_environment_keys),Y(t.client_info?.session)?.slice(0,256)].find(m=>m!==void 0),f=s?.harness&&l?og("sha256").update(`pm-agent-instance:v1\0${s.harness}\0${l}`).digest("hex").slice(0,24):void 0,p=[["harness",s?.harness],["model",d?.value],["model_source",d?.source],["session",l],["instance",f],["provenance",Object.keys(c).length>0?c:void 0],["episode",a.episode]];return Object.fromEntries(p.filter(m=>m[1]!==void 0))}function II(){return process.env.PM_AUTHOR}function TI(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function AI(e){return Yc(e).harness}function yg(e,t,n){let r=Xc(n),o=Yc(r);if(e!==void 0){let s=Y(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=Y(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=Y(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Jc(e){let t=wr.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Qc(e){let t=wr.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 Zc(e){let t=wr.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function ed(e,t){let n=yg(e,t);return wr.enterWith(n),n.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]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function sn(e,t){let n=await Ce(e);if(n===null)return[];if(await ge({path:e,scope:"project"}),n.trim()==="")return[];let r=mr(n);if(r)throw new w(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,b.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 n.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new w(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,b.GENERIC_FAILURE)}}return 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]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();var gg="__pm_suppress_host_output",Ci="@unbrained/pm-cli:suppress-host-output:v1";function LI(e){return e===void 0?{__pm_suppress_host_output:Ci}:{__pm_suppress_host_output:Ci,result:e}}function td(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[gg]===Ci}(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]="c873f95b-c435-5b0d-a631-565fb195b5cd")}catch{}})();var kr="changed_fields",hg="changed_field_count",Oi="rows",bg=new Set(["apply","rollback"]),nd=new Set(["deleted","would_delete"]);function it(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function rd(e){let t=e[kr];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==kr&&(n[r]=o);return n[hg]=t.length,n}function wg(e){return"item"in e&&Array.isArray(e[kr])}function Eg(e){return typeof e.mode=="string"&&bg.has(e.mode)&&Array.isArray(e[Oi])}function kg(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Oi]=t,n}function vg(e){if(!it(e))return null;let t=it(e.item)?e.item:it(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&nd.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function Sg(e){if(!it(e)||!it(e.item)||typeof e.item.id!="string")return null;let t=e[kr];if(!Array.isArray(t))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&nd.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:t.length},r=typeof e.close_reason=="string"?e.close_reason:typeof e.item.close_reason=="string"?e.item.close_reason:void 0;return r!==void 0&&(n.close_reason=r),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings),n}function xg(e){let t=Eg(e)?e[Oi]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!it(o))return o;let i=rd(o);return i?(n=!0,i):o});return n?{projected:kg(e,r),changed:!0}:{projected:e,changed:!1}}function vr(e,t={}){if(t.idOnly===!0){let a=vg(e);if(a!==null)return a}if(t.compactEnvelope===!0){let a=Sg(e);if(a!==null)return a}if((t.changedFields??"full")==="full"||!it(e))return e;let r=!1,o=e,i=wg(e)?rd(e):null;i!==null&&(o=i,r=!0);let s=xg(o);return s.changed&&(o=s.projected,r=!0),r?o: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]="4a108e0e-0dfc-55c4-9f14-7395cfbac456")}catch{}})();var od='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',Ig={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","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history"],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"}},Tg=[{command:"activity",complete_mode:"full",omissions_by_mode:{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 UI(e,t,n){if(e&&t)throw new w(`${n} cannot be combined with --full`,b.USAGE)}function be(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function qI(e,t){let n=Tg.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return be([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return be(r)}var Ag=[{name:"hierarchy",restore_with:"--depth standard"},{name:"activity",restore_with:"--depth standard"},{name:"progress",restore_with:"--depth standard"},{name:"blockers",restore_with:"--depth standard"},{name:"recently_created",restore_with:"--depth standard"},{name:"unparented",restore_with:"--depth standard"},{name:"files",restore_with:"--depth deep"},{name:"workload",restore_with:"--depth standard"},{name:"staleness",restore_with:"--depth deep"},{name:"tests",restore_with:"--depth deep"},{name:"workspace_memory",restore_with:"--depth deep"}];function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cg(e){return de(e)&&typeof e.command=="string"&&e.command.trim().length>0&&(e.row_kind==="collection"||e.row_kind==="none")&&Array.isArray(e.row_keys)&&e.row_keys.every(t=>typeof t=="string"&&t.length>0)&&new Set(e.row_keys).size===e.row_keys.length&&(e.fields==="supported"||e.fields==="unsupported")&&(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 Og={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"]},Rg={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","blocked","held_by_others"],search:["items","projection"],activity:["compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history"],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 Ng(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=Og[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||de(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:od}:{}}}let o=Ig[r],i=Rg[r];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)=>de(d)?d[l]:void 0,t);return Array.isArray(c)||de(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:od}:{}}})()}function Dg(e){if(!de(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>de(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return be(r,new Set(o))}function Pg(e){if(Array.isArray(e.sections_included))return be(Ag,new Set(e.sections_included.filter(t=>typeof t=="string")))}function Mg(e){if(!de(e.item))return;let t=["children","claim_state","linked"].map(n=>({name:n,restore_with:`--fields ${n}`}));return be(t,new Set(t.flatMap(({name:n})=>e[n]===void 0?[]:[n])))}function id(e){if(de(e.projection))return be([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Lg(e){if(!de(e.projection))return be([]);if(typeof e.projection.mode=="string")return be([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function $g(e){if(!(!de(e.selected)||typeof e.selected.summary!="boolean"))return be([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function Fg(e,t){let n=Dg(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return Pg(t);if(r==="get")return Mg(t);if(r==="list"||r.startsWith("list-"))return id(t);if(r==="search")return id(t)??be([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return Lg(t);if(r==="contracts")return $g(t)}function sd(e,t){if(e===void 0||!de(t))return t;let n=t.row_contract,r=Cg(n)?n:Ng(e,t),o=r!==void 0?{...t,row_contract:r}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;if(de(o.omission_receipt))return o;let i=Fg(e,o);return i===void 0?o:{...o,omission_receipt:i}}import{createHash as jg}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]="83fe180b-9d95-5d19-9d3b-ba3821700e61")}catch{}})();var Ri=1,cd=4096,zg=/^[A-Za-z0-9_-]+$/;function ad(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function GI(e,t){let n=new Set;for(let r of t)if(r.cursor_semantics==="presentation"){n.add(ad(r.flag));for(let o of r.aliases??[])n.add(ad(o))}return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function XI(e,t){return jg("sha256").update(e).update("\0").update(ae(t)).digest("hex").slice(0,24)}function Ni(e,t,n,r){return Buffer.from(JSON.stringify({version:Ri,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function st(e){return new w(e,b.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]})}function Ug(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Ri&&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 Di(e,t){if(typeof e!="string")throw st("Query cursor is malformed.");let n=e.trim();if(n.length===0||n.length>cd||!zg.test(n))throw st("Query cursor is malformed.");let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw st("Query cursor is malformed.")}if(!Ug(r))throw st("Query cursor version or payload is unsupported.");let o=r;if(o.fingerprint!==t)throw st(`Query cursor does not match the current filters, sort, or query (${o.fingerprint} != ${t}).`);return{after_id:o.after_id,...o.after_index===void 0?{}:{after_index:o.after_index},...o.snapshot===void 0?{}:{snapshot:o.snapshot}}}function YI(e,t){return Di(e,t).after_id}function qg(e,t,n,r){if(t===void 0)return 0;let o=Di(t,n),i=e.findIndex(s=>r(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 JI(e,t){if(t.cursor!==void 0&&Di(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw st("Query cursor does not match the requested snapshot.");let n=qg(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:Ni(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var QI=Object.freeze({version:Ri,max_length:cd});(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]="64c4e6e1-d7c4-50e0-a444-fb2fa3c65443")}catch{}})();var Bg=8,Vg=64;function dd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Wg(e){let t=e.row_contract;return dd(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function Pi(e,t){return typeof e=="string"?e.length<=240?e:(t.compacted=!0,`${e.slice(0,240)}\u2026`):Array.isArray(e)?e.map(n=>Pi(n,t)):dd(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Pi(r,t)])):e}function an(e,t){let n=t.estimated_tokens;for(let r=0;r<Bg;r+=1){t.estimated_tokens=n;let o=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(o===n)return;n=o}t.estimated_tokens=n}function Hg(e,t,n){let r=Wg(e);for(let o=0;o<Vg;o+=1){if(an(e,t),t.estimated_tokens<=n)return;let i=r.map(s=>({key:s,rows:Array.isArray(e[s])?e[s]:[]})).filter(({rows:s})=>s.length>1).sort((s,a)=>a.rows.length-s.rows.length||s.key.localeCompare(a.key))[0];if(!i)return;i.rows.splice(-Math.max(1,Math.ceil(i.rows.length/2))),t.rows_compacted=!0,e.has_more=!0,e.truncated=!0,typeof e.count=="number"&&(e.count=r.reduce((s,a)=>s+(Array.isArray(e[a])?e[a].length:0),0))}}function ld(e,t,n){let r={compacted:!1},o=Pi(e,r);return t.strings_compacted=r.compacted,o.read_output=t,Hg(o,t,n),an(o,t),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]="27431a6b-6f2e-5020-b4f1-b94cfa8a1c26")}catch{}})();var St=["include","amount","cost","encoding"],_d=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate"],yd=["canonical","legacy","intent","default"],Li={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},oT=Object.freeze(St.map(e=>Li[e])),Kg={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","--verbose"]},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","--verbose"]},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:{}},Gg=new Set(["--fields","--section"]),Xg=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.","--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.","--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."});function gd(e){return e.slice(2).replaceAll("-","_")}function Yg(e,t){let n=Xg[e];if(n!==void 0)return n;let r=t==="include"?Gg.has(e)?"<csv>":gd(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Li[t]} ${r}.`}function Jg(e){let t=Kg[e],n=Object.freeze(Object.fromEntries(St.map(r=>[r,Object.freeze({dimension:r,canonical_option:Li[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,migration_hint:Yg(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:yd})}var Qg=Object.freeze(_d.map(Jg)),Zg=new Map(Qg.map(e=>[e.command,e]));function hd(e){let t=e.trim().toLowerCase().split(/\s+/u)[0],n=t.startsWith("list-")?"list":t==="ctx"?"context":t;return _d.includes(n)?n:void 0}var eh=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format"],th={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"]};function nh(e){return eh.some(t=>e[t]!==void 0)}var rh=[{keys:["outputInclude","output_include"],valid:e=>Mi(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||xt(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>xt(e)!==void 0,message:"--output-budget must be a positive integer."},{keys:["outputFormat","output_format"],valid:e=>e==="toon"||e==="json",message:"--output-format must be toon or json."}];function iT(e,t){if(!nh(t))return;let n=hd(e);if(!n)throw new w(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,b.USAGE);if((th[n]??[]).some(r=>t[r]!==void 0&&t[r]!==!1))throw new w(`Universal output controls cannot be combined with a ${n} mutation.`,b.USAGE);for(let r of rh){let o=r.keys.map(i=>t[i]).find(i=>i!==void 0);if(o!==void 0&&!r.valid(o))throw new w(r.message,b.USAGE)}}function oh(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function ih(e,t){let n=oh(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function sh(e){return e!==void 0&&e!==!1&&e!==null}function Mi(e){let n=(Array.isArray(e)?e:[e]).flatMap(r=>typeof r=="string"?r.split(","):[]).map(r=>r.trim()).filter(Boolean);return n.length>0?[...new Set(n)]:void 0}function xt(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 ah(e,t,n){for(let r of e.legacy_aliases){let o=ih(t,r.flag),i={value:o,flag:r.flag};if(sh(o)&&n(i))return i}}function ud(e,t){let n=Mi(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Mi(t.value)??[gd(t.flag)]}}function fd(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=xt(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=xt(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function md(e,t){let n=xt(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=xt(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function pd(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 bd(e,t){let n=hd(e);if(!n)return;let r=Zg.get(n),o={include:c=>ud(void 0,c),amount:c=>fd(void 0,c),cost:c=>md(void 0,c),encoding:c=>pd(void 0,c)},i=Object.fromEntries(St.map(c=>[c,ah(r.dimensions[c],t,d=>o[c](d)!==void 0)])),s=St.flatMap(c=>{let d=i[c];return d?[d.flag]:[]}),a=St.flatMap(c=>{let d=i[c];return d?[r.dimensions[c].legacy_aliases.find(f=>f.flag===d.flag).migration_hint]:[]});return{command:n,include:ud(t.outputInclude??t.output_include,i.include),amount:fd(t.outputLimit??t.output_limit,i.amount),cost:md(t.outputBudget??t.output_budget,i.cost),encoding:pd(t.outputFormat??t.output_format,i.encoding),legacy_aliases_used:s,migration_hints:a,precedence:yd}}function Sr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var ch=new Set(["applied_bound","applied_limit","completeness","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","row_contract","sorting","total","truncated"]);function wd(e){let t=e.row_contract;return Sr(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function dh(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function lh(e,t){let n=wd(e),r=t.some(o=>Object.hasOwn(e,o.split(".")[0]));return n.length>0&&!r?Object.fromEntries(Object.entries(e).map(([o,i])=>[o,n.includes(o)&&Array.isArray(i)?i.map(s=>Sr(s)?dh(s,t):s):i])):Object.fromEntries(Object.entries(e).filter(([o])=>t.some(i=>i.split(".")[0]===o)||ch.has(o)))}function uh(e,t){if(t==="unbounded")return e;let n=!1,r=wd(e),o=new Set(r),i=Object.fromEntries(Object.entries(e).map(([s,a])=>!o.has(s)||!Array.isArray(a)||a.length<=t?[s,a]:(n=!0,[s,a.slice(0,t)])));return n&&(i.has_more=!0,i.truncated=!0,typeof i.count=="number"&&(i.count=r.reduce((s,a)=>s+(Array.isArray(i[a])?i[a].length:0),0)),i.applied_bound={kind:"output_limit",source:"explicit",value:t}),i}function fh(e){return St.filter(t=>e[t]!==void 0)}function Ed(e,t,n){let r=bd(e,t);if(!r)return n;let o=fh(r);if(o.filter(d=>r[d]?.source==="canonical").length===0)return n;let s={...n};r.include?.source==="canonical"&&(s=lh(s,r.include.value)),r.amount?.source==="canonical"&&(s=uh(s,r.amount.value));let a={contract_version:1,command:r.command,requested_dimensions:o,precedence:r.precedence,legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};s.read_output=a,an(s,a);let c=r.cost?.source==="canonical"?r.cost.value:void 0;if(c!==void 0&&a.estimated_tokens>c&&(s=ld(s,a,c)),c!==void 0&&a.estimated_tokens>c){let d={contract_version:1,command:r.command,requested_dimensions:o,precedence:r.precedence,legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0},l={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Increase --output-budget or narrow the read."},read_output:d};return an(l,d),l}return s}function sT(e){return Sr(e)&&Sr(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function kd(e,t){let n=bd(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}import{AsyncLocalStorage as mh}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]="e48a306e-debb-5e66-ae9b-68bf17fa405f")}catch{}})();var Sd=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:2400,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"}]),xd=new mh;function ph(){return xd.getStore()??Sd}function pT(e,t){return xd.run(yh(e.workspaceContracts,e.packageContracts),t)}function _h(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))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:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function yh(e=[],t=[]){let n=[{source:"core",contracts:Sd,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=_h(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&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function Id(e,t,n=ph()){let r=e.trim().toLowerCase(),o=t.trim().toLowerCase(),i=n.find(d=>d.command===r&&d.intent===o);if(i)return{...i,source:i.source??"core"};let s=n.filter(d=>d.command===r).map(d=>d.intent);if(s.length===0)return;let a=s.map(d=>{let l=Array.from({length:o.length+1},(f,p)=>p);for(let f=1;f<=d.length;f+=1){let p=l[0];l[0]=f;for(let m=1;m<=o.length;m+=1){let h=l[m];l[m]=Math.min(l[m]+1,l[m-1]+1,p+(d[f-1]===o[m-1]?0:1)),p=h}}return{candidate:d,distance:l[o.length]}}).sort((d,l)=>d.distance-l.distance||d.candidate.localeCompare(l.candidate))[0].candidate,c=`pm ${r} --for ${a}`;throw new w(`Unknown context intent "${o}" for ${r}. Did you mean "${a}"?`,b.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",required:`Use a declared ${r} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[c],recovery:{recovery_mode:"compact",attempted_command:`pm ${r} --for ${o}`,suggested_retry:c}})}var Td={context:(e,t,n)=>{e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard"),e.section===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]);let r=Ir(e.tokenBudget,t.token_budget),o=Math.max(1,Math.floor((r-800)/500)),i=String(n?o:Math.min(20,o));e.limit===void 0&&(e.limit=i),e.activityLimit===void 0&&(e.activityLimit=i)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{if(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"),e.limit===void 0){let r=Ir(e.tokenBudget,t.token_budget),o=Math.max(2,Math.floor((r-520)/16));e.limit=String(n?o:Math.min(100,o))}},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{if(e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0),e.limit===void 0){let r=Ir(e.tokenBudget,t.token_budget),o=Math.max(2,Math.floor((r-480)/16));e.limit=String(n?o:Math.min(100,o))}}};function _T(e,t){let n=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(n!==void 0&&(e==="get"||e==="list"||e==="search"))throw new w("--token-budget requires a declared context intent selected with --for",b.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 s={...t,tokenBudget:n};return delete s.token_budget,s}let r=Id(e,t.for),o=Fi(n)!==void 0,i={...t};return i.tokenBudget===void 0&&n!==void 0&&(i.tokenBudget=n),delete i.token_budget,i.tokenBudget===void 0&&(i.tokenBudget=String(r.token_budget)),Td[e](i,r,o),i}var gh={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},xr=256;function $i(e){return Array.isArray(e)?e.map($i):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,$i(n)])):typeof e=="string"&&e.length>240?`${e.slice(0,240)}\u2026`:e}function Fi(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 Ir(e,t){let n=Fi(e);if(n===void 0)return t;if(n<xr)throw new w(`Context intent token budget must be at least ${xr}`,b.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${xr}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${xr} or omit the override.`]});return n}function $e(e,t){let n=t.estimated_tokens;for(;;){t.estimated_tokens=n;let r=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(r===n)return;n=r}}var vd={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","blocked","held_by_others"],search:["items"]};function Ad(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 hh(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 bh(e,t,n){let r=!1;for(;;){if($e(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)return r;let o=Buffer.byteLength(JSON.stringify(n),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/n.length)))))),r=!0}}function wh(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=Ad(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=bh(e,t,r)||d,!d)return!1;let l=hh(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),$e(e,t),!1;if(e.next_cursor=Ni(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),$e(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function Eh(e,t,n,r){if(e==="list"||e==="search")return wh(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if($e(t,n),n.estimated_tokens<=n.token_budget)return o;let i=vd[e].map(p=>({key:p,rows:Array.isArray(t[p])?t[p]:[]})).filter(({rows:p})=>p.length>0).sort((p,m)=>m.rows.length-p.rows.length||p.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=vd[e].reduce((p,m)=>p+(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=(n.estimated_tokens-n.token_budget)*4,f=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-f,f),o=!0}}function kh(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in Td))return n;let o=r,i=Id(o,t.for),s={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:Ir(t.tokenBudget??t.token_budget,i.token_budget),estimated_tokens:0,within_budget:!0,degradation:gh[o],declaration_feasible:!0,result_omitted:!1},a={...n};if(o==="list"||o==="search"){let d=o==="list"?520:480,l=Math.max(2,Math.floor((s.token_budget-d)/16)),p=Fi(t.tokenBudget??t.token_budget)!==void 0?l:Math.min(100,l),m=t.limit!==void 0;s.budget_derived_limit=p,s.binding_constraint=m?"explicit_limit":"token_budget",s.limit_reason=m?"The caller supplied an explicit row limit; the budget-derived limit remains diagnostic.":"The selected intent token budget determines the row ceiling.",a.budget_derived_limit=p}let c={...a,context_intent:s};return $e(c,s),s.estimated_tokens>s.token_budget&&(s.degradation="recursive_budget_compaction",c={...$i(a),context_intent:s},$e(c,s)),s.estimated_tokens>s.token_budget&&Eh(o,c,s,t)&&(s.degradation="budget_row_compaction",$e(c,s)),s.estimated_tokens>s.token_budget&&(s.degradation="budget_receipt_only",s.declaration_feasible=!1,s.result_omitted=!0,s.within_budget=!1,c={budget_exceeded:{omitted_result:!0,reason:"declared_budget_infeasible",restore_with:"Increase --token-budget or narrow the request; the unprojected command may be larger."},context_intent:s},$e(c,s)),c}function vh(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=Ad(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function Cd(e,t,n){let r=sd(e,n);return typeof r=="object"&&r!==null&&!Array.isArray(r)?Ed(e??"",t,vh(t,kh(e??"",t,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]="15daa637-4d30-5794-bdb5-87585d443cd3")}catch{}})();var Sh=[..._e],xh=[...Mt],Ih=[...Sn],hT=[...xn],bT=[...In],Th=[...Tn],Tr=["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-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","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],wT=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],Ah=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Od={help:"Commander help rendering has no SDK operation result.",item:"The item namespace only groups lifecycle subcommands already exposed as actions.",packages:"The plural package alias only renders package-oriented help."},Rd=Object.freeze(Tr.flatMap(e=>e in Od?[]:e==="extension"||e==="package"?[...Ah.map(t=>`${e}-${t}`),e]:[e]));function ET(e=Tr,t=Rd,n=Od){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i))}}function kT(e){return Rd.includes(e)}function vT(e){return Sh.includes(e)}function ST(e){return xh.includes(e)}function xT(e){return Ih.includes(e)}function IT(e){return Th.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]="7db1cef2-4ff1-5f62-ad68-88933e25d59b")}catch{}})();var Ch=["full","compact","brief","summary","counts"],CT=["mutation","read","discovery","governance"],Oh=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"]),Rh=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Nh=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Dh={mutation:2e3,read:4e3,discovery:3e3,governance:6e3};function Ph(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");return e}var Mh=Tr.map(e=>{let t=Oh.has(e)?"mutation":Rh.has(e)?"discovery":Nh.has(e)?"governance":"read";return Ph({command:e,budget_class:t,default_max_estimated_tokens:Dh[t],degradation_ladder:Ch,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}),Lh=new Map(Mh.map(e=>[e.command,e]));function OT(e){let[t]=e.trim().split(/\s+/u);return Lh.get(t)??null}function Ar(e){return Math.ceil(Math.max(0,e)/4)}(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]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();var It=["result_rows","envelope","diagnostics","hints"],$h=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,Fh=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,jh=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,zh=8;function ji(e){return Buffer.byteLength(e,"utf8")}function Nd(e){return ji(JSON.stringify(e)??"null")}function Uh(e,t){return Fh.test(e)?"diagnostics":jh.test(e)?"hints":$h.test(e)||Array.isArray(t)?"result_rows":"envelope"}function qh(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"]=Nd(e),t;for(let[n,r]of Object.entries(e))t[Uh(n,r)]+=Nd({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function Bh(e,t){let n=It.reduce((s,a)=>s+t[a],0),r=It.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-It.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||It.indexOf(a.section)-It.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Dd(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Pd(e,t){let n=ji(t(e)),r=Bh(n,qh(e)),o=Object.fromEntries(It.map(a=>[a,{bytes:r[a],estimated_tokens:Ar(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:Ar(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Dd(e,i);for(let a=0;a<zh;a+=1){let c=ji(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Ar(c)},s=Dd(e,i)}return 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]="816ae182-02ba-56a9-8204-7474e30322bc")}catch{}})();var Ui="__pm_native_output",Md=!1;function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vh(e){return re(e)&&e[Ui]===!0}function Wh(e){if(!re(e)||e[Ui]!==!0)return e;let{[Ui]:t,...n}=e;return n}function qi(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Hh(){(process.exitCode===void 0||process.exitCode===b.SUCCESS)&&(process.exitCode=b.SUCCESS)}function Kh(){(process.exitCode===void 0||process.exitCode===b.SUCCESS)&&(process.exitCode=b.GENERIC_FAILURE)}function Bi(e){if(e==="stdout"){Hh();return}Kh()}function Ld(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function Gh(){Md||(Md=!0,process.stdout.on("error",e=>{if(qi(e)){Bi("stdout");return}Ld(e)}),process.stderr.on("error",e=>{if(qi(e)){Bi("stderr");return}Ld(e)}))}function Fd(e,t){Gh();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(qi(n))return Bi(e),!1;throw n}}function Xh(e){return Fd("stdout",e)}function cn(e){return Fd("stderr",e)}function zi(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Cr(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>Cr(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(re(e)){let t={};for(let[n,r]of Object.entries(e)){if(n==="omitted_field_groups"&&Array.isArray(r)&&r.length===0){t[n]=[];continue}let o=Cr(r);o!==void 0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}return e}}function Vi(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":e.map(r=>{if(!re(r)&&!Array.isArray(r))return`${n}- ${zi(r)}`;let i=Vi(r,t+1).split(`
|
|
10
|
+
`}function rg(e,t={}){let n=gr(e.metadata,t),r=Fc(n),o=wt(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=K_(s),c;try{c=yi(a).value}catch(d){throw new w("Refusing to persist a TOON item document that the configured decoder cannot read back.",b.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(!Oc(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(f=>!Oc(s[f],d[f]))??"document";throw new w(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,b.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}
|
|
11
|
+
`}function hr(e,t={}){let n=pr(e);if(n)throw new w(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,b.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 r=t.format??"toon",o=Mc(t);return r==="toon"?tg(e,o,t):eg(e,o,t)}function jc(e,t={}){return(t.format??"toon")==="toon"?rg(e,t):ng(e,t)}function me(e,t={}){return{metadata:gr(e.metadata,t),body:wt(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]="4d71277c-e16c-56f4-a834-5200acfa6d7a")}catch{}})();function zc(e){return e}import{AsyncLocalStorage as og}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]="16109ee9-e684-5d25-a5f4-30a6c4f62bd5")}catch{}})();var xi=new og,Uc=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function br(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function rt(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=br(n.id,128),o=br(n.parent_id,128);if(r===void 0||!Uc.test(r)||o!==void 0&&!Uc.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=br(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function kt(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=br(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function ig(e,t,n){let r=xi.getStore(),o=kt({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=rt(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...kt(r?.provenance),...o,...kt(e?.provenance)},a=rt(e?.episode,!1)??rt(n,!1)??i??rt(r?.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 qc(e,t){return ig(e.session_context,t,e.client_info?.episode)??{}}function bI(e,t){let n=xi.getStore(),r=rt(e.episode,!0),o=rt(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...kt(n?.provenance),...kt(e.provenance)};return xi.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function wI(e){let t=kt(e.provenance),n=rt(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{AsyncLocalStorage as Ai}from"node:async_hooks";import{createHash as sg}from"node:crypto";import wr from"node:fs";import ag from"node:os";import Bc 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]="0139d8ef-d286-571f-89f8-7de2f8422f22")}catch{}})();var Wc=["model","effort","role","topic","version"],Er=new Ai,Hc=new Ai,Ci=new Ai,cg=[{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"],role:["CLAUDE_CODE_CHILD_SESSION"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["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:{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:[]}],vt=new Map,Ii=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Y(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function ot(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function kr(e){let t=e.harness.trim().toLowerCase();if(!Ii.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:ot(e.environment_keys),model_environment_keys:ot(e.model_environment_keys),session_environment_keys:ot(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),ot(r)]).filter(([n])=>Ii.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&Ii.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"))),provenance_unavailable_dimensions:ot(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:ot(e.argv_markers).map(n=>n.toLowerCase()),client_names:ot(e.client_names).map(n=>n.toLowerCase())}}var Kc=cg.map(kr);function dg(e,t){return JSON.stringify(e)===JSON.stringify(t)}function Vc(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function Gc(e=[]){let t=[...Kc,...[...vt.values()].map(r=>r.descriptor),...Ci.getStore()?.descriptors??[],...e.map(kr)],n=new Set;for(let r of t){if(n.has(r.harness))throw new Error(`Harness signal descriptor collision for "${r.harness}"`);n.add(r.harness)}return t}function Xc(e,t){for(let n of t??[]){let r=Y(e[n]);if(r)return r.slice(0,256)}}function lg(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return Y(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return Y(i.slice(s.length+1))?.slice(0,256)}}function Ti(e,t){return Y(e?.[t])?.slice(0,256)}var ug=1048576;function fg(e,t){if(e.length===0||e.length>262144)return;let n;try{n=JSON.parse(e)}catch{return}if(typeof n!="object"||n===null)return;let r=n,o=typeof r.message=="object"&&r.message!==null?r.message:void 0,i=t==="model"?o?.model:r.version;return Y(i)?.slice(0,256)}function mg(e,t,n){let r=Y(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=Bc.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=Bc.join(t.home_dir??ag.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=wr.openSync(s,"r");try{let c=wr.fstatSync(a).size,d=Math.min(c,ug),l=Buffer.alloc(d);wr.readSync(a,l,0,d,Math.max(0,c-d));let f=l.toString("utf8").split(`
|
|
12
|
+
`).reverse();for(let p of f.slice(0,4096)){let m=fg(p,e);if(m)return m}return}finally{wr.closeSync(a)}}catch{return}}function pg(e,t,n,r){let o=Ci.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(Y(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return mg(e,t,n);if(s==="ai_agent_version"){let a=Y(n.AI_AGENT);return a?/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256):void 0}}function Yc(e){return e||(Hc.getStore()??{env:process.env,argv:process.argv})}function _g(e,t,n,r){let o=e.environment_keys.some(a=>Y(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return Vc(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||Vc(r,a));return o||i||s}function yg(e,t,n,r,o){let i=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,s=new Set([...Wc,...Object.keys(r?.provenance_environment_keys??{})]),a,c;s.has(e)&&(a=Y(n[i])?.slice(0,256),c=lg(t.argv??[],e));let d={...r?.provenance_environment_keys,model:r?.model_environment_keys},l={...t.client_info?.provenance,model:t.client_info?.model},f=[a,Ti(o?.provenance,e),Xc(n,d[e]),Ti(l,e),Ti(t.provenance,e),c,pg(e,t,n,r)];return["override","session","environment","mcp_client","host","argv","probe"].map((h,_)=>({value:f[_],source:h})).find(h=>h.value!==void 0)}function gg(e,t,n,r){let o=Object.keys(n?.provenance_environment_keys??{}),i=new Set([...Wc,...o,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),s={};for(let a of i){let c=yg(a,e,t,n,r);c?s[a]=c:n&&(a!=="version"||n.provenance_unavailable_dimensions.includes(a))&&(s[a]=null)}return s}function AI(e){let t=e.map(kr),n=new Map(Kc.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=vt.get(i.harness);if(s&&!dg(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=vt.get(i.harness);vt.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=vt.get(i.harness);!s||s.registrations<=1?vt.delete(i.harness):s.registrations-=1}}}}function CI(e,t){return Hc.run(e,t)}function OI(e,t,n={}){let r=e.map(kr);return Gc(r),Ci.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function Jc(e){let t=Yc(e),n=t.env??{},r=Gc(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(m=>m.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(m=>_g(m,n,o,i)),a=qc(t,n),c=gg(t,n,s,a),d=c.model,l=[Xc(n,s?.session_environment_keys),Y(t.client_info?.session)?.slice(0,256)].find(m=>m!==void 0),f=s?.harness&&l?sg("sha256").update(`pm-agent-instance:v1\0${s.harness}\0${l}`).digest("hex").slice(0,24):void 0,p=[["harness",s?.harness],["model",d?.value],["model_source",d?.source],["session",l],["instance",f],["provenance",Object.keys(c).length>0?c:void 0],["episode",a.episode]];return Object.fromEntries(p.filter(m=>m[1]!==void 0))}function RI(){return process.env.PM_AUTHOR}function NI(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function DI(e){return Jc(e).harness}function hg(e,t,n){let r=Yc(n),o=Jc(r);if(e!==void 0){let s=Y(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=Y(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=Y(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Qc(e){let t=Er.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Zc(e){let t=Er.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 ed(e){let t=Er.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function td(e,t){let n=hg(e,t);return Er.enterWith(n),n.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]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function an(e,t){let n=await Ce(e);if(n===null)return[];if(await ge({path:e,scope:"project"}),n.trim()==="")return[];let r=pr(n);if(r)throw new w(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,b.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 n.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new w(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,b.GENERIC_FAILURE)}}return 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]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();var bg="__pm_suppress_host_output",Oi="@unbrained/pm-cli:suppress-host-output:v1";function UI(e){return e===void 0?{__pm_suppress_host_output:Oi}:{__pm_suppress_host_output:Oi,result:e}}function nd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[bg]===Oi}(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]="c873f95b-c435-5b0d-a631-565fb195b5cd")}catch{}})();var vr="changed_fields",wg="changed_field_count",Ri="rows",Eg=new Set(["apply","rollback"]),rd=new Set(["deleted","would_delete"]);function it(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function od(e){let t=e[vr];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==vr&&(n[r]=o);return n[wg]=t.length,n}function kg(e){return"item"in e&&Array.isArray(e[vr])}function vg(e){return typeof e.mode=="string"&&Eg.has(e.mode)&&Array.isArray(e[Ri])}function Sg(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Ri]=t,n}function xg(e){if(!it(e))return null;let t=it(e.item)?e.item:it(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&rd.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function Ig(e){if(!it(e)||!it(e.item)||typeof e.item.id!="string")return null;let t=e[vr];if(!Array.isArray(t))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&rd.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:t.length},r=typeof e.close_reason=="string"?e.close_reason:typeof e.item.close_reason=="string"?e.item.close_reason:void 0;return r!==void 0&&(n.close_reason=r),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings),n}function Tg(e){let t=vg(e)?e[Ri]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!it(o))return o;let i=od(o);return i?(n=!0,i):o});return n?{projected:Sg(e,r),changed:!0}:{projected:e,changed:!1}}function Sr(e,t={}){if(t.idOnly===!0){let a=xg(e);if(a!==null)return a}if(t.compactEnvelope===!0){let a=Ig(e);if(a!==null)return a}if((t.changedFields??"full")==="full"||!it(e))return e;let r=!1,o=e,i=kg(e)?od(e):null;i!==null&&(o=i,r=!0);let s=Tg(o);return s.changed&&(o=s.projected,r=!0),r?o: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]="4a108e0e-0dfc-55c4-9f14-7395cfbac456")}catch{}})();var id='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',Ag={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","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history"],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"}},Cg=[{command:"activity",complete_mode:"full",omissions_by_mode:{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 HI(e,t,n){if(e&&t)throw new w(`${n} cannot be combined with --full`,b.USAGE)}function be(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function KI(e,t){let n=Cg.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return be([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return be(r)}var Og=[{name:"hierarchy",restore_with:"--depth standard"},{name:"activity",restore_with:"--depth standard"},{name:"progress",restore_with:"--depth standard"},{name:"blockers",restore_with:"--depth standard"},{name:"recently_created",restore_with:"--depth standard"},{name:"unparented",restore_with:"--depth standard"},{name:"files",restore_with:"--depth deep"},{name:"workload",restore_with:"--depth standard"},{name:"staleness",restore_with:"--depth deep"},{name:"tests",restore_with:"--depth deep"},{name:"workspace_memory",restore_with:"--depth deep"}];function de(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rg(e){return de(e)&&typeof e.command=="string"&&e.command.trim().length>0&&(e.row_kind==="collection"||e.row_kind==="none")&&Array.isArray(e.row_keys)&&e.row_keys.every(t=>typeof t=="string"&&t.length>0)&&new Set(e.row_keys).size===e.row_keys.length&&(e.fields==="supported"||e.fields==="unsupported")&&(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 Ng={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"]},Dg={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","blocked","held_by_others"],search:["items","projection"],activity:["compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history"],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 Pg(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=Ng[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||de(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:id}:{}}}let o=Ag[r],i=Dg[r];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)=>de(d)?d[l]:void 0,t);return Array.isArray(c)||de(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:id}:{}}})()}function Mg(e){if(!de(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>de(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return be(r,new Set(o))}function Lg(e){if(Array.isArray(e.sections_included))return be(Og,new Set(e.sections_included.filter(t=>typeof t=="string")))}function $g(e){if(!de(e.item))return;let t=["children","claim_state","linked"].map(n=>({name:n,restore_with:`--fields ${n}`}));return be(t,new Set(t.flatMap(({name:n})=>e[n]===void 0?[]:[n])))}function sd(e){if(de(e.projection))return be([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function Fg(e){if(!de(e.projection))return be([]);if(typeof e.projection.mode=="string")return be([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function jg(e){if(!(!de(e.selected)||typeof e.selected.summary!="boolean"))return be([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function zg(e,t){let n=Mg(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return Lg(t);if(r==="get")return $g(t);if(r==="list"||r.startsWith("list-"))return sd(t);if(r==="search")return sd(t)??be([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return Fg(t);if(r==="contracts")return jg(t)}function ad(e,t){if(e===void 0||!de(t))return t;let n=t.row_contract,r=Rg(n)?n:Pg(e,t),o=r!==void 0?{...t,row_contract:r}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;if(de(o.omission_receipt))return o;let i=zg(e,o);return i===void 0?o:{...o,omission_receipt:i}}import{createHash as Ug}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]="83fe180b-9d95-5d19-9d3b-ba3821700e61")}catch{}})();var Ni=1,dd=4096,qg=/^[A-Za-z0-9_-]+$/;function cd(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function ZI(e,t){let n=new Set;for(let r of t)if(r.cursor_semantics==="presentation"){n.add(cd(r.flag));for(let o of r.aliases??[])n.add(cd(o))}return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function eT(e,t){return Ug("sha256").update(e).update("\0").update(ae(t)).digest("hex").slice(0,24)}function Di(e,t,n,r){return Buffer.from(JSON.stringify({version:Ni,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function st(e){return new w(e,b.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]})}function Bg(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Ni&&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 Pi(e,t){if(typeof e!="string")throw st("Query cursor is malformed.");let n=e.trim();if(n.length===0||n.length>dd||!qg.test(n))throw st("Query cursor is malformed.");let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw st("Query cursor is malformed.")}if(!Bg(r))throw st("Query cursor version or payload is unsupported.");let o=r;if(o.fingerprint!==t)throw st(`Query cursor does not match the current filters, sort, or query (${o.fingerprint} != ${t}).`);return{after_id:o.after_id,...o.after_index===void 0?{}:{after_index:o.after_index},...o.snapshot===void 0?{}:{snapshot:o.snapshot}}}function tT(e,t){return Pi(e,t).after_id}function Vg(e,t,n,r){if(t===void 0)return 0;let o=Pi(t,n),i=e.findIndex(s=>r(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 nT(e,t){if(t.cursor!==void 0&&Pi(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw st("Query cursor does not match the requested snapshot.");let n=Vg(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:Di(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var rT=Object.freeze({version:Ni,max_length:dd});(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]="64c4e6e1-d7c4-50e0-a444-fb2fa3c65443")}catch{}})();var Wg=8,Hg=64;function ld(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Kg(e){let t=e.row_contract;return ld(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function Mi(e,t){return typeof e=="string"?e.length<=240?e:(t.compacted=!0,`${e.slice(0,240)}\u2026`):Array.isArray(e)?e.map(n=>Mi(n,t)):ld(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Mi(r,t)])):e}function cn(e,t){let n=t.estimated_tokens;for(let r=0;r<Wg;r+=1){t.estimated_tokens=n;let o=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(o===n)return;n=o}t.estimated_tokens=n}function Gg(e,t,n){let r=Kg(e);for(let o=0;o<Hg;o+=1){if(cn(e,t),t.estimated_tokens<=n)return;let i=r.map(s=>({key:s,rows:Array.isArray(e[s])?e[s]:[]})).filter(({rows:s})=>s.length>1).sort((s,a)=>a.rows.length-s.rows.length||s.key.localeCompare(a.key))[0];if(!i)return;i.rows.splice(-Math.max(1,Math.ceil(i.rows.length/2))),t.rows_compacted=!0,e.has_more=!0,e.truncated=!0,typeof e.count=="number"&&(e.count=r.reduce((s,a)=>s+(Array.isArray(e[a])?e[a].length:0),0))}}function ud(e,t,n){let r={compacted:!1},o=Mi(e,r);return t.strings_compacted=r.compacted,o.read_output=t,Gg(o,t,n),cn(o,t),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]="27431a6b-6f2e-5020-b4f1-b94cfa8a1c26")}catch{}})();var St=["include","amount","cost","encoding"],yd=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate"],gd=["canonical","legacy","intent","default"],$i={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},dT=Object.freeze(St.map(e=>$i[e])),Xg={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","--verbose"]},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","--verbose"]},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:{}},Yg=new Set(["--fields","--section"]),Jg=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.","--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.","--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."});function hd(e){return e.slice(2).replaceAll("-","_")}function Qg(e,t){let n=Jg[e];if(n!==void 0)return n;let r=t==="include"?Yg.has(e)?"<csv>":hd(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${$i[t]} ${r}.`}function Zg(e){let t=Xg[e],n=Object.freeze(Object.fromEntries(St.map(r=>[r,Object.freeze({dimension:r,canonical_option:$i[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,migration_hint:Qg(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:gd})}var eh=Object.freeze(yd.map(Zg)),th=new Map(eh.map(e=>[e.command,e]));function bd(e){let t=e.trim().toLowerCase().split(/\s+/u)[0],n=t.startsWith("list-")?"list":t==="ctx"?"context":t;return yd.includes(n)?n:void 0}var nh=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format"],rh={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"]};function oh(e){return nh.some(t=>e[t]!==void 0)}var ih=[{keys:["outputInclude","output_include"],valid:e=>Li(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||xt(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>xt(e)!==void 0,message:"--output-budget must be a positive integer."},{keys:["outputFormat","output_format"],valid:e=>e==="toon"||e==="json",message:"--output-format must be toon or json."}];function lT(e,t){if(!oh(t))return;let n=bd(e);if(!n)throw new w(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,b.USAGE);if((rh[n]??[]).some(r=>t[r]!==void 0&&t[r]!==!1))throw new w(`Universal output controls cannot be combined with a ${n} mutation.`,b.USAGE);for(let r of ih){let o=r.keys.map(i=>t[i]).find(i=>i!==void 0);if(o!==void 0&&!r.valid(o))throw new w(r.message,b.USAGE)}}function sh(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function ah(e,t){let n=sh(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function ch(e){return e!==void 0&&e!==!1&&e!==null}function Li(e){let n=(Array.isArray(e)?e:[e]).flatMap(r=>typeof r=="string"?r.split(","):[]).map(r=>r.trim()).filter(Boolean);return n.length>0?[...new Set(n)]:void 0}function xt(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 dh(e,t,n){for(let r of e.legacy_aliases){let o=ah(t,r.flag),i={value:o,flag:r.flag};if(ch(o)&&n(i))return i}}function fd(e,t){let n=Li(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Li(t.value)??[hd(t.flag)]}}function md(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=xt(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=xt(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function pd(e,t){let n=xt(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=xt(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function _d(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 wd(e,t){let n=bd(e);if(!n)return;let r=th.get(n),o={include:c=>fd(void 0,c),amount:c=>md(void 0,c),cost:c=>pd(void 0,c),encoding:c=>_d(void 0,c)},i=Object.fromEntries(St.map(c=>[c,dh(r.dimensions[c],t,d=>o[c](d)!==void 0)])),s=St.flatMap(c=>{let d=i[c];return d?[d.flag]:[]}),a=St.flatMap(c=>{let d=i[c];return d?[r.dimensions[c].legacy_aliases.find(f=>f.flag===d.flag).migration_hint]:[]});return{command:n,include:fd(t.outputInclude??t.output_include,i.include),amount:md(t.outputLimit??t.output_limit,i.amount),cost:pd(t.outputBudget??t.output_budget,i.cost),encoding:_d(t.outputFormat??t.output_format,i.encoding),legacy_aliases_used:s,migration_hints:a,precedence:gd}}function xr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var lh=new Set(["applied_bound","applied_limit","completeness","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","row_contract","sorting","total","truncated"]);function Ed(e){let t=e.row_contract;return xr(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function uh(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function fh(e,t){let n=Ed(e),r=t.some(o=>Object.hasOwn(e,o.split(".")[0]));return n.length>0&&!r?Object.fromEntries(Object.entries(e).map(([o,i])=>[o,n.includes(o)&&Array.isArray(i)?i.map(s=>xr(s)?uh(s,t):s):i])):Object.fromEntries(Object.entries(e).filter(([o])=>t.some(i=>i.split(".")[0]===o)||lh.has(o)))}function mh(e,t){if(t==="unbounded")return e;let n=!1,r=Ed(e),o=new Set(r),i=Object.fromEntries(Object.entries(e).map(([s,a])=>!o.has(s)||!Array.isArray(a)||a.length<=t?[s,a]:(n=!0,[s,a.slice(0,t)])));return n&&(i.has_more=!0,i.truncated=!0,typeof i.count=="number"&&(i.count=r.reduce((s,a)=>s+(Array.isArray(i[a])?i[a].length:0),0)),i.applied_bound={kind:"output_limit",source:"explicit",value:t}),i}function ph(e){return St.filter(t=>e[t]!==void 0)}function kd(e,t,n){let r=wd(e,t);if(!r)return n;let o=ph(r);if(o.filter(d=>r[d]?.source==="canonical").length===0)return n;let s={...n};r.include?.source==="canonical"&&(s=fh(s,r.include.value)),r.amount?.source==="canonical"&&(s=mh(s,r.amount.value));let a={contract_version:1,command:r.command,requested_dimensions:o,precedence:r.precedence,legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};s.read_output=a,cn(s,a);let c=r.cost?.source==="canonical"?r.cost.value:void 0;if(c!==void 0&&a.estimated_tokens>c&&(s=ud(s,a,c)),c!==void 0&&a.estimated_tokens>c){let d={contract_version:1,command:r.command,requested_dimensions:o,precedence:r.precedence,legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0},l={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Increase --output-budget or narrow the read."},read_output:d};return cn(l,d),l}return s}function uT(e){return xr(e)&&xr(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function vd(e,t){let n=wd(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}import{AsyncLocalStorage as _h}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]="e48a306e-debb-5e66-ae9b-68bf17fa405f")}catch{}})();var xd=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:2400,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"}]),Id=new _h;function yh(){return Id.getStore()??xd}function bT(e,t){return Id.run(hh(e.workspaceContracts,e.packageContracts),t)}function gh(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))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:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function hh(e=[],t=[]){let n=[{source:"core",contracts:xd,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=gh(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&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function Td(e,t,n=yh()){let r=e.trim().toLowerCase(),o=t.trim().toLowerCase(),i=n.find(d=>d.command===r&&d.intent===o);if(i)return{...i,source:i.source??"core"};let s=n.filter(d=>d.command===r).map(d=>d.intent);if(s.length===0)return;let a=s.map(d=>{let l=Array.from({length:o.length+1},(f,p)=>p);for(let f=1;f<=d.length;f+=1){let p=l[0];l[0]=f;for(let m=1;m<=o.length;m+=1){let h=l[m];l[m]=Math.min(l[m]+1,l[m-1]+1,p+(d[f-1]===o[m-1]?0:1)),p=h}}return{candidate:d,distance:l[o.length]}}).sort((d,l)=>d.distance-l.distance||d.candidate.localeCompare(l.candidate))[0].candidate,c=`pm ${r} --for ${a}`;throw new w(`Unknown context intent "${o}" for ${r}. Did you mean "${a}"?`,b.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",required:`Use a declared ${r} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[c],recovery:{recovery_mode:"compact",attempted_command:`pm ${r} --for ${o}`,suggested_retry:c}})}var Ad={context:(e,t,n)=>{e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard"),e.section===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]);let r=Tr(e.tokenBudget,t.token_budget),o=Math.max(1,Math.floor((r-800)/500)),i=String(n?o:Math.min(20,o));e.limit===void 0&&(e.limit=i),e.activityLimit===void 0&&(e.activityLimit=i)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{if(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"),e.limit===void 0){let r=Tr(e.tokenBudget,t.token_budget),o=Math.max(2,Math.floor((r-520)/16));e.limit=String(n?o:Math.min(100,o))}},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{if(e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0),e.limit===void 0){let r=Tr(e.tokenBudget,t.token_budget),o=Math.max(2,Math.floor((r-480)/16));e.limit=String(n?o:Math.min(100,o))}}};function wT(e,t){let n=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(n!==void 0&&(e==="get"||e==="list"||e==="search"))throw new w("--token-budget requires a declared context intent selected with --for",b.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 s={...t,tokenBudget:n};return delete s.token_budget,s}let r=Td(e,t.for),o=ji(n)!==void 0,i={...t};return i.tokenBudget===void 0&&n!==void 0&&(i.tokenBudget=n),delete i.token_budget,i.tokenBudget===void 0&&(i.tokenBudget=String(r.token_budget)),Ad[e](i,r,o),i}var bh={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Ir=256;function Fi(e){return Array.isArray(e)?e.map(Fi):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Fi(n)])):typeof e=="string"&&e.length>240?`${e.slice(0,240)}\u2026`:e}function ji(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 Tr(e,t){let n=ji(e);if(n===void 0)return t;if(n<Ir)throw new w(`Context intent token budget must be at least ${Ir}`,b.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${Ir}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Ir} or omit the override.`]});return n}function Fe(e,t){let n=t.estimated_tokens;for(;;){t.estimated_tokens=n;let r=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(r===n)return;n=r}}var Sd={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","blocked","held_by_others"],search:["items"]};function Cd(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 wh(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 Eh(e,t,n){let r=!1;for(;;){if(Fe(e,t),t.estimated_tokens<=t.token_budget||n.length<=1)return r;let o=Buffer.byteLength(JSON.stringify(n),"utf8"),i=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(i/Math.max(1,Math.ceil(o/n.length)))))),r=!0}}function kh(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=Cd(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=Eh(e,t,r)||d,!d)return!1;let l=wh(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),Fe(e,t),!1;if(e.next_cursor=Di(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),Fe(e,t),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function vh(e,t,n,r){if(e==="list"||e==="search")return kh(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Fe(t,n),n.estimated_tokens<=n.token_budget)return o;let i=Sd[e].map(p=>({key:p,rows:Array.isArray(t[p])?t[p]:[]})).filter(({rows:p})=>p.length>0).sort((p,m)=>m.rows.length-p.rows.length||p.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=Sd[e].reduce((p,m)=>p+(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=(n.estimated_tokens-n.token_budget)*4,f=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-f,f),o=!0}}function Sh(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in Ad))return n;let o=r,i=Td(o,t.for),s={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:Tr(t.tokenBudget??t.token_budget,i.token_budget),estimated_tokens:0,within_budget:!0,degradation:bh[o],declaration_feasible:!0,result_omitted:!1},a={...n};if(o==="list"||o==="search"){let d=o==="list"?520:480,l=Math.max(2,Math.floor((s.token_budget-d)/16)),p=ji(t.tokenBudget??t.token_budget)!==void 0?l:Math.min(100,l),m=t.limit!==void 0;s.budget_derived_limit=p,s.binding_constraint=m?"explicit_limit":"token_budget",s.limit_reason=m?"The caller supplied an explicit row limit; the budget-derived limit remains diagnostic.":"The selected intent token budget determines the row ceiling.",a.budget_derived_limit=p}let c={...a,context_intent:s};return Fe(c,s),s.estimated_tokens>s.token_budget&&(s.degradation="recursive_budget_compaction",c={...Fi(a),context_intent:s},Fe(c,s)),s.estimated_tokens>s.token_budget&&vh(o,c,s,t)&&(s.degradation="budget_row_compaction",Fe(c,s)),s.estimated_tokens>s.token_budget&&(s.degradation="budget_receipt_only",s.declaration_feasible=!1,s.result_omitted=!0,s.within_budget=!1,c={budget_exceeded:{omitted_result:!0,reason:"declared_budget_infeasible",restore_with:"Increase --token-budget or narrow the request; the unprojected command may be larger."},context_intent:s},Fe(c,s)),c}function xh(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=Cd(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"])delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function Od(e,t,n){let r=ad(e,n);return typeof r=="object"&&r!==null&&!Array.isArray(r)?kd(e??"",t,xh(t,Sh(e??"",t,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]="15daa637-4d30-5794-bdb5-87585d443cd3")}catch{}})();var Ih=[..._e],Th=[...Mt],Ah=[...xn],vT=[...In],ST=[...Tn],Ch=[...An],Ar=["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-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","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],xT=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],Oh=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Rd={help:"Commander help rendering has no SDK operation result.",item:"The item namespace only groups lifecycle subcommands already exposed as actions.",packages:"The plural package alias only renders package-oriented help."},Nd=Object.freeze(Ar.flatMap(e=>e in Rd?[]:e==="extension"||e==="package"?[...Oh.map(t=>`${e}-${t}`),e]:[e]));function IT(e=Ar,t=Nd,n=Rd){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i))}}function TT(e){return Nd.includes(e)}function AT(e){return Ih.includes(e)}function CT(e){return Th.includes(e)}function OT(e){return Ah.includes(e)}function RT(e){return Ch.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]="23b3a820-f205-506b-9507-dbd60087f62e")}catch{}})();var Rh=["full","compact","brief","summary","counts"],PT=["mutation","read","discovery","governance"],Nh=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"]),Dh=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Ph=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Mh={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Lh=3,$h=2;function Fh(e){let[t=""]=e.trim().split(/\s+/u);return Nh.has(t)?"mutation":Dh.has(t)?"discovery":Ph.has(t)?"governance":"read"}function Dd(e,t=Fh(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=Mh[t];return jh({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*Lh/$h)},degradation_ladder:Rh,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function jh(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,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var zh=Ar.map(e=>Dd(e)),Uh=new Map(zh.map(e=>[e.command,e]));function MT(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=n.split(" "),o=Uh.get(r);return o?{...o,command:n}:t.generateFallback?Dd(n):null}function Cr(e){return Math.ceil(Math.max(0,e)/4)}(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]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();var It=["result_rows","envelope","diagnostics","hints"],qh=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,Bh=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,Vh=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,Wh=8;function zi(e){return Buffer.byteLength(e,"utf8")}function Pd(e){return zi(JSON.stringify(e)??"null")}function Hh(e,t){return Bh.test(e)?"diagnostics":Vh.test(e)?"hints":qh.test(e)||Array.isArray(t)?"result_rows":"envelope"}function Kh(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"]=Pd(e),t;for(let[n,r]of Object.entries(e))t[Hh(n,r)]+=Pd({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function Gh(e,t){let n=It.reduce((s,a)=>s+t[a],0),r=It.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-It.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||It.indexOf(a.section)-It.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function Md(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function Ld(e,t){let n=zi(t(e)),r=Gh(n,Kh(e)),o=Object.fromEntries(It.map(a=>[a,{bytes:r[a],estimated_tokens:Cr(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:Cr(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=Md(e,i);for(let a=0;a<Wh;a+=1){let c=zi(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Cr(c)},s=Md(e,i)}return 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]="816ae182-02ba-56a9-8204-7474e30322bc")}catch{}})();var qi="__pm_native_output",$d=!1;function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xh(e){return re(e)&&e[qi]===!0}function Yh(e){if(!re(e)||e[qi]!==!0)return e;let{[qi]:t,...n}=e;return n}function Bi(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Jh(){(process.exitCode===void 0||process.exitCode===b.SUCCESS)&&(process.exitCode=b.SUCCESS)}function Qh(){(process.exitCode===void 0||process.exitCode===b.SUCCESS)&&(process.exitCode=b.GENERIC_FAILURE)}function Vi(e){if(e==="stdout"){Jh();return}Qh()}function Fd(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function Zh(){$d||($d=!0,process.stdout.on("error",e=>{if(Bi(e)){Vi("stdout");return}Fd(e)}),process.stderr.on("error",e=>{if(Bi(e)){Vi("stderr");return}Fd(e)}))}function zd(e,t){Zh();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Bi(n))return Vi(e),!1;throw n}}function eb(e){return zd("stdout",e)}function dn(e){return zd("stderr",e)}function Ui(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Or(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>Or(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(re(e)){let t={};for(let[n,r]of Object.entries(e)){if(n==="omitted_field_groups"&&Array.isArray(r)&&r.length===0){t[n]=[];continue}let o=Or(r);o!==void 0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}return e}}function Wi(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":e.map(r=>{if(!re(r)&&!Array.isArray(r))return`${n}- ${Ui(r)}`;let i=Wi(r,t+1).split(`
|
|
13
13
|
`),[s,...a]=i;return a.length===0?`${n}- ${s.trimStart()}`:`${n}- ${s.trimStart()}
|
|
14
14
|
${a.join(`
|
|
15
15
|
`)}`}).join(`
|
|
16
|
-
`);if(re(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>!re(i)&&!Array.isArray(i)?`${n}${o}: ${
|
|
17
|
-
${
|
|
18
|
-
`)}return`${n}${
|
|
16
|
+
`);if(re(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>!re(i)&&!Array.isArray(i)?`${n}${o}: ${Ui(i)}`:Array.isArray(i)&&i.length===0?`${n}${o}: []`:re(i)&&Object.keys(i).length===0?`${n}${o}: {}`:`${n}${o}:
|
|
17
|
+
${Wi(i,t+1)}`).join(`
|
|
18
|
+
`)}return`${n}${Ui(e)}`}function tb(e){if(!re(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})`,""],n=re(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
|
|
19
19
|
`)}
|
|
20
20
|
`;for(let r of e.events){if(!re(r))continue;let o=typeof r.kind=="string"?r.kind:"event",i=typeof r.item_title=="string"?r.item_title:"",s=typeof r.item_id=="string"?r.item_id:"",a=typeof r.reminder_text=="string"&&r.reminder_text.length>0?` ${r.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${a}`.trim())}return`${t.join(`
|
|
21
21
|
`)}
|
|
22
|
-
`}function
|
|
23
|
-
`;let n=
|
|
24
|
-
`:`${
|
|
25
|
-
`}function
|
|
22
|
+
`}function nb(e){return e.json===!0||e.json===void 0&&e.defaultOutputFormat==="json"?"json":"toon"}var rb=new Set(["filters","now","projection","sorting"]);function ob(e){let t=Or(e);if(!re(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!rb.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function ib(e,t){if(!re(e)||!Array.isArray(e.run_results)||!e.run_results.every(re))return e;let n=e.run_results,r=n.map(s=>s.execution_context).filter(s=>s!==void 0),o=r.length===n.length&&r.length>0&&r.every(s=>JSON.stringify(s)===JSON.stringify(r[0]))?r[0]:void 0,i=n.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 jd(e,t){if(t==="json")return`${JSON.stringify(e,null,2)}
|
|
23
|
+
`;let n=Or(e);return n===void 0?`{}
|
|
24
|
+
`:`${Wi(n,0)}
|
|
25
|
+
`}function sb(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:di("output_format",{command:n.command,args:n.commandArgs,command_options:n.commandOptions,global:{...n},pm_root:n.pmRoot,format:r,options:{...n},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&dn(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
|
|
26
26
|
`),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
|
|
27
27
|
`)?o.result:`${o.result}
|
|
28
|
-
`}:{result:o.handled?o.result:e,rendered:null}}function
|
|
28
|
+
`}:{result:o.handled?o.result:e,rendered:null}}function ab(e,t,n){let r=oc(),o=n.command??r?.command,i={...r?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat]].filter(h=>h[1]!==void 0))},s=vd(o??"",i)??nb(n),a={...n,command:o,commandOptions:i},c=sb(e,t,a,s);if(c.rendered!==null)return c.rendered;let d=c.result,l=o==="test"?ib(d,n.lean===!0):d,f=Od(o,i,l),p=h=>{if(s==="toon"){let y=tb(h);if(y!==null)return y}let _=t?{rendered:null}:ac(s,h);return _.rendered!==null?_.rendered.endsWith(`
|
|
29
29
|
`)?_.rendered:`${_.rendered}
|
|
30
|
-
`:s==="json"
|
|
30
|
+
`:s==="json"?jd(n.lean===!0?ob(h):h,"json"):jd(h,"toon")},m=n.tokenAccounting===!0?Ld(f,p):f;return p(m)}function cb(e,t){let n=sc(e),r=nd(n.result)?n.result:null,o=Xh(n.result),i=r?r.result:Yh(n.result);return ic(i),r?"":ab(i,o,t)}function HT(e,t){let n=t.idOnly?Sr(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?Sr(e,{changedFields:"compact"}):Sr(e,{compactEnvelope:!0}),r=cb(n,t);t.quiet||eb(r)}function KT(e){let t=di("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;dn(n.endsWith(`
|
|
31
31
|
`)?n:`${n}
|
|
32
|
-
`)}import
|
|
32
|
+
`)}import Gd from"fast-json-patch";import je from"node:fs/promises";import Te from"node:path";import{randomUUID as db}from"node:crypto";import{createRequire as lb}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]="f1205949-16d8-51ce-98e8-04abc4c78ee8")}catch{}})();var ub="history-event-index.sqlite",Hi="2";function Dr(e){return Te.join(e,"runtime",ub)}function fb(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function mb(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?fb(t):null}var Rr;function Ki(){return Rr!==void 0||(Rr=mb(process.versions.node,lb(import.meta.url))),Rr}function pb(e){e.exec(`
|
|
33
33
|
PRAGMA journal_mode = OFF;
|
|
34
34
|
PRAGMA synchronous = OFF;
|
|
35
35
|
CREATE TABLE metadata (
|
|
@@ -57,21 +57,21 @@ ${Vi(i,t+1)}`).join(`
|
|
|
57
57
|
ON events(agent_harness, ts, stream_id, stream_offset);
|
|
58
58
|
CREATE INDEX events_instance_order
|
|
59
59
|
ON events(agent_instance, ts, stream_id, stream_offset);
|
|
60
|
-
`),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(
|
|
60
|
+
`),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Hi)}function Ud(e,t){e.prepare(`INSERT INTO events(
|
|
61
61
|
stream_id, stream_offset, ts, author, agent_harness,
|
|
62
62
|
agent_instance, op, entry_json
|
|
63
|
-
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,t.entry.ts,t.entry.author,t.entry.agent_harness??null,t.entry.agent_instance??null,t.entry.op,JSON.stringify(t.entry))}async function
|
|
63
|
+
) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,t.entry.ts,t.entry.author,t.entry.agent_harness??null,t.entry.agent_instance??null,t.entry.op,JSON.stringify(t.entry))}async function eA(e){let t=Ki();if(!t)return!1;let n=Te.join(e,"history"),o=(await je.readdir(n,{withFileTypes:!0}).catch(c=>{if(typeof c=="object"&&c!==null&&"code"in c&&c.code==="ENOENT")return[];throw c})).filter(c=>c.isFile()&&c.name.endsWith(".jsonl")).sort((c,d)=>c.name.localeCompare(d.name)),i=Dr(e);await je.mkdir(Te.dirname(i),{recursive:!0});let s=`${i}.${db()}.tmp`,a;try{a=new t(s),pb(a),a.exec("BEGIN IMMEDIATE");for(let c of o){let d=c.name.slice(0,-6),l=await an(Te.join(n,c.name),d);for(let[f,p]of l.entries())Ud(a,{stream_id:d,stream_offset:f,entry:p})}return a.exec("COMMIT"),a.close(),a=void 0,await je.rm(i,{force:!0}),await je.rename(s,i),!0}catch(c){throw a?.close(),await je.rm(s,{force:!0}),c}}async function qd(e,t){let n=Te.dirname(Te.dirname(e)),r=Dr(n);try{await je.access(r)}catch{return}let o=Ki();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hi)throw new TypeError("Unsupported history event index version");let a=Te.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);Ud(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await je.rm(r,{force:!0})}}async function Pr(e){await je.rm(Dr(Te.dirname(Te.dirname(e))),{force:!0})}function Nr(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function _b(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function tA(e,t){let n=Ki();if(!n)return null;let r=[],o=[];t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0?(r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))"),o.push(t.after_ts,t.after_ts,t.after_stream_id,t.after_ts,t.after_stream_id,t.after_stream_offset)):t.since_ts!==void 0&&(r.push("ts >= ?"),o.push(t.since_ts)),Nr(r,o,"op",t.ops),Nr(r,o,"author",t.authors),_b(r,o,t.harnesses,t.harness_alias_authors),Nr(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);Nr(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s;try{if(s=new n(Dr(e),{readOnly:!0}),s.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Hi)return s.close(),null;let c=s.prepare(`SELECT stream_id, stream_offset, entry_json
|
|
64
64
|
FROM events${i}
|
|
65
65
|
ORDER BY ts, stream_id, stream_offset
|
|
66
|
-
LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.length>t.limit,l=c.slice(0,t.limit).map(f=>({stream_id:String(f.stream_id),stream_offset:Number(f.stream_offset),entry:JSON.parse(String(f.entry_json))}));return s.close(),{events:l,has_more:d}}catch{return s?.close(),null}}import
|
|
67
|
-
`);return}try{await
|
|
68
|
-
`)}}async function
|
|
66
|
+
LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.length>t.limit,l=c.slice(0,t.limit).map(f=>({stream_id:String(f.stream_id),stream_offset:Number(f.stream_offset),entry:JSON.parse(String(f.entry_json))}));return s.close(),{events:l,has_more:d}}catch{return s?.close(),null}}import Gi from"node:fs/promises";import Tt 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]="4db09d54-90c6-548b-baa8-c7ce419f70a2")}catch{}})();var yb=Tt.join("runtime","history-drift-cache.json"),Bd={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 Vd(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function gb(e){let t=Tt.join(e,yb),n=!1,r="invalid_cache_path";try{n=(await Gi.stat(await Gi.realpath(e))).isDirectory()}catch(o){let i=Vd(o);r=i===void 0?"unknown":Bd[i]??"filesystem_error"}if(!n){dn(`[pm] warning: history_drift_cache_invalidation_failed:${r}
|
|
67
|
+
`);return}try{await Gi.rm(t,{force:!0})}catch(o){let i=Vd(o);if(i==="ENOENT")return;let s=i===void 0?"unknown":Bd[i]??"filesystem_error";dn(`[pm] warning: history_drift_cache_invalidation_failed:${s}
|
|
68
|
+
`)}}async function ln(e){let t=Tt.dirname(Tt.resolve(e));Tt.basename(t)==="history"&&await gb(Tt.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]="5228a53a-603c-5c9f-870b-8ea8e0c5d27a")}catch{}})();var hb={front_matter:{},body:""};function bb(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function wb(e,t){let n=bb(t);if(n.length===0)return!0;let r=e;for(let o of n){if(Array.isArray(r)){if(o==="-"||!/^(0|[1-9]\d*)$/.test(o))return!1;let s=Number(o);if(!Number.isInteger(s)||s<0||s>=r.length)return!1;let a=r[s];if(a===void 0)return!1;r=a;continue}if(typeof r!="object"||r===null||!Object.prototype.hasOwnProperty.call(r,o))return!1;let i=r[o];if(i===void 0)return!1;r=i}return!0}function Eb(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!wb(r,o.path)?{...o,op:"add"}:o;n.push(i),r=Gd.applyPatch(r,[i],!0,!0).newDocument}return n}function Xi(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let n=me(e);return{front_matter:x(n.metadata,ye),body:n.body}}function Wd(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=me(e);return{metadata:x(n.metadata,ye),body:n.body}}function Xd(e){return Xe(ae(Xi(e)))}function hA(){return Xe(ae(hb))}function At(e){let t=Xi(e.before),n=Xi(e.after),r=Wd(e.before),o=Wd(e.after),i=Gd.compare(r,o),s=Eb(r,i),a=Zc(e.author);return{ts:e.nowIso,author:e.author,author_source:e.authorSource??Qc(e.author),...a.harness?{agent_harness:a.harness}:{},...a.model?{agent_model:a.model}:{},...a.model_source?{agent_model_source:a.model_source}:{},...a.instance?{agent_instance:a.instance}:{},...a.provenance?{agent_provenance:a.provenance}:{},...a.episode?{agent_episode:a.episode}:{},op:e.op,patch:s,before_hash:Xe(ae(t)),after_hash:Xe(ae(n)),message:e.message===void 0?void 0:e.message,...e.context===void 0?{}:{context:e.context}}}function Hd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kb(e){let t=e.ts.trim();return t.length>0?t:Ke()}function Kd(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function Mr(e,t){let n=kb(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(Hd(r))return JSON.stringify(Kd(r,n))}catch{}return e}return Hd(e)?JSON.stringify(Kd(e,n)):JSON.stringify(e)}async function Ct(e,t){let n=await Ie("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Pt(e,Mr(n.result,t)),await ln(e),await Pr(e);return}if(typeof n.result=="object"&&n.result!==null){let r=n.result;if(r.skip===!0)return;let o=typeof r.history_path=="string"?r.history_path:e;if(typeof r.line=="string"){await Pt(o,Mr(r.line,t)),await ln(o),await Pr(o);return}await Pt(o,Mr(r.entry??t,t)),await ln(o),await Pr(o);return}}await Pt(e,Mr(t,t)),await ln(e),await qd(e,t)}import Yi 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]="c8668470-7e57-5dee-8e41-298e7c697b77")}catch{}})();var vb={metadata:{},body:""};function $r(){return structuredClone(vb)}function Lr(e){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Xd(Fr(e))}catch{}return Xe(ae({replay_fallback:!0,metadata:e.metadata,body:e.body}))}function Fr(e){return{metadata:e.metadata,body:e.body}}function IA(e,t={}){return me(Fr(e),t)}function TA(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=me(e);return{metadata:x(t.metadata,ye),body:t.body}}function Yd(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function Sb(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Qd(e){return Array.isArray(e)?e.filter(Sb).map(t=>({...t,path:Yd(t.path),from:typeof t.from=="string"?Yd(t.from):void 0})):[]}function xb(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 jr(e,t){try{let n=Qd(t),r=Yi.applyPatch(structuredClone(e),n,!0,!1).newDocument;return xb(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function Ji(e){let t=$r();for(let n=0;n<e.length;n+=1){let r=e[n];if(Lr(t)!==r.before_hash)return{ok:!1,errors:[`verify_failed:before_hash_mismatch:entry_${n+1}`]};let o=jr(t,r.patch);if(!o.ok)return{ok:!1,errors:[`verify_failed:patch_apply_failed:entry_${n+1}`]};if(t=o.document,Lr(t)!==r.after_hash)return{ok:!1,errors:[`verify_failed:after_hash_mismatch:entry_${n+1}`]}}return{ok:!0,errors:[]}}function Jd(e,t){try{return{ok:!0,document:Yi.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function Ib(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Qd(t)){let c=Jd(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let d=Jd(n,{...a,op:"add"});if(d.ok){n=d.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function AA(e){let t=$r(),n=[],r=[],o=0,i=0,s=0,a=0;for(let c=0;c<e.length;c+=1){let d=e[c],l=Lr(t),f=jr(t,d.patch),p,m,h=!1,_=0,y=0;if(f.ok)p=f.document,m=d.patch;else{let J=Ib(t,d.patch);p=J.document,m=Yi.compare(t,p),h=!0,_=J.convertedReplaceToAdd,y=J.skippedOps,s+=_,a+=y,i+=1}let T=Lr(p),L=l!==d.before_hash||T!==d.after_hash;L&&(o+=1),n.push({...d,patch:m,before_hash:l,after_hash:T}),r.push({index:c+1,rehashed:L,patch_repaired:h,converted_replace_to_add:_,skipped_ops:y}),t=p}return{entries:n,finalDocument:t,entriesRehashed:o,entriesPatchRepaired:i,convertedReplaceToAdd:s,skippedOps:a,details:r}}function CA(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
|
|
69
69
|
`)}
|
|
70
|
-
`}import
|
|
71
|
-
`,"utf8")}finally{await o.close()}await
|
|
72
|
-
`,"utf8")}catch{return await Zi(e),null}return t}async function Hb(e){let t;try{let r=await Ae.stat(e);if(t=Date.now()-r.mtimeMs,t<=Fb)return!1}catch(r){return ln(r,"ENOENT")}let n=await sl(e);return n!==null&&Wb(n.pid)&&t<=jb?!1:Zi(e)}async function Kb(e,t){let n=`${e}${$b}`,r=await Zd(n);if(r!==null)return async()=>Qd(n,r.token);if(!await Hb(n))return null;let o=await Zd(n);return o===null?null:async()=>Qd(n,o.token)}async function Gb(e){let t=await Kb(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await el(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!rl(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Bb(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=Lb)throw il(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await nl(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function je(e,t,n,r,o=!1,i=!0,s){let a=await Ie("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let m=qb(a.result);if(m)return async()=>{await Promise.resolve(m()),await Ie("lock_release",{pm_root:e,id:t,owner:r})}}let c=Js(e,t),d=zb(s),l=Date.now(),f=0,p=Db;for(;;)try{return await Rb(c,t,r,n),async()=>{await nl(c,"lock:release"),await Ie("lock_release",{pm_root:e,id:t,owner:r})}}catch(m){if(!ln(m,"EEXIST"))throw new w(`Failed to acquire lock for ${t}: ${Is(m)}`,b.GENERIC_FAILURE);let h=await el(c);if(rl(h.info,n)){let y=await Gb({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:f,waitBudgetMs:d,startedAtMs:l,fallbackLockInfo:h});if(h=y.lockInfo,y.staleRemovalCounted&&(f+=1),y.shouldRetryCreate)continue}let _=Date.now()-l;if(d===0||_>=d)throw il(t,h.info,d===0?0:_);await Ub(Math.min(p,d-_)),p=Math.min(p*2,Pb)}}import Xb from"node:fs/promises";import al 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]="8a15177d-4090-5e58-aac7-20b2ed7684a2")}catch{}})();var jr="_workspace";function cl(e){return al.join(e,"history",`${jr}.jsonl`)}function Yb(e,t){return{metadata:{id:jr,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 dl(e){let t=Lr();for(let n of e)t=Fr(t,n.patch).document;return $r(t)}async function ll(e){let t=cl(e.pmRoot),n=await sn(t,jr),r=Yi(n);if(!r.ok)throw new TypeError(`Workspace history verification failed: ${r.errors.join(", ")}`);let o=e.idempotencyKey===void 0?void 0:n.find(f=>f.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=new Date().toISOString(),s=n.length===0?Lt:dl(n),a="documents"in s.metadata&&typeof s.metadata.documents=="object"&&s.metadata.documents!==null&&!Array.isArray(s.metadata.documents)?s.metadata.documents:{},c=a[e.documentPath];if(c!==void 0&&ae(c)!==ae(e.before))throw new w(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,b.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=Yb({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=At({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 Ct(t,l),{entry:l,historyPath:t}}async function eC(e){let t=await je(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await ll(e)}finally{await t()}}async function tC(e){let t=await je(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=cl(e.pmRoot),r=await sn(n,jr),o=Yi(r);if(!o.ok)throw new TypeError(`Workspace history verification failed: ${o.errors.join(", ")}`);let i=r.length===0?Lt:dl(r),s=At({nowIso:new Date().toISOString(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Ct(n,s),{entry:s,historyPath:n}}finally{await t()}}async function ul(e){let t=await je(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await Ce(e.filePath);if(n===e.raw)return!1;let r=n===null?null:JSON.parse(n),o=JSON.parse(e.raw);await Q(e.filePath,e.raw);try{(n!==null||e.recordCreation!==!1)&&await ll({pmRoot:e.pmRoot,documentPath:al.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:r,after:o,op:e.op,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(i){throw n===null?await Xb.rm(e.filePath,{force:!0}):await Q(e.filePath,n),i}return!0}finally{await t()}}import Jb from"node:crypto";import fl 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]="50a277b9-d530-5aa0-8bd0-8eb0d36911e5")}catch{}})();function pl(e){let t=(e??"").trim().toLowerCase();return t?t.endsWith("-")?t:`${t}-`:"pm-"}function es(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function ts(e,t){let n=pl(t),r=es(e);return r.startsWith(n)?r:`${n}${r}`}function Qb(e){let t=Os(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=Jb.randomInt(0,36).toString(36);return n}async function Zb(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[fl.join(e,o,`${t}.md`),fl.join(e,o,`${t}.toon`)]);return(await Promise.all(r.map(o=>ke(o)))).some(Boolean)}var ml=4,_l=12;function ew(e){return typeof e!="number"||!Number.isFinite(e)?ml:Math.min(_l,Math.max(ml,Math.trunc(e)))}async function cC(e,t,n={}){let r=ew(n.tokenLength),o=Math.min(r+6,_l),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${pl(t)}${Qb(r)}`;if(n.probeExisting===!1||!await Zb(e,a,n.typeToFolder??se))return a;i+=1}r+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}(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]="027f6acb-15cc-5707-85ed-b5298b6b6abe")}catch{}})();var B={ok:!1},g=e=>typeof e=="string"?{ok:!0,value:e}:B,O=e=>typeof e=="boolean"?{ok:!0,value:e}:B;function M(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?B:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:B}function E(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return B;let r=[];for(let o of n){let i=e(o);if(!i.ok)return B;r.push(i.value)}return{ok:!0,value:r}}}function rs(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:B}function u(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function zr(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return B;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return B;n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return B;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return B;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var tw=I({key:g,values:E(g),required:u(O),aliases:u(E(g)),description:u(g)}),nw=I({command:N("create","update"),option:g,required:u(O),visible:u(O),enabled:u(O)}),rw=I({name:g,description:u(g),default_status:u(g),folder:u(g),aliases:u(E(g)),required_create_fields:u(E(g)),required_create_repeatables:u(E(g)),options:u(E(tw)),command_option_policies:u(E(nw))}),ow=I({id:g,aliases:u(E(g)),roles:u(E(N(...Mn))),description:u(g),order:u(M())}),iw=I({key:g,metadata_key:u(g),front_matter_key:u(g),cli_flag:u(g),cli_aliases:u(E(g)),description:u(g),type:u(N(...mt)),commands:u(E(N(...Ln))),repeatable:u(O),required:u(O),required_on_create:u(O),required_types:u(E(g)),allow_unset:u(O)}),sw=e=>{if(!Array.isArray(e)||e.length!==2)return B;let[t,n]=e;return typeof t!="string"||typeof n!="string"?B:{ok:!0,value:[t,n]}},aw=I({type:g,allowed_transitions:E(sw)}),cw=u(I({version:u(M({int:!0})),files:u(I({types:u(g),statuses:u(g),fields:u(g),workflows:u(g)})),statuses:u(E(ow)),fields:u(E(iw)),workflow:u(I({draft_status:u(g),open_status:u(g),in_progress_status:u(g),blocked_status:u(g),close_status:u(g),canceled_status:u(g)})),type_workflows:u(E(aw)),unknown_field_policy:u(N(...$n))})),dw=u(I({preset:u(N(...$s)),ownership_enforcement:u(N("none","warn","strict")),create_mode_default:u(N("progressive","strict")),close_validation_default:u(N("off","warn","strict")),require_close_reason:u(O),parent_reference:u(N("warn","strict_error")),metadata_profile:u(N("core","strict","custom")),force_required_for_stale_lock:u(O),create_default_type:u(g),workflow_enforcement:u(N("off","warn","strict")),duplicate_detection_mode:u(N("off","advisory","strict")),duplicate_detection_threshold:u(M({min:0,max:1})),duplicate_detection_limit:u(M({int:!0,min:0,max:20}))})),lw=I({name:g,disabled:u(O),require_trusted:u(O),require_provenance:u(O),sandbox_profile:u(N("none","restricted","strict")),allowed_capabilities:u(E(g)),blocked_capabilities:u(E(g)),allowed_surfaces:u(E(g)),blocked_surfaces:u(E(g)),allowed_commands:u(E(g)),blocked_commands:u(E(g)),allowed_actions:u(E(g)),blocked_actions:u(E(g)),allowed_services:u(E(g)),blocked_services:u(E(g))}),ns=N("block","warn"),uw=e=>typeof e=="string"?ns(e):I({global:u(ns),project:u(ns)})(e),fw=u(I({mode:u(N("off","warn","enforce")),trust_mode:u(N("off","warn","enforce")),pm_max_version_exceeded_mode:u(uw),require_provenance:u(O),trusted_extensions:u(E(g)),default_sandbox_profile:u(N("none","restricted","strict")),allowed_extensions:u(E(g)),blocked_extensions:u(E(g)),allowed_capabilities:u(E(g)),blocked_capabilities:u(E(g)),allowed_surfaces:u(E(g)),blocked_surfaces:u(E(g)),allowed_commands:u(E(g)),blocked_commands:u(E(g)),allowed_actions:u(E(g)),blocked_actions:u(E(g)),allowed_services:u(E(g)),blocked_services:u(E(g)),extension_overrides:u(E(lw))})),at=rs(128),mw=I({harness:rs(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:u(E(at,64)),model_environment_keys:u(E(at,64)),session_environment_keys:u(E(at,64)),provenance_environment_keys:u(zr(E(at,64))),provenance_resolvers:u(zr(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:u(E(at,64)),argv_markers:u(E(at,64)),client_names:u(E(at,64))}),pw=I({version:M({int:!0}),id_prefix:g,ids:u(I({token_length:u(M({int:!0,min:4,max:12}))})),author_default:g,agent_identity:u(I({probes_enabled:u(O),identity_vocabulary:u(I({version:M({int:!0,positive:!0}),aliases:zr(rs(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:E(mw)})),mutation_guard:u(I({require_attributed_author:u(O),secret_guard:u(N("off","advise","block")),stale_in_progress_hours:u(M({int:!0,positive:!0}))})),item_format:u(N("toon","json_markdown")),locks:I({ttl_seconds:M({int:!0}),wait_ms:u(M({int:!0,min:0}))}),checkpoints:u(I({retention_days:u(M({int:!0,positive:!0}))})),output:I({default_format:N("toon","json")}),history:u(I({missing_stream:N("auto_create","strict_error"),compact_policy:u(I({enabled:u(O),max_entries:u(M({int:!0,positive:!0})),trigger:u(N("health_warn","auto"))}))})),validation:u(I({sprint_release_format:N("warn","strict_error"),parent_reference:u(N("warn","strict_error")),metadata_profile:u(N("core","strict","custom")),metadata_required_fields:u(E(g)),lifecycle_stale_blocker_reason_patterns:u(E(g)),lifecycle_closure_like_blocked_reason_patterns:u(E(g)),lifecycle_closure_like_resolution_patterns:u(E(g)),lifecycle_closure_like_actual_result_patterns:u(E(g)),estimate_defaults_by_type:u(zr(M({int:!0,positive:!0})))})),governance:dw,workflow:u(I({definition_of_done:E(g)})),testing:u(I({record_results_to_items:O})),telemetry:u(I({enabled:O,first_run_prompt_completed:u(O),capture_level:u(N("minimal","redacted","max")),endpoint:u(g),installation_id:u(g),retention_days:u(M({int:!0,positive:!0}))})),agent_guidance:u(I({prompt_completed:u(O),declined:u(O),declined_at:u(g),template_version:u(M({int:!0,positive:!0})),last_checked_files:u(E(g))})),item_types:u(I({definitions:E(rw)})),schema:cw,context:u(I({default_depth:u(N("brief","standard","deep")),activity_limit:u(M({int:!0,positive:!0})),stale_threshold_days:u(M({int:!0,positive:!0})),sections:u(I({hierarchy:u(O),activity:u(O),progress:u(O),recently_created:u(O),unparented:u(O),blockers:u(O),files:u(O),workload:u(O),staleness:u(O),tests:u(O)}))})),extensions:I({enabled:E(g),disabled:E(g),policy:fw}),search:I({score_threshold:M(),hybrid_semantic_weight:u(M()),max_results:M({int:!0}),embedding_model:g,embedding_corpus_max_characters:u(M()),embedding_batch_size:M({int:!0}),embedding_timeout_ms:u(M({int:!0})),scanner_max_batch_retries:M({int:!0}),provider:u(g),corpus_fields:u(E(g)),mutation_refresh_policy:u(N("cache_only","semantic_configured","semantic_auto")),query_expansion:u(I({enabled:u(O),provider:u(g)})),rerank:u(I({enabled:u(O),model:u(g),top_k:u(M({int:!0,positive:!0}))})),bm25:u(I({k1:u(M()),b:u(M())}))}),providers:I({openai:I({base_url:g,api_key:g,model:g}),ollama:I({base_url:g,model:g})}),vector_store:I({adapter:u(g),collection_name:u(g),qdrant:I({url:g,api_key:g}),lancedb:I({path:g})})});function yl(e){let t=pw(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]="2d377bc4-c624-561c-9856-405c82099070")}catch{}})();var _w={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},gl=120;function os(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function bl(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var yw=bl(_w),hl=new WeakMap;function gw(e){let t=hl.get(e);if(t)return t;let n=bl(e);return hl.set(e,n),n}function fC(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return gl;if(t){let o=gw(t).get(n);if(os(o))return Math.floor(o)}let r=yw.get(n);return os(r)?Math.floor(r):gl}function is(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!os(r)||(t[o]=Math.floor(r))}return t}import{stat as hw}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]="60da76ea-0bd3-56a9-a2bc-d88ba76e1013")}catch{}})();var Ur=new Map;function wl(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function bw(e){try{let t=await hw(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function ze(e){let t=wl(e),n=await Promise.all(t.map(r=>bw(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function un(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function El(e){return Ur.get(e)}function qr(e,t){let n=wl(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));Ur.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Ue(e){if(e){Ur.delete(e);return}Ur.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]="9381a512-7436-5d2c-9667-3845b777b901")}catch{}})();var ww="settings:write",Il=Symbol("pm.settings.persist_source"),Ew=128,kw=new Set(["off","advisory","strict"]);function kl(e){return structuredClone(mo[e])}function vw(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}function vl(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(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 Sw(e){return e.preset==="custom"?vl({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):vl({preset:e.preset},e)}function xw(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),kw.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function Vr(e){let t=e.governance??{},n=vw(t.preset),r=xw(t);if(n==="custom"){let s=kl("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,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,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=kl(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Tl(){return structuredClone(S)}function Al(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function Cl(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function Ol(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function Rl(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function Nl(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function Dl(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function Pl(e){if(typeof e!="string")return S.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,Ew);return n.length>0?n:S.vector_store.collection_name}function ss(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Iw(e,t){let n=e.schema,r=ss(n?.statuses),o=ss(n?.fields),i=ss(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Ot(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.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:Ot(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 us(e,t){Object.defineProperty(e,Il,{value:t,writable:!0,configurable:!0,enumerable:!1})}function fs(e){let t=e[Il];if(!(!t||typeof t!="object"))return t}function AC(e){let t=fs(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,us(e,n)}}function Br(e){let t=structuredClone(e.settings),n=fs(e.settings);return n&&us(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function Tw(e,t,n){let r=he(t);return[n,X(e,r.files.types,K.types),X(e,r.files.statuses,K.statuses),X(e,r.files.fields,K.fields),X(e,r.files.workflows,K.workflows)]}async function Aw(e,t,n){let r=await ze(t);qr(e,{tracked_paths:t,signatures:r,value:Br(n)})}async function Cw(e,t,n){try{await Aw(e,t,n)}catch{Ue(e)}}function Sl(e,t){return e.find(n=>n.path===t)}function Ow(e,t,n){for(let r of n){let o=Sl(e,r),i=Sl(t,r);if(!o||!i||!un([o],[i]))return!1}return!0}async function as(e,t,n,r,o){try{let i=await ze(t);if(!Ow(r,i,o)){Ue(e);return}qr(e,{tracked_paths:t,signatures:i,value:Br(n)})}catch{Ue(e)}}function Rw(e,t){let n=he(e.schema),r=Ot(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=te(r,t.runtime_item_type_definitions),s=te(n.statuses,t.runtime_schema_statuses),a=te(n.fields,t.runtime_schema_fields),c=te(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Ot(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function fn(e){return{settings:Tl(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function Nw(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function ds(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ml(e){let t=S.agent_guidance,n=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 n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:ds(e?.last_checked_files??t.last_checked_files)}}function pe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Dw(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function Pw(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function Ll(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function Mw(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=Ll(e.sandbox_profile));let r=pe(e.allowed_capabilities),o=pe(e.blocked_capabilities),i=pe(e.allowed_surfaces),s=pe(e.blocked_surfaces),a=pe(e.allowed_commands),c=pe(e.blocked_commands),d=pe(e.allowed_actions),l=pe(e.blocked_actions),f=pe(e.allowed_services),p=pe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),f.length>0&&(n.allowed_services=f),p.length>0&&(n.blocked_services=p),n}function Lw(e){let t=new Map;for(let n of e??[]){let r=Mw(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function cs(e){return e==="block"||e==="warn"?e:void 0}function $w(e){if(typeof e=="string")return cs(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=cs(e.global),n=cs(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function oe(e,t){return pe(e?.[t]??S.extensions.policy[t])}function $l(e){let t=$w(e?.pm_max_version_exceeded_mode);return{mode:Dw(e?.mode),trust_mode:Pw(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:oe(e,"trusted_extensions"),default_sandbox_profile:Ll(e?.default_sandbox_profile),allowed_extensions:oe(e,"allowed_extensions"),blocked_extensions:oe(e,"blocked_extensions"),allowed_capabilities:oe(e,"allowed_capabilities"),blocked_capabilities:oe(e,"blocked_capabilities"),allowed_surfaces:oe(e,"allowed_surfaces"),blocked_surfaces:oe(e,"blocked_surfaces"),allowed_commands:oe(e,"allowed_commands"),blocked_commands:oe(e,"blocked_commands"),allowed_actions:oe(e,"allowed_actions"),blocked_actions:oe(e,"blocked_actions"),allowed_services:oe(e,"allowed_services"),blocked_services:oe(e,"blocked_services"),extension_overrides:Lw(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function Fl(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).filter(n=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(n))}function qe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function U(e,t){return e===void 0?t:e}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function ls(e){return Array.isArray(e)?e:[]}function Fw(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Fl(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:qe(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:qe(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:qe(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:qe(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:is(e.validation?.estimate_defaults_by_type)}}function jw(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 zw(e,t){return{...t.search,...e.search,mutation_refresh_policy:Al(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Cl(e.search?.query_expansion?.enabled),provider:Ol(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Rl(e.search?.rerank?.enabled),model:Nl(e.search?.rerank?.model),top_k:Dl(e.search?.rerank?.top_k)}}}function Uw(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Pl(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function qw(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function Bw(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 Vw(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Ot(e){let t=(e??[]).map(r=>Un(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function jl(e){let t=Tl(),n=Vr({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:qw(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},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:Fw(e,t,n),governance:n,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},telemetry:jw(e,t),agent_guidance:Ml(e.agent_guidance??t.agent_guidance),item_types:{definitions:Ot(e.item_types?.definitions)},schema:he(e.schema??t.schema),context:Bw(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:$l(e.extensions.policy??t.extensions.policy)},search:zw(e,t),providers:Vw(e,t),vector_store:Uw(e,t)}}function Ww(e){e.agent_identity=x(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=x(ie(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=ls(e.agent_identity.harness_signals).map(n=>x(ie(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=x(e.locks,["ttl_seconds","wait_ms"]),e.ids=x(e.ids,["token_length"]),e.mutation_guard=x(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=x(e.checkpoints,["retention_days"]),e.output=x(e.output,["default_format"]),e.history=x(e.history,["missing_stream","compact_policy"]),e.validation=x(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=x(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=x(e.workflow,["definition_of_done"]),e.testing=x(e.testing,["record_results_to_items"]),e.telemetry=x(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=x(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=x(e.item_types,["definitions"]),e.schema=x(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=x(ie(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=x(ie(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=x(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=x(ie(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=x(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=x(ie(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=ls(e.extensions.policy.extension_overrides).map(n=>x(ie(n),["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=x(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","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=x(ie(e.search.query_expansion),["enabled","provider"]),e.search.rerank=x(ie(e.search.rerank),["enabled","model","top_k"]),e.providers=x(e.providers,["openai","ollama"]),e.providers.openai=x(ie(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=x(ie(e.providers.ollama),["base_url","model"]),e.vector_store=x(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=x(ie(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=x(ie(e.vector_store.lancedb),["path"])}function Hw(e){return{...e,locks:U(e.locks,S.locks),ids:U(e.ids,S.ids),agent_identity:U(e.agent_identity,S.agent_identity),mutation_guard:U(e.mutation_guard,S.mutation_guard),checkpoints:U(e.checkpoints,S.checkpoints),output:U(e.output,S.output),history:U(e.history,S.history),validation:U(e.validation,S.validation),workflow:U(e.workflow,S.workflow),testing:U(e.testing,S.testing),telemetry:U(e.telemetry,S.telemetry),agent_guidance:U(e.agent_guidance,S.agent_guidance),item_types:U(e.item_types,S.item_types),schema:U(e.schema,S.schema),context:U(e.context,S.context),extensions:U(e.extensions,S.extensions),search:U(e.search,S.search),providers:U(e.providers,S.providers),vector_store:U(e.vector_store,S.vector_store)}}function Kw(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:Fl(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:qe(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:qe(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:qe(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:qe(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:is(e.validation?.estimate_defaults_by_type)}}function Gw(e){return{...S.search,...e.search,mutation_refresh_policy:Al(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:Cl(e.search?.query_expansion?.enabled),provider:Ol(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:Rl(e.search?.rerank?.enabled),model:Nl(e.search?.rerank?.model),top_k:Dl(e.search?.rerank?.top_k)}}}function Xw(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 Yw(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:Pl(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function Jw(e,t,n,r){return{...e,item_format:"toon",validation:Kw(e,t),governance:t,agent_guidance:Ml(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:Gw(e),context:Xw(e),extensions:{enabled:ds(e.extensions?.enabled),disabled:ds(e.extensions?.disabled),policy:$l(e.extensions?.policy)},vector_store:Yw(e)}}function zl(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!te(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:{};zl(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Ul=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function xl(e,t){let n=Hw(e),r=Vr(n),o=he(n.schema),i=Rw(n,t),s=Jw(n,r,o,i),a=x({...s,governance:Sw(r)},Ul);return Ww(a),a}function Qw(e,t={}){let n=xl(e,t.persist_source);if(t.persist_source){let r=jl(t.persist_source.source_settings);r.item_types={definitions:structuredClone(t.persist_source.runtime_item_type_definitions)},r.schema={...r.schema,statuses:structuredClone(t.persist_source.runtime_schema_statuses),fields:structuredClone(t.persist_source.runtime_schema_fields),type_workflows:structuredClone(t.persist_source.runtime_schema_type_workflows)};let o=xl(r,t.persist_source),i=structuredClone(t.persist_source.source_settings);return zl(i,o,n),`${JSON.stringify(x(i,Ul),null,2)}
|
|
70
|
+
`}import Tb from"node:fs/promises";import Ab 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]="58fd6fef-9c13-5c6a-9110-b760461896aa")}catch{}})();function Cb(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function Ob(e,t){return new w(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,b.NOT_FOUND)}async function Rb(e,t){return await vn(Ab.dirname(e)),await(await Tb.open(e,"a")).close(),ue({path:e,scope:"project",op:`${t}:history:auto_create`})}async function Qi(e){return Nb({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Nb(e){let t=Cb(e.itemIds),n=[],r=[];for(let o of t){let i=zt(e.pmRoot,o);if(!await ke(i)){if(e.settings.history.missing_stream==="strict_error")throw Ob(o,e.commandLabel);r.push(...await Rb(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import Ae from"node:fs/promises";import Zi from"node:path";import{randomUUID as Db}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]="c638b65d-148a-5b42-8f24-d6fa9d5ac7d3")}catch{}})();function Pb(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 n=t,r=n.id,o=n.pid,i=n.owner,s=n.created_at,a=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||typeof s!="string"||typeof a!="number"||!Number.isFinite(a)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,created_at:s,ttl_seconds:a},warnings:[]}}async function nl(e){try{let t=await Ae.readFile(e,"utf8");return await ge({path:e,scope:"project"}),Pb(t)}catch(t){return un(t,"ENOENT")?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function un(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function rl(e,t){await ue({path:e,scope:"project",op:t})}function Mb(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:Ke(),ttl_seconds:n}}async function Lb(e,t,n,r){await Ae.mkdir(Zi.dirname(e),{recursive:!0});let o=await Ae.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Mb(t,n,r),null,2)}
|
|
71
|
+
`,"utf8")}finally{await o.close()}await rl(e,"lock:create")}async function ol(e,t){try{return await Ae.unlink(e),await rl(e,t),!0}catch{return!1}}function il(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}function $b(e){return e?.owner?` (owner ${e.owner})`:""}var Fb=25,jb=200,zb=250,Ub=3,qb=".stale-cleanup",sl="owner.json",Bb=1e4,Vb=5*6e4;function Zd(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function Wb(e){let t=process.env.PM_LOCK_WAIT_MS,n=Zd(t);if(n!==void 0)return n;let r=Zd(e);return r!==void 0?r:0}function Hb(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function al(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new w(`Item ${e} is locked${$b(t)}${r}`,b.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:zb}})}function Kb(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 Gb(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new w(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,b.CONFLICT)}}function Xb(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0?null:{pid:r,token:o}}async function cl(e){try{return Xb(await Ae.readFile(Zi.join(e,sl),"utf8"))}catch{return null}}function Yb(e){try{return process.kill(e,0),!0}catch(t){return!un(t,"ESRCH")}}async function es(e){try{return await Ae.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function el(e,t){let n=await cl(e);n===null||n.token!==t||await es(e)}async function tl(e){try{await Ae.mkdir(e)}catch(n){return un(n,"EEXIST"),null}let t={pid:process.pid,token:Db()};try{await Ae.writeFile(Zi.join(e,sl),`${JSON.stringify(t)}
|
|
72
|
+
`,"utf8")}catch{return await es(e),null}return t}async function Jb(e){let t;try{let r=await Ae.stat(e);if(t=Date.now()-r.mtimeMs,t<=Bb)return!1}catch(r){return un(r,"ENOENT")}let n=await cl(e);return n!==null&&Yb(n.pid)&&t<=Vb?!1:es(e)}async function Qb(e,t){let n=`${e}${qb}`,r=await tl(n);if(r!==null)return async()=>el(n,r.token);if(!await Jb(n))return null;let o=await tl(n);return o===null?null:async()=>el(n,o.token)}async function Zb(e){let t=await Qb(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await nl(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!il(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Gb(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=Ub)throw al(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await ol(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function ze(e,t,n,r,o=!1,i=!0,s){let a=await Ie("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let m=Kb(a.result);if(m)return async()=>{await Promise.resolve(m()),await Ie("lock_release",{pm_root:e,id:t,owner:r})}}let c=Qs(e,t),d=Wb(s),l=Date.now(),f=0,p=Fb;for(;;)try{return await Lb(c,t,r,n),async()=>{await ol(c,"lock:release"),await Ie("lock_release",{pm_root:e,id:t,owner:r})}}catch(m){if(!un(m,"EEXIST"))throw new w(`Failed to acquire lock for ${t}: ${Ts(m)}`,b.GENERIC_FAILURE);let h=await nl(c);if(il(h.info,n)){let y=await Zb({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:f,waitBudgetMs:d,startedAtMs:l,fallbackLockInfo:h});if(h=y.lockInfo,y.staleRemovalCounted&&(f+=1),y.shouldRetryCreate)continue}let _=Date.now()-l;if(d===0||_>=d)throw al(t,h.info,d===0?0:_);await Hb(Math.min(p,d-_)),p=Math.min(p*2,jb)}}import ew from"node:fs/promises";import dl 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]="8a15177d-4090-5e58-aac7-20b2ed7684a2")}catch{}})();var zr="_workspace";function ll(e){return dl.join(e,"history",`${zr}.jsonl`)}function tw(e,t){return{metadata:{id:zr,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 ul(e){let t=$r();for(let n of e)t=jr(t,n.patch).document;return Fr(t)}async function fl(e){let t=ll(e.pmRoot),n=await an(t,zr),r=Ji(n);if(!r.ok)throw new TypeError(`Workspace history verification failed: ${r.errors.join(", ")}`);let o=e.idempotencyKey===void 0?void 0:n.find(f=>f.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=new Date().toISOString(),s=n.length===0?Lt:ul(n),a="documents"in s.metadata&&typeof s.metadata.documents=="object"&&s.metadata.documents!==null&&!Array.isArray(s.metadata.documents)?s.metadata.documents:{},c=a[e.documentPath];if(c!==void 0&&ae(c)!==ae(e.before))throw new w(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,b.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=tw({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=At({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 Ct(t,l),{entry:l,historyPath:t}}async function iC(e){let t=await ze(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await fl(e)}finally{await t()}}async function sC(e){let t=await ze(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=ll(e.pmRoot),r=await an(n,zr),o=Ji(r);if(!o.ok)throw new TypeError(`Workspace history verification failed: ${o.errors.join(", ")}`);let i=r.length===0?Lt:ul(r),s=At({nowIso:new Date().toISOString(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Ct(n,s),{entry:s,historyPath:n}}finally{await t()}}async function ml(e){let t=await ze(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await Ce(e.filePath);if(n===e.raw)return!1;let r=n===null?null:JSON.parse(n),o=JSON.parse(e.raw);await Q(e.filePath,e.raw);try{(n!==null||e.recordCreation!==!1)&&await fl({pmRoot:e.pmRoot,documentPath:dl.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:r,after:o,op:e.op,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(i){throw n===null?await ew.rm(e.filePath,{force:!0}):await Q(e.filePath,n),i}return!0}finally{await t()}}import nw from"node:crypto";import pl 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]="50a277b9-d530-5aa0-8bd0-8eb0d36911e5")}catch{}})();function yl(e){let t=(e??"").trim().toLowerCase();return t?t.endsWith("-")?t:`${t}-`:"pm-"}function ts(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function ns(e,t){let n=yl(t),r=ts(e);return r.startsWith(n)?r:`${n}${r}`}function rw(e){let t=Rs(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=nw.randomInt(0,36).toString(36);return n}async function ow(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[pl.join(e,o,`${t}.md`),pl.join(e,o,`${t}.toon`)]);return(await Promise.all(r.map(o=>ke(o)))).some(Boolean)}var _l=4,gl=12;function iw(e){return typeof e!="number"||!Number.isFinite(e)?_l:Math.min(gl,Math.max(_l,Math.trunc(e)))}async function mC(e,t,n={}){let r=iw(n.tokenLength),o=Math.min(r+6,gl),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${yl(t)}${rw(r)}`;if(n.probeExisting===!1||!await ow(e,a,n.typeToFolder??se))return a;i+=1}r+=1}throw new Error(`Unable to generate unique id after ${i} attempts`)}(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]="027f6acb-15cc-5707-85ed-b5298b6b6abe")}catch{}})();var B={ok:!1},g=e=>typeof e=="string"?{ok:!0,value:e}:B,O=e=>typeof e=="boolean"?{ok:!0,value:e}:B;function M(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?B:{ok:!0,value:t}}function N(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:B}function E(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return B;let r=[];for(let o of n){let i=e(o);if(!i.ok)return B;r.push(i.value)}return{ok:!0,value:r}}}function os(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:B}function u(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Ur(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return B;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return B;n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return B;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return B;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var sw=I({key:g,values:E(g),required:u(O),aliases:u(E(g)),description:u(g)}),aw=I({command:N("create","update"),option:g,required:u(O),visible:u(O),enabled:u(O)}),cw=I({name:g,description:u(g),default_status:u(g),folder:u(g),aliases:u(E(g)),required_create_fields:u(E(g)),required_create_repeatables:u(E(g)),options:u(E(sw)),command_option_policies:u(E(aw))}),dw=I({id:g,aliases:u(E(g)),roles:u(E(N(...Ln))),description:u(g),order:u(M())}),lw=I({key:g,metadata_key:u(g),front_matter_key:u(g),cli_flag:u(g),cli_aliases:u(E(g)),description:u(g),type:u(N(...mt)),commands:u(E(N(...$n))),repeatable:u(O),required:u(O),required_on_create:u(O),required_types:u(E(g)),allow_unset:u(O)}),uw=e=>{if(!Array.isArray(e)||e.length!==2)return B;let[t,n]=e;return typeof t!="string"||typeof n!="string"?B:{ok:!0,value:[t,n]}},fw=I({type:g,allowed_transitions:E(uw)}),mw=u(I({version:u(M({int:!0})),files:u(I({types:u(g),statuses:u(g),fields:u(g),workflows:u(g)})),statuses:u(E(dw)),fields:u(E(lw)),workflow:u(I({draft_status:u(g),open_status:u(g),in_progress_status:u(g),blocked_status:u(g),close_status:u(g),canceled_status:u(g)})),type_workflows:u(E(fw)),unknown_field_policy:u(N(...Fn))})),pw=u(I({preset:u(N(...Fs)),ownership_enforcement:u(N("none","warn","strict")),create_mode_default:u(N("progressive","strict")),close_validation_default:u(N("off","warn","strict")),require_close_reason:u(O),parent_reference:u(N("warn","strict_error")),metadata_profile:u(N("core","strict","custom")),force_required_for_stale_lock:u(O),create_default_type:u(g),workflow_enforcement:u(N("off","warn","strict")),duplicate_detection_mode:u(N("off","advisory","strict")),duplicate_detection_threshold:u(M({min:0,max:1})),duplicate_detection_limit:u(M({int:!0,min:0,max:20}))})),_w=I({name:g,disabled:u(O),require_trusted:u(O),require_provenance:u(O),sandbox_profile:u(N("none","restricted","strict")),allowed_capabilities:u(E(g)),blocked_capabilities:u(E(g)),allowed_surfaces:u(E(g)),blocked_surfaces:u(E(g)),allowed_commands:u(E(g)),blocked_commands:u(E(g)),allowed_actions:u(E(g)),blocked_actions:u(E(g)),allowed_services:u(E(g)),blocked_services:u(E(g))}),rs=N("block","warn"),yw=e=>typeof e=="string"?rs(e):I({global:u(rs),project:u(rs)})(e),gw=u(I({mode:u(N("off","warn","enforce")),trust_mode:u(N("off","warn","enforce")),pm_max_version_exceeded_mode:u(yw),require_provenance:u(O),trusted_extensions:u(E(g)),default_sandbox_profile:u(N("none","restricted","strict")),allowed_extensions:u(E(g)),blocked_extensions:u(E(g)),allowed_capabilities:u(E(g)),blocked_capabilities:u(E(g)),allowed_surfaces:u(E(g)),blocked_surfaces:u(E(g)),allowed_commands:u(E(g)),blocked_commands:u(E(g)),allowed_actions:u(E(g)),blocked_actions:u(E(g)),allowed_services:u(E(g)),blocked_services:u(E(g)),extension_overrides:u(E(_w))})),at=os(128),hw=I({harness:os(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:u(E(at,64)),model_environment_keys:u(E(at,64)),session_environment_keys:u(E(at,64)),provenance_environment_keys:u(Ur(E(at,64))),provenance_resolvers:u(Ur(N("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:u(E(at,64)),argv_markers:u(E(at,64)),client_names:u(E(at,64))}),bw=I({version:M({int:!0}),id_prefix:g,ids:u(I({token_length:u(M({int:!0,min:4,max:12}))})),author_default:g,agent_identity:u(I({probes_enabled:u(O),identity_vocabulary:u(I({version:M({int:!0,positive:!0}),aliases:Ur(os(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:E(hw)})),mutation_guard:u(I({require_attributed_author:u(O),secret_guard:u(N("off","advise","block")),stale_in_progress_hours:u(M({int:!0,positive:!0}))})),item_format:u(N("toon","json_markdown")),locks:I({ttl_seconds:M({int:!0}),wait_ms:u(M({int:!0,min:0}))}),checkpoints:u(I({retention_days:u(M({int:!0,positive:!0}))})),output:I({default_format:N("toon","json")}),history:u(I({missing_stream:N("auto_create","strict_error"),compact_policy:u(I({enabled:u(O),max_entries:u(M({int:!0,positive:!0})),trigger:u(N("health_warn","auto"))}))})),validation:u(I({sprint_release_format:N("warn","strict_error"),parent_reference:u(N("warn","strict_error")),metadata_profile:u(N("core","strict","custom")),metadata_required_fields:u(E(g)),lifecycle_stale_blocker_reason_patterns:u(E(g)),lifecycle_closure_like_blocked_reason_patterns:u(E(g)),lifecycle_closure_like_resolution_patterns:u(E(g)),lifecycle_closure_like_actual_result_patterns:u(E(g)),estimate_defaults_by_type:u(Ur(M({int:!0,positive:!0})))})),governance:pw,workflow:u(I({definition_of_done:E(g)})),testing:u(I({record_results_to_items:O})),telemetry:u(I({enabled:O,first_run_prompt_completed:u(O),capture_level:u(N("minimal","redacted","max")),endpoint:u(g),installation_id:u(g),retention_days:u(M({int:!0,positive:!0}))})),agent_guidance:u(I({prompt_completed:u(O),declined:u(O),declined_at:u(g),template_version:u(M({int:!0,positive:!0})),last_checked_files:u(E(g))})),item_types:u(I({definitions:E(cw)})),schema:mw,context:u(I({default_depth:u(N("brief","standard","deep")),activity_limit:u(M({int:!0,positive:!0})),stale_threshold_days:u(M({int:!0,positive:!0})),sections:u(I({hierarchy:u(O),activity:u(O),progress:u(O),recently_created:u(O),unparented:u(O),blockers:u(O),files:u(O),workload:u(O),staleness:u(O),tests:u(O)}))})),extensions:I({enabled:E(g),disabled:E(g),policy:gw}),search:I({score_threshold:M(),hybrid_semantic_weight:u(M()),max_results:M({int:!0}),embedding_model:g,embedding_corpus_max_characters:u(M()),embedding_batch_size:M({int:!0}),embedding_timeout_ms:u(M({int:!0})),scanner_max_batch_retries:M({int:!0}),provider:u(g),corpus_fields:u(E(g)),mutation_refresh_policy:u(N("cache_only","semantic_configured","semantic_auto")),query_expansion:u(I({enabled:u(O),provider:u(g)})),rerank:u(I({enabled:u(O),model:u(g),top_k:u(M({int:!0,positive:!0}))})),bm25:u(I({k1:u(M()),b:u(M())}))}),providers:I({openai:I({base_url:g,api_key:g,model:g}),ollama:I({base_url:g,model:g})}),vector_store:I({adapter:u(g),collection_name:u(g),qdrant:I({url:g,api_key:g}),lancedb:I({path:g})})});function hl(e){let t=bw(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]="2d377bc4-c624-561c-9856-405c82099070")}catch{}})();var ww={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},bl=120;function is(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function El(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var Ew=El(ww),wl=new WeakMap;function kw(e){let t=wl.get(e);if(t)return t;let n=El(e);return wl.set(e,n),n}function gC(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return bl;if(t){let o=kw(t).get(n);if(is(o))return Math.floor(o)}let r=Ew.get(n);return is(r)?Math.floor(r):bl}function ss(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!is(r)||(t[o]=Math.floor(r))}return t}import{stat as vw}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]="60da76ea-0bd3-56a9-a2bc-d88ba76e1013")}catch{}})();var qr=new Map;function kl(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function Sw(e){try{let t=await vw(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function Ue(e){let t=kl(e),n=await Promise.all(t.map(r=>Sw(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function fn(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function vl(e){return qr.get(e)}function Br(e,t){let n=kl(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));qr.set(e,{tracked_paths:n,signatures:r,value:t.value})}function qe(e){if(e){qr.delete(e);return}qr.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]="a434b9ea-4692-51c5-8761-0f1759fff394")}catch{}})();var xw="settings:write",Al=Symbol("pm.settings.persist_source"),Iw=128,Tw=new Set(["off","advisory","strict"]);function Sl(e){return structuredClone(po[e])}function Aw(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}function xl(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(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 Cw(e){return e.preset==="custom"?xl({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):xl({preset:e.preset},e)}function Ow(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),Tw.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function Wr(e){let t=e.governance??{},n=Aw(t.preset),r=Ow(t);if(n==="custom"){let s=Sl("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,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,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Sl(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Cl(){return structuredClone(S)}function Ol(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function Rl(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function Nl(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function Dl(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function Pl(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function Ml(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function Ll(e){if(typeof e!="string")return S.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,Iw);return n.length>0?n:S.vector_store.collection_name}function as(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Rw(e,t){let n=e.schema,r=as(n?.statuses),o=as(n?.fields),i=as(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Ot(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.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:Ot(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 fs(e,t){Object.defineProperty(e,Al,{value:t,writable:!0,configurable:!0,enumerable:!1})}function ms(e){let t=e[Al];if(!(!t||typeof t!="object"))return t}function DC(e){let t=ms(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,fs(e,n)}}function Vr(e){let t=structuredClone(e.settings),n=ms(e.settings);return n&&fs(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function Nw(e,t,n){let r=he(t);return[n,X(e,r.files.types,K.types),X(e,r.files.statuses,K.statuses),X(e,r.files.fields,K.fields),X(e,r.files.workflows,K.workflows)]}async function Dw(e,t,n){let r=await Ue(t);Br(e,{tracked_paths:t,signatures:r,value:Vr(n)})}async function Pw(e,t,n){try{await Dw(e,t,n)}catch{qe(e)}}function Il(e,t){return e.find(n=>n.path===t)}function Mw(e,t,n){for(let r of n){let o=Il(e,r),i=Il(t,r);if(!o||!i||!fn([o],[i]))return!1}return!0}async function cs(e,t,n,r,o){try{let i=await Ue(t);if(!Mw(r,i,o)){qe(e);return}Br(e,{tracked_paths:t,signatures:i,value:Vr(n)})}catch{qe(e)}}function Lw(e,t){let n=he(e.schema),r=Ot(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=te(r,t.runtime_item_type_definitions),s=te(n.statuses,t.runtime_schema_statuses),a=te(n.fields,t.runtime_schema_fields),c=te(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Ot(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function mn(e){return{settings:Cl(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function $w(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function ls(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function $l(e){let t=S.agent_guidance,n=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 n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:ls(e?.last_checked_files??t.last_checked_files)}}function pe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Fw(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function jw(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function Fl(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function zw(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=Fl(e.sandbox_profile));let r=pe(e.allowed_capabilities),o=pe(e.blocked_capabilities),i=pe(e.allowed_surfaces),s=pe(e.blocked_surfaces),a=pe(e.allowed_commands),c=pe(e.blocked_commands),d=pe(e.allowed_actions),l=pe(e.blocked_actions),f=pe(e.allowed_services),p=pe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),f.length>0&&(n.allowed_services=f),p.length>0&&(n.blocked_services=p),n}function Uw(e){let t=new Map;for(let n of e??[]){let r=zw(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function ds(e){return e==="block"||e==="warn"?e:void 0}function qw(e){if(typeof e=="string")return ds(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=ds(e.global),n=ds(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function oe(e,t){return pe(e?.[t]??S.extensions.policy[t])}function jl(e){let t=qw(e?.pm_max_version_exceeded_mode);return{mode:Fw(e?.mode),trust_mode:jw(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:oe(e,"trusted_extensions"),default_sandbox_profile:Fl(e?.default_sandbox_profile),allowed_extensions:oe(e,"allowed_extensions"),blocked_extensions:oe(e,"blocked_extensions"),allowed_capabilities:oe(e,"allowed_capabilities"),blocked_capabilities:oe(e,"blocked_capabilities"),allowed_surfaces:oe(e,"allowed_surfaces"),blocked_surfaces:oe(e,"blocked_surfaces"),allowed_commands:oe(e,"allowed_commands"),blocked_commands:oe(e,"blocked_commands"),allowed_actions:oe(e,"allowed_actions"),blocked_actions:oe(e,"blocked_actions"),allowed_services:oe(e,"allowed_services"),blocked_services:oe(e,"blocked_services"),extension_overrides:Uw(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function zl(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).filter(n=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(n))}function Be(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function U(e,t){return e===void 0?t:e}function ie(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function us(e){return Array.isArray(e)?e:[]}function Bw(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:zl(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Be(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Be(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Be(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Be(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:ss(e.validation?.estimate_defaults_by_type)}}function Vw(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 Ww(e,t){return{...t.search,...e.search,mutation_refresh_policy:Ol(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Rl(e.search?.query_expansion?.enabled),provider:Nl(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Dl(e.search?.rerank?.enabled),model:Pl(e.search?.rerank?.model),top_k:Ml(e.search?.rerank?.top_k)}}}function Hw(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Ll(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function Kw(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function Gw(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 Xw(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Ot(e){let t=(e??[]).map(r=>qn(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function Ul(e){let t=Cl(),n=Wr({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:Kw(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},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:Bw(e,t,n),governance:n,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},telemetry:Vw(e,t),agent_guidance:$l(e.agent_guidance??t.agent_guidance),item_types:{definitions:Ot(e.item_types?.definitions)},schema:he(e.schema??t.schema),context:Gw(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:jl(e.extensions.policy??t.extensions.policy)},search:Ww(e,t),providers:Xw(e,t),vector_store:Hw(e,t)}}function Yw(e){e.agent_identity=x(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=x(ie(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=us(e.agent_identity.harness_signals).map(n=>x(ie(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=x(e.locks,["ttl_seconds","wait_ms"]),e.ids=x(e.ids,["token_length"]),e.mutation_guard=x(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=x(e.checkpoints,["retention_days"]),e.output=x(e.output,["default_format"]),e.history=x(e.history,["missing_stream","compact_policy"]),e.validation=x(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=x(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=x(e.workflow,["definition_of_done"]),e.testing=x(e.testing,["record_results_to_items"]),e.telemetry=x(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=x(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=x(e.item_types,["definitions"]),e.schema=x(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=x(ie(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=x(ie(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=x(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=x(ie(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=x(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=x(ie(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=us(e.extensions.policy.extension_overrides).map(n=>x(ie(n),["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=x(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","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=x(ie(e.search.query_expansion),["enabled","provider"]),e.search.rerank=x(ie(e.search.rerank),["enabled","model","top_k"]),e.providers=x(e.providers,["openai","ollama"]),e.providers.openai=x(ie(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=x(ie(e.providers.ollama),["base_url","model"]),e.vector_store=x(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=x(ie(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=x(ie(e.vector_store.lancedb),["path"])}function Jw(e){return{...e,locks:U(e.locks,S.locks),ids:U(e.ids,S.ids),agent_identity:U(e.agent_identity,S.agent_identity),mutation_guard:U(e.mutation_guard,S.mutation_guard),checkpoints:U(e.checkpoints,S.checkpoints),output:U(e.output,S.output),history:U(e.history,S.history),validation:U(e.validation,S.validation),workflow:U(e.workflow,S.workflow),testing:U(e.testing,S.testing),telemetry:U(e.telemetry,S.telemetry),agent_guidance:U(e.agent_guidance,S.agent_guidance),item_types:U(e.item_types,S.item_types),schema:U(e.schema,S.schema),context:U(e.context,S.context),extensions:U(e.extensions,S.extensions),search:U(e.search,S.search),providers:U(e.providers,S.providers),vector_store:U(e.vector_store,S.vector_store)}}function Qw(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:zl(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Be(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Be(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Be(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Be(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:ss(e.validation?.estimate_defaults_by_type)}}function Zw(e){return{...S.search,...e.search,mutation_refresh_policy:Ol(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:Rl(e.search?.query_expansion?.enabled),provider:Nl(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:Dl(e.search?.rerank?.enabled),model:Pl(e.search?.rerank?.model),top_k:Ml(e.search?.rerank?.top_k)}}}function eE(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 tE(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:Ll(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function nE(e,t,n,r){return{...e,item_format:"toon",validation:Qw(e,t),governance:t,agent_guidance:$l(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:Zw(e),context:eE(e),extensions:{enabled:ls(e.extensions?.enabled),disabled:ls(e.extensions?.disabled),policy:jl(e.extensions?.policy)},vector_store:tE(e)}}function ql(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!te(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:{};ql(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Bl=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function Tl(e,t){let n=Jw(e),r=Wr(n),o=he(n.schema),i=Lw(n,t),s=nE(n,r,o,i),a=x({...s,governance:Cw(r)},Bl);return Yw(a),a}function rE(e,t={}){let n=Tl(e,t.persist_source);if(t.persist_source){let r=Ul(t.persist_source.source_settings);r.item_types={definitions:structuredClone(t.persist_source.runtime_item_type_definitions)},r.schema={...r.schema,statuses:structuredClone(t.persist_source.runtime_schema_statuses),fields:structuredClone(t.persist_source.runtime_schema_fields),type_workflows:structuredClone(t.persist_source.runtime_schema_type_workflows)};let o=Tl(r,t.persist_source),i=structuredClone(t.persist_source.source_settings);return ql(i,o,n),`${JSON.stringify(x(i,Bl),null,2)}
|
|
73
73
|
`}return`${JSON.stringify(n,null,2)}
|
|
74
|
-
`}async function
|
|
74
|
+
`}async function Vl(e){let t=Ge(e),n=[t];await ge({path:t,scope:"project"});let r=vl(e);if(r){let d=await Ue(r.tracked_paths);if(fn(d,r.signatures))return Vr(r.value)}let o=await Ue([t]),i;try{i=await Ce(t)}catch{return mn("settings_read_fs_error")}if(i===null){let d=mn();return await cs(e,[t],d,o,[t]),d}let s=await Ue([t]);if(!fn(o,s))return qe(e),Vl(e);let a;try{a=JSON.parse(i)}catch{let d=mn("settings_read_invalid_json");return await cs(e,[t],d,s,[t]),d}let c=hl(a);if(!c.success){let d=mn("settings_read_invalid_schema");return await cs(e,[t],d,s,[t]),d}try{let d=Ul(c.data),l=Nw(e,d.schema,t);n=l;let f=await Ue(l),p=await bc(e,d.schema),m=await wc(e,d.schema),h=await Ue(l),_={...d,item_types:{definitions:Ot([...d.item_types.definitions,...us(m.type_definitions_from_file)])},schema:m.schema};fs(_,Rw(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:$w(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...p.created_paths.map(T=>`runtime_schema_bootstrap_created:${T}`),...m.warnings]};return p.created_paths.length===0?fn(f,h)?Br(e,{tracked_paths:l,signatures:h,value:Vr(y)}):qe(e):qe(e),y}catch{let d=mn("settings_read_merge_failed");return await Pw(e,n,d),d}}async function PC(e){return(await Vl(e)).settings}async function MC(e,t,n=xw){let r=Ge(e),o=rE(t,{persist_source:ms(t)});try{await ml({pmRoot:e,filePath:r,raw:o,op:n,author:td(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),await ue({path:r,scope:"project",op:n})}finally{qe(e)}}import ct from"node:fs/promises";import Hl from"node:path";import{randomUUID as oE}from"node:crypto";import{createRequire as iE}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]="e94075b0-810d-506c-b6a2-ae322526c078")}catch{}})();var sE="metadata-query-index.sqlite",pn="4";function aE(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Hr;function cE(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?aE(t):null}function _n(){return Hr!==void 0||(Hr=cE(process.versions.node,iE(import.meta.url))),Hr}function Wl(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Rt(e){return Hl.join(e,"runtime",sE)}function dE(e){e.exec(`
|
|
75
75
|
PRAGMA foreign_keys = ON;
|
|
76
76
|
PRAGMA journal_mode = OFF;
|
|
77
77
|
PRAGMA synchronous = OFF;
|
|
@@ -126,7 +126,7 @@ ${Vi(i,t+1)}`).join(`
|
|
|
126
126
|
tags,
|
|
127
127
|
tokenize = 'unicode61'
|
|
128
128
|
);
|
|
129
|
-
`)}function
|
|
129
|
+
`)}function Gr(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function Kl(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
|
|
130
130
|
id, relative_path, metadata_json, status, type, priority,
|
|
131
131
|
updated_at, created_at, parent, assignee, sprint, release
|
|
132
132
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
@@ -141,10 +141,10 @@ ${Vi(i,t+1)}`).join(`
|
|
|
141
141
|
parent = excluded.parent,
|
|
142
142
|
assignee = excluded.assignee,
|
|
143
143
|
sprint = excluded.sprint,
|
|
144
|
-
release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE id = ?").run(n.id),e.prepare("INSERT INTO item_search(id, title, description, tags) VALUES (?, ?, ?, ?)").run(n.id,n.title,n.description,n.tags.join(" "));let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function
|
|
145
|
-
ORDER BY ${n.terminalStatuses&&n.terminalStatuses.length>0?`CASE WHEN status IN (${n.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${d}`).all(...o,...n.terminalStatuses??[],...c).map(p=>{let m=JSON.parse(String(p.metadata_json));if(!m.id)throw new TypeError("Indexed metadata row has no id");return m});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:f}}catch{return i?.close(),null}}async function
|
|
144
|
+
release = excluded.release`).run(n.id,t.relativePath,JSON.stringify(n),n.status,n.type,n.priority,n.updated_at,n.created_at,n.parent??null,n.assignee??null,n.sprint??null,n.release??null),e.prepare("DELETE FROM item_metadata_keys WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_linked_files WHERE item_id = ?").run(n.id),e.prepare("DELETE FROM item_search WHERE id = ?").run(n.id),e.prepare("INSERT INTO item_search(id, title, description, tags) VALUES (?, ?, ?, ?)").run(n.id,n.title,n.description,n.tags.join(" "));let r=e.prepare("INSERT INTO item_metadata_keys(item_id, key) VALUES (?, ?)");for(let i of Object.keys(n))r.run(n.id,i);let o=e.prepare("INSERT INTO item_linked_files(item_id, path, scope, note) VALUES (?, ?, ?, ?)");for(let i of t.linkedFiles??[])o.run(n.id,i.path,i.scope,i.note??null)}async function Gl(e){let t=Rt(e.pmRoot),n=_n();if(!n){await ct.rm(t,{force:!0});return}await ct.mkdir(Hl.dirname(t),{recursive:!0});let r=`${t}.${oE()}.tmp`,o;try{o=new n(r),dE(o),o.exec("BEGIN IMMEDIATE"),Gr(o,"version",pn),Gr(o,"context_fingerprint",e.contextFingerprint),Gr(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Kl(o,i);o.exec("COMMIT"),o.close(),o=void 0,await ct.rm(t,{force:!0}),await ct.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([ct.rm(r,{force:!0})]),i}}function Xr(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Xl(e){let t=Rt(e.pmRoot),n;try{await ct.access(t);let r=_n();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Xr(n);if(o.version!==pn||o.context_fingerprint!==e.contextFingerprint||o.source_cursor!==e.expectedSourceCursor)return n.close(),!1;n.exec("BEGIN IMMEDIATE");let i=n.prepare("DELETE FROM items WHERE relative_path = ?"),s=n.prepare("SELECT id FROM items WHERE relative_path = ?"),a=n.prepare("DELETE FROM item_search WHERE id = ?");for(let c of e.deletedRelativePaths??[]){let d=s.get(c);i.run(c),d&&a.run(d.id)}return e.row&&Kl(n,e.row),Gr(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}function Kr(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function lE(e){let t=[],n=[];Kr(t,n,"status",e.statuses,"IN"),Kr(t,n,"status",e.excludeStatuses,"NOT IN"),Kr(t,n,"type",e.types,"IN"),Kr(t,n,"id",e.ids,"IN");for(let r of e.metadataKeys??[])t.push("EXISTS (SELECT 1 FROM item_metadata_keys AS indexed_key WHERE indexed_key.item_id = items.id AND indexed_key.key = ?)"),n.push(r);for(let[r,o]of[["parent",e.parent],["assignee",e.assignee],["sprint",e.sprint],["release",e.release]])o!==void 0&&(t.push(`${r} = ?`),n.push(o));return e.priority!==void 0&&(t.push("priority = ?"),n.push(e.priority)),{where:t.length===0?"":` WHERE ${t.join(" AND ")}`,parameters:n}}async function UC(e){let t=_n();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=lE(n),i;try{i=new t(Rt(e.pmRoot),{readOnly:!0});let s=Xr(i);if(s.version!==pn||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],d="";n.limit!==void 0?(d+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(d+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(d+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let f=i.prepare(`SELECT metadata_json FROM items${r}
|
|
145
|
+
ORDER BY ${n.terminalStatuses&&n.terminalStatuses.length>0?`CASE WHEN status IN (${n.terminalStatuses.map(()=>"?").join(", ")}) THEN 1 ELSE 0 END ASC, `:""}priority ASC, updated_at DESC, id ASC${d}`).all(...o,...n.terminalStatuses??[],...c).map(p=>{let m=JSON.parse(String(p.metadata_json));if(!m.id)throw new TypeError("Indexed metadata row has no id");return m});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:f}}catch{return i?.close(),null}}async function qC(e){let t=_n();if(!t||e.paths.length===0)return null;let n;try{n=new t(Rt(e.pmRoot),{readOnly:!0});let r=Xr(n);if(r.version!==pn||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let o=e.paths.map(()=>"?").join(", "),i=e.scope===void 0?"":" AND scope = ?",s=[...e.paths,...e.scope===void 0?[]:[e.scope]],a=`path IN (${o})${i}`,c=n.prepare(`SELECT COUNT(DISTINCT item_id) AS count
|
|
146
146
|
FROM item_linked_files
|
|
147
|
-
WHERE ${a}`).get(...s),d=
|
|
147
|
+
WHERE ${a}`).get(...s),d=Wl(e.limit,50),l=Wl(e.offset,0),f=n.prepare(`SELECT items.id, items.metadata_json
|
|
148
148
|
FROM items
|
|
149
149
|
WHERE EXISTS (
|
|
150
150
|
SELECT 1 FROM item_linked_files
|
|
@@ -155,10 +155,10 @@ ${Vi(i,t+1)}`).join(`
|
|
|
155
155
|
FROM item_linked_files
|
|
156
156
|
WHERE item_id IN (${m.map(()=>"?").join(", ")})
|
|
157
157
|
AND ${a}
|
|
158
|
-
ORDER BY path ASC, scope ASC`).all(...m,...s),_=new Map(m.map(y=>[y,[]]));for(let y of h){let T=String(y.item_id),L=_.get(T);L.push({path:String(y.path),scope:String(y.scope),...y.note===null?{}:{note:String(y.note)}}),_.set(T,L)}for(let y of f){let T=JSON.parse(String(y.metadata_json));p.push({item:T,files:_.get(String(y.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:p}}catch{return n?.close(),null}}async function
|
|
158
|
+
ORDER BY path ASC, scope ASC`).all(...m,...s),_=new Map(m.map(y=>[y,[]]));for(let y of h){let T=String(y.item_id),L=_.get(T);L.push({path:String(y.path),scope:String(y.scope),...y.note===null?{}:{note:String(y.note)}}),_.set(T,L)}for(let y of f){let T=JSON.parse(String(y.metadata_json));p.push({item:T,files:_.get(String(y.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:p}}catch{return n?.close(),null}}async function BC(e){let t=_n();if(!t)return null;let n;try{n=new t(Rt(e.pmRoot),{readOnly:!0});let r=Xr(n);if(r.version!==pn||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let i=n.prepare(`SELECT items.metadata_json
|
|
159
159
|
FROM item_search
|
|
160
160
|
JOIN items ON items.id = item_search.id
|
|
161
161
|
WHERE item_search MATCH ?
|
|
162
162
|
ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
|
|
163
|
-
LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(s=>JSON.parse(String(s.metadata_json)));return n.close(),{source_cursor:r.source_cursor,items:i}}catch{return n?.close(),null}}async function Xr(e){await ct.rm(Rt(e),{force:!0})}import V from"node:fs/promises";import $ from"node:path";import{createHash as sE,randomUUID as Ql}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]="8ed70856-9cba-599d-8b53-21a981af1f40")}catch{}})();var we=8,Zl=500,aE="metadata-derived-index",cE="metadata-cache.json",dE="metadata-cache-bodies.json",lE="metadata-cache-collections.json",uE="metadata-cache-delta.json",fE="metadata-cache-manifest.json",Gl=4,mE=["comments","notes","learnings","files","tests","test_runs","docs"];function eu(){return ur(Zt())}function Jr(e){let t={...e},n={};for(let r of mE)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function tu(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function nu(e,t,n,r){let o=sE("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function Qr(e){return $.join(e,"runtime",cE)}function Zr(e){return $.join(e,"runtime",dE)}function eo(e){return $.join(e,"runtime",lE)}function ps(e){return $.join(e,"runtime",uE)}function _s(e){return $.join(e,"runtime",fE)}function to(e,t){let n=$.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var pE=24,le=new Map,no=new WeakMap;function ys(e){return no.get(e)??e.source_cursor}function _E(e,t){let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){no.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function yE(e,t){if(!e)return;let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){no.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function gE(e,t){if(!e)return;let n=ys(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){no.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function hE(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(_E(e,r),yE(t,r),gE(n,r))}function ms(e,t){le.size>=pE&&!le.has(e)&&Nn(le),le.set(e,t)}async function Be(e,t){let n;try{n=await V.stat(e)}catch{return le.delete(e),null}let r=le.get(e);if(r&&_n(r.signature,n.mtimeMs,n.ctimeMs,n.size))return le.delete(e),le.set(e,r),r.envelope;let o;try{o=t(await V.readFile(e,"utf8"))}catch{o=null}return ms(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function bE(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==we||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=Qr(e),i=await Be(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await Be(to(o,t),r);return s===null&&hn(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function wE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==we||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Zr(e),o=await Be(r,n);return t&&o?.context_fingerprint!==t?await Be(to(r,t),n):o}async function EE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==we||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=eo(e),o=await Be(r,n);return t&&o?.context_fingerprint!==t?await Be(to(r,t),n):o}async function gs(e){let t=ps(e),n=await Be(t,r=>{let o=JSON.parse(r);return o.version!==we||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await V.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function hs(e){let t=_s(e),n=await Be(t,r=>{let o=JSON.parse(r);return o.version!==we||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await V.stat(t),await Nt(e)}catch{}return null}async function yn(e,t){await V.mkdir($.dirname(e),{recursive:!0}),await Q(e,JSON.stringify(t));try{let r=await V.stat(e);ms(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{le.delete(e)}let n=$.dirname($.dirname(e));if(e===Qr(n)||e===Zr(n)||e===eo(n)){let r=to(e,t.context_fingerprint);await Q(r,JSON.stringify(t));try{let c=await V.stat(r);ms(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{le.delete(r)}let o=$.dirname(e),i=$.extname(e),s=$.basename(e,i),a=(await V.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==$.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>$.join(o,c.name));if(a.length>Gl){let c=(await Promise.all(a.map(async d=>{try{return{path:d,mtime:(await V.stat(d)).mtimeMs}}catch{return null}}))).filter(d=>d!==null);for(let d of c.sort((l,f)=>l.mtime-f.mtime).slice(0,Math.max(0,c.length-Gl)))await V.rm(d.path,{force:!0}),le.delete(d.path)}}}function kE(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ru(e,t,n){return e===void 0||kE(e,t,n)}function hn(e,t){e&&!e.includes(t)&&e.push(t)}function _n(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function vE(e,t,n){let r=$.join(e,t);try{let o=await V.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code!=="ENOENT"&&hn(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function SE(e,t){try{let n=await V.stat($.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function Yr(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await SE(e,n))))}function gn(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&_n(o,r.mtime_ms,r.ctime_ms,r.size)})}function xE(e){return qn.some(t=>e.toLowerCase().endsWith(t))}function IE(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function TE(e,t,n){if(n)for(let r of await ge({path:e,scope:"project"}))hn(t,r)}function Xl(e,t,n,r){if(e)return t&&n?n.collections:r}async function AE(e,t,n){let r=await V.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=ko(e);await TE(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=c!==void 0&&_n(c,o,i,s),l=n.previousBodies[t],f=l!==void 0&&_n(l,o,i,s),p=n.previousCollections[t],m=p!==void 0&&_n(p,o,i,s);if(!(!d||n.includeBody&&!f||n.includeCollections&&!m))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Xl(n.includeCollections,m,p,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let _=await V.readFile(e,"utf8"),y=gr(_,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:L=>hn(n.warnings,L)}),T=Jr(y.metadata);return IE(n.state.misses,n.includeBody,n.includeCollections,d,f,m),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:T.light,heavyMetadata:Xl(n.includeCollections,m,p,T.heavy),bodyLength:d?c.body_length:y.body.length,body:n.includeBody?y.body:void 0}}function CE(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?tu(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};ru(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function OE(e,t,n,r){try{let o=await AE(t,n,r);CE(t,n,r,o)}catch{hn(r.warnings,`item_list_item_read_failed:${e}/${$.basename(t)}`)}}function RE(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function NE(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function DE(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function PE(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function ME(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!xE(s))continue;let a=$.join(o,s),c=$.relative(t.pmRoot,a);n.push(OE(r,a,c,t))}return n}async function LE(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!gn(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await yn(Qr(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await yn(_s(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let n=[...e.state.documentsById.values()].map(({candidate:r})=>({relativePath:$.relative(e.pmRoot,r.item_path),metadata:Jr(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Hl({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Xr(e.pmRoot)}catch{}}async function $E(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await yn(Zr(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function FE(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await yn(eo(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function bs(e,t,n={}){let r=await hs(e);return n.required!==!0&&(r===null||r.entry_count<Zl)?async()=>{}:je(e,aE,30,t,!1,!1,3e3)}async function JC(e,t){let n=await hs(e);if(n===null)return null;let r=await gs(e);if(r.invalid)return await Nt(e),null;let o=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.source_cursor:n.source_cursor,i=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.directory_signatures:n.directory_signatures;return t&&!gn(i,await Yr(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function Yl(e,t){let n=$.relative(e,t);return n===""||n===".."||n.startsWith(`..${$.sep}`)||$.isAbsolute(n)?null:n}async function Nt(e){await Promise.all([Qr(e),Zr(e),eo(e),ps(e),_s(e)].map(async t=>{await V.rm(t,{force:!0}),le.delete(t)})),await Xr(e)}async function jE(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await V.stat(e.mutation.itemPath),n=Jr(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function zE(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function ws(e){let t=Yl(e.pmRoot,e.itemPath),n=e.previousItemPath?Yl(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Nt(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=nu(e.preferredFormat,e.typeToFolder,e.schema,eu()),o=await hs(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await gs(e.pmRoot);if(s.invalid)return await Nt(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=zE(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await jE({mutation:e});let d=Ql();return await yn(ps(e.pmRoot),{version:we,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await Yr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Kl({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:Jr(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Xr(e.pmRoot),[]}catch{return await Nt(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function UE(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function Jl(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function qE(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function BE(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=ko(n);if(!o)continue;let i=e.includeCollections?tu(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ru(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:$.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function VE(e){return e.forceSourceScan||ai()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!gn(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Jl(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Jl(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&qE(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function ro(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=eu(),d=nu(t,n,o,c),l=await gs(e);l.invalid&&await Nt(e);let f=await bE(e,d,i.cacheDiagnostics),p=s?await wE(e,d):null,m=a?await EE(e,d):null;hE(f,p,m,l.envelope);let h=RE(f,d),_=NE(p,d),y=DE(m,d),T=[...new Set(Object.values(n))],L=await Yr(e,T),J=Object.keys(h),q=Math.max(1,Math.floor(i.derivedIndexMinimumItems??Zl));if(VE({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:f,existingBodyCache:p,existingCollectionsCache:m,directorySignatures:L,entryKeys:J,minimumIndexedItems:q,includeBody:s,includeCollections:a,previousBodies:_,previousCollections:y}))return BE({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:h,previousBodies:_,previousCollections:y});let dt=await Promise.all(T.map(uu=>vE(e,uu,r))),bn=ai(),Ee=PE(),so={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,dispatchReadHooks:bn,previousEntries:h,previousBodies:_,previousCollections:y,state:Ee};await Promise.all(ME(dt,so));let wn=await Yr(e,T),ks=gn(L,wn)?wn:{},ao=Ee.misses.metadata||Object.keys(h).length!==Object.keys(Ee.newEntries).length||!gn(f?.directory_signatures,ks)||f===null?Ql():f.source_cursor;return await LE({pmRoot:e,contextFingerprint:d,sourceCursor:ao,existingCache:f,previousEntries:h,directorySignatures:ks,state:Ee,minimumIndexedItems:q}),s&&await $E({pmRoot:e,contextFingerprint:d,sourceCursor:ao,existingBodyCache:p,previousBodies:_,state:Ee}),a&&await FE({pmRoot:e,contextFingerprint:d,sourceCursor:ao,existingCollectionsCache:m,previousCollections:y,state:Ee}),UE(Ee)}async function ou(e,t,n,r,o){return(await ro(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}async function iu(e,t,n,r,o){return(await ro(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}import Ve from"node:fs/promises";import Dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="827bddce-74c6-5b36-ae56-bf3b14625f82")}catch{}})();async function WE(e){try{return await Ve.access(e),!0}catch{return!1}}function oo(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function HE(e,t){e&&(e.includes(t)||e.push(t))}function su(e){return e??ur(Zt())}function KE(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}function io(e){return new w(`Tracker root is not a directory at ${e}.`,b.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",nextSteps:["Pass the tracker directory itself, usually <workspace>/.agents/pm."]})}async function GE(e){let t=Dt.parse(Dt.resolve(e)).root,n=Dt.dirname(Dt.resolve(e));for(;n!==t;){let r;try{r=await Ve.stat(n)}catch(o){if(oo(o,"ENOTDIR"))throw io(e);if(!oo(o,"ENOENT"))throw o;n=Dt.dirname(n);continue}if(!r.isDirectory())throw io(e);break}}async function Es(e){let t;try{t=await Ve.stat(e)}catch(n){throw oo(n,"ENOENT")?(await GE(e),new w(`Tracker root does not exist at ${e}.`,b.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",nextSteps:["Confirm the tracker root path and retry the SDK read.","Initialize a tracker before enumerating its item metadata."]})):oo(n,"ENOTDIR")?io(e):n}if(!t.isDirectory())throw io(e)}async function au(e,t,n="pm-",r,o=se){let i=ts(t,n),s=es(t),a=i===s?[i]:[i,s],c=Object.entries(o),d=KE(r);for(let l of a)for(let[f]of c)for(let p of d){let m=Eo(e,f,l,p,o);if(await WE(m))return{id:l,type:f,itemPath:m,item_format:p}}return null}async function cu(e,t={}){let n=await Ve.readFile(e.itemPath,"utf8");await ge({path:e.itemPath,scope:"project"});let r=gr(n,{format:e.item_format,schema:t.schema,extensionFieldNames:su(t.extensionFieldNames),onWarning:o=>HE(t.warnings,o)});return{raw:n,document:r}}async function XE(e,t,n=se,r,o){return await Es(e),(await ou(e,t,n,r,o)).map(s=>s.metadata)}async function hO(e,t,n=se,r,o){return await Es(e),(await iu(e,t,n,r,o)).map(s=>s.metadata)}async function bO(e,t,n=se,r,o,i={}){return await Es(e),(await ro(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function du(e){return{async get(t){let n=await au(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await cu(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>XE(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function YE(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await Ve.readdir(Dt.join(e,o));for(let s of i)for(let a of qn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function JE(e,t,n,r){let o=ts(t,n),i=await YE(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:pt(c,o,s)})).filter(c=>c.distance!==null).sort((c,d)=>c.distance-d.distance).slice(0,3).map(c=>c.id)}async function QE(e,t,n,r){let o=await JE(e,t,n,r),i=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return o.length>0&&i.unshift(`Did you mean one of: ${o.join(", ")}?`),new w(`Item ${t} not found`,b.NOT_FOUND,{nextSteps:i})}function ZE(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function lu(e){let t=e.typeToFolder??Gs(e.settings,Zt()).type_to_folder,n=await au(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await QE(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await je(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let o=[],{raw:i,document:s}=await cu(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,d=Zc(e.author),l=Vr(e.settings);if(a&&c!==d&&!e.force&&!ZE(e.op,e.bypassAssigneeConflict)){if(l.ownership_enforcement==="strict")throw new w(`Item ${n.id} is assigned to ${a}. Use --force to override.`,b.CONFLICT);l.ownership_enforcement==="warn"&&o.push(`ownership_warning:assignee_conflict:${n.id}:${a}`)}return{typeToFolder:t,located:n,originalRaw:i,document:s,warnings:o,releaseLock:r}}catch(o){throw await r(),o}}function ek(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function tk(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await Q(e.originalItemPath,e.originalRaw),await Ve.rm(e.effectiveTargetItemPath,{force:!0});return}await Q(e.originalItemPath,e.originalRaw)}}async function wO(e){let t=await lu({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a}=t;try{let c=me(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=me(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=await e.mutate(d);if(e.skipNoop===!0&&l.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...l.warnings??[]]};d.metadata.updated_at=He();let f=me(d,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await si({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:l.changedFields,sdk:du({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await Ji({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),m="toon",h=Fc(f,{format:m,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),_=Eo(e.pmRoot,f.metadata.type,r.id,m,n),y=zt(e.pmRoot,r.id),T=await Ie("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:_,history_path:y,item_format:m,before:c,after:f,contents:h}),{effectiveTargetItemPath:L,effectiveSerializedAfter:J,skipItemWrite:q}=ek(T,_,h),dt=await bs(e.pmRoot,e.author),bn=[];try{q||await Q(L,J),!q&&L!==r.itemPath&&await Ve.rm(r.itemPath);let so=At({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message});try{await Ct(y,so)}catch(wn){throw await tk({skipItemWrite:q,effectiveTargetItemPath:L,originalItemPath:r.itemPath,originalRaw:o}),wn}q||(bn=await ws({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:L,previousItemPath:r.itemPath,document:f}))}finally{await dt()}let Ee=[...await ue({path:L,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:l.changedFields}),...await ue({path:y,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:l.changedFields})];return ii({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:dr(c.metadata,l.changedFields),current:dr(f.metadata,l.changedFields),changed_fields:l.changedFields}),{item:f.metadata,body:f.body,changedFields:l.changedFields,warnings:[...s,...l.warnings??[],...p.warnings,...T.warnings,...bn,...Ee]}}finally{await a()}}async function EO(e){let t=await lu({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:n,originalRaw:r,document:o,warnings:i,releaseLock:s}=t;try{let a=su(void 0),c=me(o,{schema:e.settings.schema,extensionFieldNames:a});await si({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:du({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let d=await Ji({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),l=He(),f=Lt,p=At({nowIso:l,author:e.author,op:"delete",before:c,after:f,message:e.message}),m=zt(e.pmRoot,n.id),h=await Ie("item_store_delete",{op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:m,before:c}),_=n.itemPath,y=!1;if(h.handled&&typeof h.result=="object"&&h.result!==null){let q=h.result;typeof q.item_path=="string"&&q.item_path.trim().length>0&&(_=q.item_path),q.skip_delete===!0&&(y=!0)}if(e.dryRun===!0)return{item:c.metadata,changedFields:["deleted"],targetPath:_,warnings:[...i,...d.warnings,...h.warnings]};let T=await bs(e.pmRoot,e.author),L=[];try{y||await Ve.rm(_);try{await Ct(m,p)}catch(q){throw y||await Q(_,r),q}y||(L=await ws({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:_,document:null}))}finally{await T()}let J=[...await ue({path:_,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:f,changed_fields:["deleted"]}),...await ue({path:m,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:f,changed_fields:["deleted"]})];return ii({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:dr(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...i,...d.warnings,...h.warnings,...L,...J]}}finally{await s()}}export{kn as a,ke as b,Ce as c,Q as d,Pt as e,ik as f,_e as g,vn as h,co as i,ak as j,Sn as k,xn as l,In as m,Tn as n,An as o,Cn as p,lk as q,pu as r,uk as s,se as t,yu as u,ye as v,mo as w,gu as x,lo as y,S as z,b as A,fk as B,w as C,bu as D,_k as E,yk as F,gk as G,Is as H,hk as I,bk as J,wk as K,xs as L,Ts as M,Ek as N,Nn as O,ku as P,Ik as Q,He as R,Oe as S,W as T,Nk as U,Dk as V,Ds as W,Ps as X,Ho as Y,Pn as Z,jk as _,zk as $,Wu as aa,Ls as ba,ft as ca,Mn as da,mt as ea,Ln as fa,qk as ga,Bk as ha,Vk as ia,Fn as ja,jn as ka,Wk as la,Hk as ma,Kk as na,Gk as oa,zn as pa,$t as qa,go as ra,Xk as sa,Fs as ta,Yk as ua,Jk as va,Qk as wa,Zk as xa,qs as ya,Ks as za,cv as Aa,wo as Ba,df as Ca,Gs as Da,vf as Ea,Sf as Fa,dv as Ga,lv as Ha,qn as Ia,jf as Ja,gv as Ka,hv as La,bv as Ma,Ys as Na,Ke as Oa,Eo as Pa,ko as Qa,zt as Ra,Js as Sa,Uf as Ta,Bn as Ua,qf as Va,wv as Wa,Bf as Xa,Vf as Ya,Ev as Za,kv as _a,Wf as $a,vv as ab,pt as bb,Cm as cb,ya as db,ga as eb,ba as fb,wa as gb,xo as hb,Io as ib,Iv as jb,Zf as kb,Qs as lb,Tv as mb,Zs as nb,To as ob,rm as pb,om as qb,j as rb,Vt as sb,Ao as tb,Co as ub,Oo as vb,Ro as wb,No as xb,Do as yb,Po as zb,Mv as Ab,ae as Bb,te as Cb,Ge as Db,Em as Eb,Mo as Fb,vm as Gb,Lo as Hb,$o as Ib,Fo as Jb,jo as Kb,zo as Lb,Uo as Mb,Bo as Nb,Vo as Ob,Wo as Pb,Gm as Qb,rp as Rb,ip as Sb,sp as Tb,pp as Ub,MS as Vb,LS as Wb,$S as Xb,VS as Yb,HS as Zb,Gp as _b,Xp as $b,oi as ac,Qp as bc,Zp as cc,ex as dc,tx as ec,nx as fc,rx as gc,ox as hc,ix as ic,sx as jc,ax as kc,Zt as lc,cx as mc,dx as nc,oc,lx as pc,ii as qc,dr as rc,ux as sc,fx as tc,ue as uc,si as vc,ge as wc,ai as xc,mx as yc,px as zc,_x as Ac,yx as Bc,Ie as Cc,lr as Dc,ur as Ec,xx as Fc,Ix as Gc,K as Hc,fi as Ic,he as Jc,X as Kc,Nx as Lc,hc as Mc,wc as Nc,mi as Oc,Ec as Pc,kc as Qc,Dx as Rc,xc as Sc,tn as Tc,Fx as Uc,jx as Vc,ht as Wc,Tc as Xc,Ux as Yc,Ac as Zc,j_ as _c,qx as $c,fr as ad,U_ as bd,Hx as cd,mr as dd,yr as ed,Yy as fd,gr as gd,Fc as hd,me as id,jc as jd,rt as kd,Uc as ld,pI as md,_I as nd,Vc as od,sg as pd,vI as qd,SI as rd,xI as sd,Yc as td,II as ud,TI as vd,AI as wd,yg as xd,Zc as yd,ed as zd,sn as Ad,XT as Bd,YT as Cd,Ci as Dd,LI as Ed,td as Fd,vr as Gd,od as Hd,Ig as Id,Tg as Jd,UI as Kd,be as Ld,qI as Md,Cg as Nd,Ng as Od,Fg as Pd,sd as Qd,GI as Rd,XI as Sd,Ni as Td,Di as Ud,YI as Vd,qg as Wd,JI as Xd,QI as Yd,St as Zd,_d,oT as $d,Qg as ae,hd as be,iT as ce,bd as de,Ed as ee,sT as fe,kd as ge,Sd as he,ph as ie,pT as je,yh as ke,Id as le,_T as me,Ad as ne,hh as oe,kh as pe,Cd as qe,Sh as re,xh as se,Ih as te,hT as ue,bT as ve,Th as we,Tr as xe,wT as ye,Ah as ze,Od as Ae,Rd as Be,ET as Ce,kT as De,vT as Ee,ST as Fe,xT as Ge,IT as He,Ch as Ie,CT as Je,Ph as Ke,Mh as Le,OT as Me,Ar as Ne,Pd as Oe,Xh as Pe,$d as Qe,UT as Re,qT as Se,fb as Te,dn as Ue,Kd as Ve,mA as We,At as Xe,Ct as Ye,hb as Ze,Lr as _e,Mr as $e,$r as af,EA as bf,kA as cf,Yd as df,Fr as ef,Yi as ff,vA as gf,SA as hf,Ji as if,Tb as jf,je as kf,jr as lf,cl as mf,eC as nf,tC as of,ul as pf,pl as qf,es as rf,ts as sf,cC as tf,fC as uf,Vr as vf,AC as wf,ql as xf,CC as yf,OC as zf,LC as Af,$C as Bf,FC as Cf,Zl as Df,mE as Ef,bs as Ff,JC as Gf,ws as Hf,ro as If,au as Jf,cu as Kf,XE as Lf,hO as Mf,bO as Nf,du as Of,QE as Pf,wO as Qf,EO as Rf};
|
|
164
|
-
//# sourceMappingURL=chunk-
|
|
163
|
+
LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(s=>JSON.parse(String(s.metadata_json)));return n.close(),{source_cursor:r.source_cursor,items:i}}catch{return n?.close(),null}}async function Yr(e){await ct.rm(Rt(e),{force:!0})}import V from"node:fs/promises";import $ from"node:path";import{createHash as uE,randomUUID as eu}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]="8ed70856-9cba-599d-8b53-21a981af1f40")}catch{}})();var we=8,tu=500,fE="metadata-derived-index",mE="metadata-cache.json",pE="metadata-cache-bodies.json",_E="metadata-cache-collections.json",yE="metadata-cache-delta.json",gE="metadata-cache-manifest.json",Yl=4,hE=["comments","notes","learnings","files","tests","test_runs","docs"];function nu(){return fr(Zt())}function Qr(e){let t={...e},n={};for(let r of hE)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function ru(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function ou(e,t,n,r){let o=uE("sha256");o.update(`format:${e??"default"}`);let i=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return o.update(`|types:${i}`),n&&o.update(`|schema:${JSON.stringify(n)}`),r.length>0&&o.update(`|extension_fields:${r.join(",")}`),o.digest("hex").slice(0,16)}function Zr(e){return $.join(e,"runtime",mE)}function eo(e){return $.join(e,"runtime",pE)}function to(e){return $.join(e,"runtime",_E)}function _s(e){return $.join(e,"runtime",yE)}function ys(e){return $.join(e,"runtime",gE)}function no(e,t){let n=$.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var bE=24,le=new Map,ro=new WeakMap;function gs(e){return ro.get(e)??e.source_cursor}function wE(e,t){let n=gs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ro.set(e,n);for(let[r,o]of Object.entries(t.changes))o.entry?e.entries[r]=o.entry:delete e.entries[r];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function EE(e,t){if(!e)return;let n=gs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ro.set(e,n);for(let[r,o]of Object.entries(t.changes))o.body?e.bodies[r]=o.body:delete e.bodies[r];e.source_cursor=t.source_cursor}}function kE(e,t){if(!e)return;let n=gs(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ro.set(e,n);for(let[r,o]of Object.entries(t.changes))o.collections?e.collections[r]=o.collections:delete e.collections[r];e.source_cursor=t.source_cursor}}function vE(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(wE(e,r),EE(t,r),kE(n,r))}function ps(e,t){le.size>=bE&&!le.has(e)&&Dn(le),le.set(e,t)}async function Ve(e,t){let n;try{n=await V.stat(e)}catch{return le.delete(e),null}let r=le.get(e);if(r&&yn(r.signature,n.mtimeMs,n.ctimeMs,n.size))return le.delete(e),le.set(e,r),r.envelope;let o;try{o=t(await V.readFile(e,"utf8"))}catch{o=null}return ps(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function SE(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==we||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=Zr(e),i=await Ve(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await Ve(no(o,t),r);return s===null&&bn(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function xE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==we||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=eo(e),o=await Ve(r,n);return t&&o?.context_fingerprint!==t?await Ve(no(r,t),n):o}async function IE(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==we||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=to(e),o=await Ve(r,n);return t&&o?.context_fingerprint!==t?await Ve(no(r,t),n):o}async function hs(e){let t=_s(e),n=await Ve(t,r=>{let o=JSON.parse(r);return o.version!==we||typeof o.base_source_cursor!="string"||typeof o.source_cursor!="string"||typeof o.changes!="object"||o.changes===null?null:o});if(n)return{envelope:n,invalid:!1};try{return await V.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function bs(e){let t=ys(e),n=await Ve(t,r=>{let o=JSON.parse(r);return o.version!==we||typeof o.context_fingerprint!="string"||typeof o.source_cursor!="string"||!Number.isInteger(o.entry_count)||o.entry_count<0||typeof o.directory_signatures!="object"||o.directory_signatures===null?null:o});if(n)return n;try{await V.stat(t),await Nt(e)}catch{}return null}async function gn(e,t){await V.mkdir($.dirname(e),{recursive:!0}),await Q(e,JSON.stringify(t));try{let r=await V.stat(e);ps(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{le.delete(e)}let n=$.dirname($.dirname(e));if(e===Zr(n)||e===eo(n)||e===to(n)){let r=no(e,t.context_fingerprint);await Q(r,JSON.stringify(t));try{let c=await V.stat(r);ps(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{le.delete(r)}let o=$.dirname(e),i=$.extname(e),s=$.basename(e,i),a=(await V.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==$.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>$.join(o,c.name));if(a.length>Yl){let c=(await Promise.all(a.map(async d=>{try{return{path:d,mtime:(await V.stat(d)).mtimeMs}}catch{return null}}))).filter(d=>d!==null);for(let d of c.sort((l,f)=>l.mtime-f.mtime).slice(0,Math.max(0,c.length-Yl)))await V.rm(d.path,{force:!0}),le.delete(d.path)}}}function TE(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function iu(e,t,n){return e===void 0||TE(e,t,n)}function bn(e,t){e&&!e.includes(t)&&e.push(t)}function yn(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function AE(e,t,n){let r=$.join(e,t);try{let o=await V.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&o.code!=="ENOENT"&&bn(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function CE(e,t){try{let n=await V.stat($.join(e,t));return[t,{exists:!0,mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function Jr(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await CE(e,n))))}function hn(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([n,r])=>{let o=e[n];return o!==void 0&&o.exists===r.exists&&yn(o,r.mtime_ms,r.ctime_ms,r.size)})}function OE(e){return Bn.some(t=>e.toLowerCase().endsWith(t))}function RE(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function NE(e,t,n){if(n)for(let r of await ge({path:e,scope:"project"}))bn(t,r)}function Jl(e,t,n,r){if(e)return t&&n?n.collections:r}async function DE(e,t,n){let r=await V.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=vo(e);await NE(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],d=c!==void 0&&yn(c,o,i,s),l=n.previousBodies[t],f=l!==void 0&&yn(l,o,i,s),p=n.previousCollections[t],m=p!==void 0&&yn(p,o,i,s);if(!(!d||n.includeBody&&!f||n.includeCollections&&!m))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Jl(n.includeCollections,m,p,void 0),bodyLength:c.body_length,body:n.includeBody?l.body:void 0};let _=await V.readFile(e,"utf8"),y=hr(_,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:L=>bn(n.warnings,L)}),T=Qr(y.metadata);return RE(n.state.misses,n.includeBody,n.includeCollections,d,f,m),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:d?c.metadata:T.light,heavyMetadata:Jl(n.includeCollections,m,p,T.heavy),bodyLength:d?c.body_length:y.body.length,body:n.includeBody?y.body:void 0}}function PE(e,t,n,r){n.state.newEntries[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,metadata:r.lightMetadata,body_length:r.bodyLength},n.includeBody&&r.body!==void 0&&(n.state.newBodies[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,body:r.body}),n.includeCollections&&r.heavyMetadata!==void 0&&(n.state.newCollections[t]={mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size,collections:r.heavyMetadata});let o=n.includeCollections?ru(r.lightMetadata,r.heavyMetadata):r.lightMetadata,i=n.state.documentsById.get(o.id),s={metadata:o,body:r.body,item_format:r.itemFormat,item_path:e};iu(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function ME(e,t,n,r){try{let o=await DE(t,n,r);PE(t,n,r,o)}catch{bn(r.warnings,`item_list_item_read_failed:${e}/${$.basename(t)}`)}}function LE(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function $E(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function FE(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function jE(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function zE(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!OE(s))continue;let a=$.join(o,s),c=$.relative(t.pmRoot,a);n.push(ME(r,a,c,t))}return n}async function UE(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!hn(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await gn(Zr(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await gn(ys(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let n=[...e.state.documentsById.values()].map(({candidate:r})=>({relativePath:$.relative(e.pmRoot,r.item_path),metadata:Qr(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Gl({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Yr(e.pmRoot)}catch{}}async function qE(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await gn(eo(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function BE(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await gn(to(e.pmRoot),{version:we,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function ws(e,t,n={}){let r=await bs(e);return n.required!==!0&&(r===null||r.entry_count<tu)?async()=>{}:ze(e,fE,30,t,!1,!1,3e3)}async function nO(e,t){let n=await bs(e);if(n===null)return null;let r=await hs(e);if(r.invalid)return await Nt(e),null;let o=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.source_cursor:n.source_cursor,i=r.envelope?.context_fingerprint===n.context_fingerprint&&r.envelope.base_source_cursor===n.source_cursor?r.envelope.directory_signatures:n.directory_signatures;return t&&!hn(i,await Jr(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function Ql(e,t){let n=$.relative(e,t);return n===""||n===".."||n.startsWith(`..${$.sep}`)||$.isAbsolute(n)?null:n}async function Nt(e){await Promise.all([Zr(e),eo(e),to(e),_s(e),ys(e)].map(async t=>{await V.rm(t,{force:!0}),le.delete(t)})),await Yr(e)}async function VE(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await V.stat(e.mutation.itemPath),n=Qr(e.mutation.document.metadata),r={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...r,metadata:n.light,body_length:e.mutation.document.body.length},body:{...r,body:e.mutation.document.body},collections:{...r,collections:n.heavy}}}function WE(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function Es(e){let t=Ql(e.pmRoot,e.itemPath),n=e.previousItemPath?Ql(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Nt(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=ou(e.preferredFormat,e.typeToFolder,e.schema,nu()),o=await bs(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await hs(e.pmRoot);if(s.invalid)return await Nt(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=WE(s.envelope,r,i),c=s.envelope?.context_fingerprint===r&&s.envelope.base_source_cursor===i?s.envelope.source_cursor:i;n!==void 0&&(a[n]={entry:null,body:null,collections:null}),a[t]=await VE({mutation:e});let d=eu();return await gn(_s(e.pmRoot),{version:we,context_fingerprint:r,base_source_cursor:i,source_cursor:d,directory_signatures:await Jr(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Xl({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:d,row:e.document===null?null:{relativePath:t,metadata:Qr(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Yr(e.pmRoot),[]}catch{return await Nt(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function HE(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function Zl(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function KE(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function GE(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=vo(n);if(!o)continue;let i=e.includeCollections?ru(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);iu(s?.itemFormat,o,e.preferredFormat)&&t.set(i.id,{itemFormat:o,candidate:{metadata:i,body:e.includeBody?e.previousBodies[n]?.body:void 0,item_format:o,item_path:$.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function XE(e){return e.forceSourceScan||ci()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!hn(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Zl(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Zl(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&KE(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function oo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=nu(),d=ou(t,n,o,c),l=await hs(e);l.invalid&&await Nt(e);let f=await SE(e,d,i.cacheDiagnostics),p=s?await xE(e,d):null,m=a?await IE(e,d):null;vE(f,p,m,l.envelope);let h=LE(f,d),_=$E(p,d),y=FE(m,d),T=[...new Set(Object.values(n))],L=await Jr(e,T),J=Object.keys(h),q=Math.max(1,Math.floor(i.derivedIndexMinimumItems??tu));if(XE({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:d,existingCache:f,existingBodyCache:p,existingCollectionsCache:m,directorySignatures:L,entryKeys:J,minimumIndexedItems:q,includeBody:s,includeCollections:a,previousBodies:_,previousCollections:y}))return GE({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:h,previousBodies:_,previousCollections:y});let dt=await Promise.all(T.map(mu=>AE(e,mu,r))),wn=ci(),Ee=jE(),ao={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,dispatchReadHooks:wn,previousEntries:h,previousBodies:_,previousCollections:y,state:Ee};await Promise.all(zE(dt,ao));let En=await Jr(e,T),vs=hn(L,En)?En:{},co=Ee.misses.metadata||Object.keys(h).length!==Object.keys(Ee.newEntries).length||!hn(f?.directory_signatures,vs)||f===null?eu():f.source_cursor;return await UE({pmRoot:e,contextFingerprint:d,sourceCursor:co,existingCache:f,previousEntries:h,directorySignatures:vs,state:Ee,minimumIndexedItems:q}),s&&await qE({pmRoot:e,contextFingerprint:d,sourceCursor:co,existingBodyCache:p,previousBodies:_,state:Ee}),a&&await BE({pmRoot:e,contextFingerprint:d,sourceCursor:co,existingCollectionsCache:m,previousCollections:y,state:Ee}),HE(Ee)}async function su(e,t,n,r,o){return(await oo(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}async function au(e,t,n,r,o){return(await oo(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}import We from"node:fs/promises";import Dt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f43e1170-e797-5a0c-b02e-d31e002ab275")}catch{}})();async function YE(e){try{return await We.access(e),!0}catch{return!1}}function io(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function JE(e,t){e&&(e.includes(t)||e.push(t))}function cu(e){return e??fr(Zt())}function QE(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}function so(e){return new w(`Tracker root is not a directory at ${e}.`,b.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",nextSteps:["Pass the tracker directory itself, usually <workspace>/.agents/pm."]})}async function ZE(e){let t=Dt.parse(Dt.resolve(e)).root,n=Dt.dirname(Dt.resolve(e));for(;n!==t;){let r;try{r=await We.stat(n)}catch(o){if(io(o,"ENOTDIR"))throw so(e);if(!io(o,"ENOENT"))throw o;n=Dt.dirname(n);continue}if(!r.isDirectory())throw so(e);break}}async function ks(e){let t;try{t=await We.stat(e)}catch(n){throw io(n,"ENOENT")?(await ZE(e),new w(`Tracker root does not exist at ${e}.`,b.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",nextSteps:["Confirm the tracker root path and retry the SDK read.","Initialize a tracker before enumerating its item metadata."]})):io(n,"ENOTDIR")?so(e):n}if(!t.isDirectory())throw so(e)}async function du(e,t,n="pm-",r,o=se){let i=ns(t,n),s=ts(t),a=i===s?[i]:[i,s],c=Object.entries(o),d=QE(r);for(let l of a)for(let[f]of c)for(let p of d){let m=ko(e,f,l,p,o);if(await YE(m))return{id:l,type:f,itemPath:m,item_format:p}}return null}async function lu(e,t={}){let n=await We.readFile(e.itemPath,"utf8");await ge({path:e.itemPath,scope:"project"});let r=hr(n,{format:e.item_format,schema:t.schema,extensionFieldNames:cu(t.extensionFieldNames),onWarning:o=>JE(t.warnings,o)});return{raw:n,document:r}}async function ek(e,t,n=se,r,o){return await ks(e),(await su(e,t,n,r,o)).map(s=>s.metadata)}async function vO(e,t,n=se,r,o){return await ks(e),(await au(e,t,n,r,o)).map(s=>s.metadata)}async function SO(e,t,n=se,r,o,i={}){return await ks(e),(await oo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function uu(e){return{async get(t){let n=await du(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await lu(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>ek(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function tk(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await We.readdir(Dt.join(e,o));for(let s of i)for(let a of Bn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function nk(e,t,n,r){let o=ns(t,n),i=await tk(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:pt(c,o,s)})).filter(c=>c.distance!==null).sort((c,d)=>c.distance-d.distance).slice(0,3).map(c=>c.id)}async function rk(e,t,n,r){let o=await nk(e,t,n,r),i=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return o.length>0&&i.unshift(`Did you mean one of: ${o.join(", ")}?`),new w(`Item ${t} not found`,b.NOT_FOUND,{nextSteps:i})}function ok(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function fu(e){let t=e.typeToFolder??Xs(e.settings,Zt()).type_to_folder,n=await du(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await rk(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await ze(e.pmRoot,n.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms);try{let o=[],{raw:i,document:s}=await lu(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,d=ed(e.author),l=Wr(e.settings);if(a&&c!==d&&!e.force&&!ok(e.op,e.bypassAssigneeConflict)){if(l.ownership_enforcement==="strict")throw new w(`Item ${n.id} is assigned to ${a}. Use --force to override.`,b.CONFLICT);l.ownership_enforcement==="warn"&&o.push(`ownership_warning:assignee_conflict:${n.id}:${a}`)}return{typeToFolder:t,located:n,originalRaw:i,document:s,warnings:o,releaseLock:r}}catch(o){throw await r(),o}}function ik(e,t,n){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:n,skipItemWrite:!1};let r=e.result;return{effectiveTargetItemPath:typeof r.target_item_path=="string"&&r.target_item_path.trim().length>0?r.target_item_path:t,effectiveSerializedAfter:typeof r.contents=="string"?r.contents:n,skipItemWrite:r.skip_write===!0}}async function sk(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await Q(e.originalItemPath,e.originalRaw),await We.rm(e.effectiveTargetItemPath,{force:!0});return}await Q(e.originalItemPath,e.originalRaw)}}async function xO(e){let t=await fu({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:n,located:r,originalRaw:o,document:i,warnings:s,releaseLock:a}=t;try{let c=me(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=me(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=await e.mutate(d);if(e.skipNoop===!0&&l.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...l.warnings??[]]};d.metadata.updated_at=Ke();let f=me(d,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await ai({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:l.changedFields,sdk:uu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await Qi({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),m="toon",h=jc(f,{format:m,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),_=ko(e.pmRoot,f.metadata.type,r.id,m,n),y=zt(e.pmRoot,r.id),T=await Ie("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:_,history_path:y,item_format:m,before:c,after:f,contents:h}),{effectiveTargetItemPath:L,effectiveSerializedAfter:J,skipItemWrite:q}=ik(T,_,h),dt=await ws(e.pmRoot,e.author),wn=[];try{q||await Q(L,J),!q&&L!==r.itemPath&&await We.rm(r.itemPath);let ao=At({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message});try{await Ct(y,ao)}catch(En){throw await sk({skipItemWrite:q,effectiveTargetItemPath:L,originalItemPath:r.itemPath,originalRaw:o}),En}q||(wn=await Es({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:L,previousItemPath:r.itemPath,document:f}))}finally{await dt()}let Ee=[...await ue({path:L,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:l.changedFields}),...await ue({path:y,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:l.changedFields})];return si({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:lr(c.metadata,l.changedFields),current:lr(f.metadata,l.changedFields),changed_fields:l.changedFields}),{item:f.metadata,body:f.body,changedFields:l.changedFields,warnings:[...s,...l.warnings??[],...p.warnings,...T.warnings,...wn,...Ee]}}finally{await a()}}async function IO(e){let t=await fu({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:n,originalRaw:r,document:o,warnings:i,releaseLock:s}=t;try{let a=cu(void 0),c=me(o,{schema:e.settings.schema,extensionFieldNames:a});await ai({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:uu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let d=await Qi({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),l=Ke(),f=Lt,p=At({nowIso:l,author:e.author,op:"delete",before:c,after:f,message:e.message}),m=zt(e.pmRoot,n.id),h=await Ie("item_store_delete",{op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:m,before:c}),_=n.itemPath,y=!1;if(h.handled&&typeof h.result=="object"&&h.result!==null){let q=h.result;typeof q.item_path=="string"&&q.item_path.trim().length>0&&(_=q.item_path),q.skip_delete===!0&&(y=!0)}if(e.dryRun===!0)return{item:c.metadata,changedFields:["deleted"],targetPath:_,warnings:[...i,...d.warnings,...h.warnings]};let T=await ws(e.pmRoot,e.author),L=[];try{y||await We.rm(_);try{await Ct(m,p)}catch(q){throw y||await Q(_,r),q}y||(L=await Es({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:_,document:null}))}finally{await T()}let J=[...await ue({path:_,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:f,changed_fields:["deleted"]}),...await ue({path:m,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:f,changed_fields:["deleted"]})];return si({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:lr(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...i,...d.warnings,...h.warnings,...L,...J]}}finally{await s()}}export{vn as a,ke as b,Ce as c,Q as d,Pt as e,lk as f,_e as g,Sn as h,lo as i,fk as j,xn as k,In as l,Tn as m,An as n,Cn as o,On as p,_k as q,yu as r,yk as s,se as t,hu as u,ye as v,po as w,bu as x,uo as y,S as z,b as A,gk as B,w as C,Eu as D,wk as E,Ek as F,kk as G,Ts as H,vk as I,Sk as J,xk as K,Is as L,As as M,Ik as N,Dn as O,Su as P,Rk as Q,Ke as R,Oe as S,W as T,$k as U,Fk as V,Ps as W,Ms as X,Ko as Y,Mn as Z,Vk as _,Wk as $,Ku as aa,$s as ba,ft as ca,Ln as da,mt as ea,$n as fa,Kk as ga,Gk as ha,Xk as ia,jn as ja,zn as ka,Yk as la,Jk as ma,Qk as na,Zk as oa,Un as pa,$t as qa,ho as ra,ev as sa,js as ta,tv as ua,nv as va,rv as wa,ov as xa,Bs as ya,Gs as za,mv as Aa,Eo as Ba,uf as Ca,Xs as Da,xf as Ea,If as Fa,pv as Ga,_v as Ha,Bn as Ia,Uf as Ja,kv as Ka,vv as La,Sv as Ma,Js as Na,Ge as Oa,ko as Pa,vo as Qa,zt as Ra,Qs as Sa,Bf as Ta,Vn as Ua,Vf as Va,xv as Wa,Wf as Xa,Hf as Ya,Iv as Za,Tv as _a,Kf as $a,Av as ab,pt as bb,Rm as cb,ga as db,ha as eb,wa as fb,Ea as gb,Io as hb,To as ib,Rv as jb,tm as kb,Zs as lb,Nv as mb,ea as nb,Ao as ob,im as pb,sm as qb,j as rb,Vt as sb,Co as tb,Oo as ub,Ro as vb,No as wb,Do as xb,Po as yb,Mo as zb,zv as Ab,ae as Bb,te as Cb,Xe as Db,vm as Eb,Lo as Fb,xm as Gb,$o as Hb,Fo as Ib,jo as Jb,zo as Kb,Uo as Lb,qo as Mb,Vo as Nb,Wo as Ob,Ho as Pb,Ym as Qb,ip as Rb,ap as Sb,cp as Tb,yp as Ub,zS as Vb,US as Wb,qS as Xb,XS as Yb,JS as Zb,Yp as _b,Jp as $b,ii as ac,e_ as bc,t_ as cc,ix as dc,sx as ec,ax as fc,cx as gc,dx as hc,lx as ic,ux as jc,fx as kc,Zt as lc,mx as mc,px as nc,ic as oc,_x as pc,si as qc,lr as rc,yx as sc,gx as tc,ue as uc,ai as vc,ge as wc,ci as xc,hx as yc,bx as zc,wx as Ac,Ex as Bc,Ie as Cc,ur as Dc,fr as Ec,Ox as Fc,Rx as Gc,K as Hc,mi as Ic,he as Jc,X as Kc,$x as Lc,bc as Mc,Ec as Nc,pi as Oc,kc as Pc,vc as Qc,Fx as Rc,Ic as Sc,tn as Tc,Bx as Uc,Vx as Vc,ht as Wc,Ac as Xc,Hx as Yc,Cc as Zc,U_ as _c,Kx as $c,mr as ad,B_ as bd,Jx as cd,pr as dd,gr as ed,Qy as fd,hr as gd,jc as hd,me as id,zc as jd,rt as kd,qc as ld,bI as md,wI as nd,Wc as od,cg as pd,AI as qd,CI as rd,OI as sd,Jc as td,RI as ud,NI as vd,DI as wd,hg as xd,ed as yd,td as zd,an as Ad,eA as Bd,tA as Cd,Oi as Dd,UI as Ed,nd as Fd,Sr as Gd,id as Hd,Ag as Id,Cg as Jd,HI as Kd,be as Ld,KI as Md,Rg as Nd,Pg as Od,zg as Pd,ad as Qd,ZI as Rd,eT as Sd,Di as Td,Pi as Ud,tT as Vd,Vg as Wd,nT as Xd,rT as Yd,St as Zd,yd as _d,dT as $d,eh as ae,bd as be,lT as ce,wd as de,kd as ee,uT as fe,vd as ge,xd as he,yh as ie,bT as je,hh as ke,Td as le,wT as me,Cd as ne,wh as oe,Sh as pe,Od as qe,Ih as re,Th as se,Ah as te,vT as ue,ST as ve,Ch as we,Ar as xe,xT as ye,Oh as ze,Rd as Ae,Nd as Be,IT as Ce,TT as De,AT as Ee,CT as Fe,OT as Ge,RT as He,Rh as Ie,PT as Je,Fh as Ke,Dd as Le,jh as Me,zh as Ne,MT as Oe,Cr as Pe,Ld as Qe,eb as Re,jd as Se,HT as Te,KT as Ue,gb as Ve,ln as We,Xd as Xe,hA as Ye,At as Ze,Ct as _e,vb as $e,$r as af,Lr as bf,Fr as cf,IA as df,TA as ef,Qd as ff,jr as gf,Ji as hf,AA as if,CA as jf,Qi as kf,Nb as lf,ze as mf,zr as nf,ll as of,iC as pf,sC as qf,ml as rf,yl as sf,ts as tf,ns as uf,mC as vf,gC as wf,Wr as xf,DC as yf,Vl as zf,PC as Af,MC as Bf,UC as Cf,qC as Df,BC as Ef,tu as Ff,hE as Gf,ws as Hf,nO as If,Es as Jf,oo as Kf,du as Lf,lu as Mf,ek as Nf,vO as Of,SO as Pf,uu as Qf,rk as Rf,xO as Sf,IO as Tf};
|
|
164
|
+
//# sourceMappingURL=chunk-GE4KCSZP.js.map
|