@unbrained/pm-cli 2026.8.31 → 2026.9.1

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.
Files changed (103) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/AGENTS.md +15 -13
  3. package/CHANGELOG.md +23 -6
  4. package/README.md +3 -3
  5. package/dist/cli/commands/merge.d.ts +1 -1
  6. package/dist/cli/commands/merge.js +3 -3
  7. package/dist/cli/register-mutation.js +8 -5
  8. package/dist/cli-bundle/bundle-manifest.json +125 -125
  9. package/dist/cli-bundle/chunks/{chunk-SXMHPK4V.js → chunk-2MC2LCXZ.js} +4 -4
  10. package/dist/cli-bundle/chunks/{chunk-52JXYSDW.js → chunk-3WICXLVT.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-OUGDA7NR.js → chunk-6XIIGE7U.js} +2 -2
  12. package/dist/cli-bundle/chunks/chunk-ALKKAUFN.js +35 -0
  13. package/dist/cli-bundle/chunks/{chunk-JIFYOJF7.js → chunk-DTGWEL23.js} +2 -2
  14. package/dist/cli-bundle/chunks/chunk-GOACULJW.js +13 -0
  15. package/dist/cli-bundle/chunks/{chunk-NW6LV3TU.js → chunk-NOPL37X4.js} +64 -64
  16. package/dist/cli-bundle/chunks/{chunk-IEFJ3ZEB.js → chunk-TAG4VC22.js} +4 -4
  17. package/dist/cli-bundle/chunks/{chunk-MWIN6OH2.js → chunk-U45JXJCC.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-5DH5XCJL.js → chunk-X4RCGLTX.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-QZCIBZR3.js → chunk-Y7VOMSZT.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-list-query-7C7DKZ2U.js → register-list-query-XYNX4ASQ.js} +2 -2
  21. package/dist/cli-bundle/chunks/register-mutation-2MVLRS3J.js +20 -0
  22. package/dist/cli-bundle/chunks/{register-operations-IIMA5OKO.js → register-operations-WCIDXBU3.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-setup-52H36QCB.js → register-setup-KVNC5KPL.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/chunk-7VATS5QY.js +16 -0
  25. package/dist/cli-bundle/focused-chunks/{chunk-VJ7EFMFL.js → chunk-FWPLDEXF.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-FOMZ6NG5.js → chunk-MKHG3T76.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/{chunk-UN34D63M.js → chunk-PF3E6Q36.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/{chunk-APN4QN6R.js → chunk-RMRCQPWU.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-BPWJ4QM5.js → chunk-S4U5CN5Q.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/chunk-T2LXXSOD.js +158 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-JCOOAUHK.js → chunk-Y6JJIX6I.js} +30 -30
  32. package/dist/cli-bundle/main.js +2 -2
  33. package/dist/cli-bundle/sdk-contracts.js +1 -1
  34. package/dist/cli-bundle/sdk-core.js +25 -25
  35. package/dist/cli-bundle/sdk-governance.js +1 -1
  36. package/dist/cli-bundle/sdk-graph.js +1 -1
  37. package/dist/cli-bundle/sdk-merge.js +31 -31
  38. package/dist/cli-bundle/sdk-query.js +1 -1
  39. package/dist/cli-bundle/sdk-runtime.js +1 -1
  40. package/dist/cli-bundle/sdk-testing.js +1 -1
  41. package/dist/cli-bundle/sdk.js +10 -10
  42. package/dist/core/history/drift-scan.js +6 -6
  43. package/dist/core/history/history.d.ts +6 -0
  44. package/dist/core/history/history.js +47 -5
  45. package/dist/core/history/replay.d.ts +12 -1
  46. package/dist/core/history/replay.js +60 -39
  47. package/dist/mcp/server.d.ts +2 -2
  48. package/dist/mcp/server.js +78 -15
  49. package/dist/mcp/tool-definitions.js +56 -2
  50. package/dist/sdk/agent-capability-contracts.js +4 -2
  51. package/dist/sdk/history-read.js +14 -6
  52. package/dist/sdk/history-repair.js +17 -10
  53. package/dist/sdk/index.d.ts +1 -0
  54. package/dist/sdk/index.js +3 -2
  55. package/dist/sdk/init-agent-guidance.js +4 -4
  56. package/dist/sdk/lifecycle/update.js +23 -10
  57. package/dist/sdk/mcp/discovery.d.ts +152 -0
  58. package/dist/sdk/mcp/discovery.js +495 -0
  59. package/dist/sdk/merge/index.d.ts +1 -1
  60. package/dist/sdk/merge/index.js +3 -3
  61. package/dist/sdk/merge/receipts.d.ts +27 -1
  62. package/dist/sdk/merge/receipts.js +27 -8
  63. package/dist/sdk/merge/three-way.d.ts +3 -1
  64. package/dist/sdk/merge/three-way.js +9 -7
  65. package/dist/sdk/runtime-extended-actions.js +4 -4
  66. package/docs/AGENT_GUIDE.md +11 -3
  67. package/docs/ARCHITECTURE.md +5 -0
  68. package/docs/CLAUDE_CODE_PLUGIN.md +2 -2
  69. package/docs/CONTEXT_RECOVERY_PRIMITIVES.md +14 -5
  70. package/docs/MCP_2026_07_28.md +9 -5
  71. package/docs/MCP_CAPABILITY_SURFACES.md +7 -1
  72. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +11 -1
  73. package/docs/MERGE_SAFETY.md +30 -2
  74. package/docs/OUTPUT_TOKEN_ACCOUNTING.md +5 -3
  75. package/docs/PROGRESSIVE_TOOL_DISCOVERY.md +42 -0
  76. package/docs/README.md +1 -0
  77. package/docs/agent-task-token-baseline.json +157 -3
  78. package/docs/agent-task-transcripts.json +143 -0
  79. package/docs/performance/cli-transport-overhead.md +8 -6
  80. package/marketplace.json +2 -2
  81. package/package.json +2 -2
  82. package/packages/pm-beads/package.json +1 -1
  83. package/packages/pm-calendar/package.json +1 -1
  84. package/packages/pm-command-kit/package.json +1 -1
  85. package/packages/pm-digital-twin/package.json +1 -1
  86. package/packages/pm-governance-audit/package.json +1 -1
  87. package/packages/pm-guide-shell/package.json +1 -1
  88. package/packages/pm-kanban/package.json +1 -1
  89. package/packages/pm-lifecycle-hooks/package.json +1 -1
  90. package/packages/pm-linked-test-adapters/package.json +1 -1
  91. package/packages/pm-search-advanced/package.json +1 -1
  92. package/packages/pm-templates/package.json +1 -1
  93. package/packages/pm-todos/package.json +1 -1
  94. package/packages/pm-vcs/package.json +1 -1
  95. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  96. package/plugins/pm-claude/README.md +4 -3
  97. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  98. package/sdk/public-surface.json +145 -2
  99. package/dist/cli-bundle/chunks/chunk-2XVV45NJ.js +0 -35
  100. package/dist/cli-bundle/chunks/chunk-3FCSFWZT.js +0 -13
  101. package/dist/cli-bundle/chunks/register-mutation-OI4BJLUX.js +0 -20
  102. package/dist/cli-bundle/focused-chunks/chunk-BMD42PUG.js +0 -158
  103. package/dist/cli-bundle/focused-chunks/chunk-EUTABA4M.js +0 -16
@@ -1,52 +1,52 @@
1
- var eT=Object.defineProperty;var _q=(e,t)=>{for(var n in t)eT(e,n,{get:t[n],enumerable:!0})};import*as ne from"node:fs/promises";import ii from"node:path";import tT 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]="23fc5fcb-5c80-57ab-8d91-8d15ee35ab53")}catch{}})();var nT=[10,25,50,100];async function si(e){await ne.mkdir(e,{recursive:!0})}async function ee(e){try{return await ne.access(e),!0}catch{return!1}}function Bf(e){return de(e)||rn(e,"ENOTDIR")}function de(e){return rn(e,"ENOENT")}async function Y(e){try{return await ne.readFile(e,"utf8")}catch(t){if(Bf(t))return null;throw t}}async function P(e,t){let n=ii.dirname(e);await si(n);let r=ii.join(n,`.${ii.basename(e)}.${process.pid}.${Date.now()}.${tT.randomBytes(4).toString("hex")}.tmp`);await ne.writeFile(r,t,"utf8");try{await ne.rename(r,e)}catch(o){if(process.platform==="win32"&&(rn(o,"EPERM")||rn(o,"EBUSY"))){let i=o;for(let s of nT){await new Promise(a=>setTimeout(a,s));try{await ne.rename(r,e);return}catch(a){if(i=a,!rn(a,"EPERM")&&!rn(a,"EBUSY"))break}}try{await ne.unlink(r)}catch{}throw i}if(rn(o,"EXDEV")){try{await ne.copyFile(r,e)}finally{try{await ne.unlink(r)}catch{}}return}try{await ne.unlink(r)}catch{}throw o}}async function Ct(e,t){let n=ii.dirname(e);await si(n);let r=await ne.open(e,"a");try{await r.writeFile(`${t}
2
- `,"utf8")}finally{await r.close()}}async function $r(e){try{await ne.unlink(e)}catch(t){if(!Bf(t))throw t}}function rn(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]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var Qe=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],ai=2,Ja=Object.freeze({migration:"schema",validation:"schema"}),wq=Object.freeze({version:ai,capabilities:[...Qe],legacy_aliases:{...Ja}}),ci=["off","warn","enforce"],li=["off","warn","enforce"],di=["none","restricted","strict"],Hf=["block","warn"],ui=["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","services.assuranceprovider"],Gn=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function fi(){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]="27c5eac3-4580-5f6f-8ae9-b04d0281766d")}catch{}})();var Wf=["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"],rT=["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",...Wf,"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"],Me=rT;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var Za=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"]}]),ec=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),pi=".agents/pm",mi="settings.json",oT="Closed at creation via pm create",iT=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],sT=["decisions","events","reminders","milestones","meetings","plans"],kq=[...iT,...sT],_e={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},tc={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}},aT=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],Qa={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 Kf(e){return e?[...e]:void 0}var x={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"},ux:{deprecation_hints:!0},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:[...aT],lifecycle_closure_like_blocked_reason_patterns:[...Qa.blocked_reason],lifecycle_closure_like_resolution_patterns:[...Qa.resolution],lifecycle_closure_like_actual_result_patterns:[...Qa.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...tc.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!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:Za.map(e=>({...e,aliases:Kf(e.aliases),roles:Kf(e.roles)})),fields:[],workflow:{...ec},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:fi()},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:""}}},Bn={metadata:{},body:""},g={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},cT=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 _i(e){let t=(e??"").trim().toLowerCase();if(t.length===0)return"unknown";let n=cT[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]="922e2e27-1499-5466-98e4-322d0d742e40")}catch{}})();var h=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 F(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function lT(e){return F(e)??void 0}function jr(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 Hn(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function z(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function gi(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 Xf(e){let t=gi(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function Cq(e,t,n){let r=gi(e);return r===null||r<t||r>n?null:r}function dT(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function on(e){return typeof e!="object"||e===null?null:e}function Yf(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Jf(e){let t=Yf(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=Yf(t.default);return typeof n?.activate=="function"?n:null}function uT(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 Wn(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import fT from"node:crypto";import{AsyncLocalStorage as pT}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]="aacc48ae-e9b2-5c8e-945f-89d05aff48e8")}catch{}})();var nc=new pT,Qf=1024;function mT(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function _T(e){let n={...mT(e),clockReads:0,tokenReads:0};return r=>nc.run(n,r)}async function Dq(e,t){return _T(e)(t)}function Zf(){let e=nc.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 ep(e){let t=nc.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Qf)throw new Error(`Reproducible token length must be an integer between 0 and ${Qf}`);let n="";for(;n.length<e;){let r=fT.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]="7887e752-b1b8-5c5e-9dd8-93b41cb757af")}catch{}})();var gT=/^([+-]?)(\d+)([hdwm])$/i,yT=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,hT=/^(\d{4})(\d{2})(\d{2})$/,bT=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,wT=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,ET=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,vT=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function oe(){return Zf()??new Date().toISOString()}function ft(e){return Number.isFinite(Date.parse(e))}function np(e){let t=vT.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,l]=t,[d,u,f,p,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=ic(d,u-1)&&p<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var TT=1e4,yi=new Map;function tp(e){let t=yi.get(e);if(t!==void 0)return t;let n=Date.parse(e);return yi.size>=TT&&Wn(yi),yi.set(e,n),n}function ue(e,t){let n=tp(e),r=tp(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function jq(e,t){return!(t.deadlineBefore&&(!e.deadline||ue(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||ue(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&ue(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&ue(e.updated_at,t.updatedBefore)>0||t.createdAfter&&ue(e.created_at,t.createdAfter)<0||t.createdBefore&&ue(e.created_at,t.createdBefore)>0)}function rc(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function oc(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 kT(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function AT(e){let t=[],n=l=>kT(t,e,l),r=hT.exec(e);if(r){let[,l,d,u]=r;n(`${l}-${d}-${u}`)}let o=bT.exec(e);if(o){let[,l,d,u,f,p,_,y,b]=o,E=_?`:${_}`:"";n(`${l}-${d}-${u}T${f}:${p}${E}${rc(y)}${oc(b)}`)}let i=wT.exec(e);if(i){let[,l,d,u,f,p,_]=i,y=f?`:${f}`:"";n(`${l}T${d}:${u}${y}${rc(p)}${oc(_)}`)}let s=ET.exec(e);if(s){let[,l,d,u,f,p,_]=s,y=f?`:${f}`:"";n(`${l}T${d}:${u}${y}${rc(p)}${oc(_)}`)}let a=10,c=e.slice(0,a);if(xT(c)){let l=a;for(;l<e.length&&CT(e[l]);)l+=1;l<e.length&&n(`${c}T${e.slice(l)}`)}return t}function ST(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of AT(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function xT(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 CT(e){return e?e===" "||e===" "||e===`
3
- `||e==="\r"||e==="\f"||e==="\v":!1}function ic(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var OT=["January","February","March","April","May","June","July","August","September","October","November","December"],IT=/^(\d{4})-(\d{2})-(\d{2})/,RT=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function NT(e,t,n){let r=IT.exec(t)??RT.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 h(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,g.USAGE);let c=ic(o,i-1);if(s<1||s>c)throw new h(`Invalid ${a} value "${e}". ${OT[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,g.USAGE)}function DT(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,ic(i,s));return n.setUTCFullYear(i,s,a),n}function PT(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=gT.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 DT(t,a).toISOString();let l=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*l).toISOString()}NT(e,r,n);let i=ST(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=yT.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 h(`Invalid ${s} value "${e}". ${a}`,g.USAGE)}return new Date(i).toISOString()}import{mkdir as LT,readFile as MT}from"node:fs/promises";import rp 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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();function FT(e){let t=e.trim();if(!t)throw new h("--rollback requires a non-empty checkpoint ID",g.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new h("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",g.USAGE);return t}function $T(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function op(e,t){return rp.join(e,"checkpoints",t)}function ip(e,t,n){return rp.join(op(e,t),`${n}.json`)}async function jT(e,t,n,r){let o=op(e,t);await LT(o,{recursive:!0});let i=ip(e,t,n);return await P(i,`${JSON.stringify(r,null,2)}
4
- `),i}function UT(e,t){if(!Array.isArray(e.items))throw new h(`Checkpoint ${t} is missing items`,g.GENERIC_FAILURE);return e.items.map(n=>{if(!n||typeof n!="object")throw new h(`Checkpoint ${t} contains an invalid item entry`,g.GENERIC_FAILURE);let r=n;if(typeof r.id!="string"||r.id.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without ID`,g.GENERIC_FAILURE);if(typeof r.target_updated_at!="string"||r.target_updated_at.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without target_updated_at`,g.GENERIC_FAILURE);return{id:r.id.trim(),target_updated_at:r.target_updated_at.trim()}})}async function zT(e,t,n,r){let o=FT(n),i=ip(e,t,o);if(!await ee(i))throw new h(`Checkpoint ${o} not found`,g.NOT_FOUND);let s=await MT(i,"utf8"),a;try{a=JSON.parse(s)}catch(d){throw new h(`Checkpoint ${o} contains invalid JSON: ${z(d)}`,g.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new h(`Checkpoint ${o} is invalid`,g.GENERIC_FAILURE);let c=a;if(c.schema_version!==r)throw new h(`Checkpoint ${o} has unsupported schema version`,g.GENERIC_FAILURE);let l=UT(c,o);return{record:c,items:l,path:i,id:typeof c.id=="string"?c.id:o,created_at:typeof c.created_at=="string"?c.created_at:oe(),author:typeof c.author=="string"?c.author:"unknown"}}async function qT(e,t){let n=[],r=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);n.push({id:o.id,status:"restored",changed_fields:i.changed_fields,warnings:i.warnings}),r.push(o.id)}catch(i){n.push({id:o.id,status:"failed",error:z(i)})}return{rows:n,restored_ids:r,failed_count:n.filter(o=>o.status==="failed").length}}(function(){try{var e=typeof window<"u"?window:typeof 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 VT=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function sc(e){return typeof e!="string"?null:VT[e.trim().toLowerCase()]??null}function ac(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 sp(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof 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 Be(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 l=s[0];for(let d=1;d<=t.length;d+=1){let u=e[c-1]===t[d-1]?0:1,f=i[d-1]+u,p=s[d-1]+1,_=i[d]+1,y=Math.min(f,p,_);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(y=Math.min(y,o[d-2]+1)),s[d]=y,y<l&&(l=y)}if(l>n)return null;for(let d=0;d<r;d+=1)o[d]=i[d],i[d]=s[d]}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]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}catch{}})();var e2=[{code:"unknown_lifecycle_action"}];function GT(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Math.floor(n.length/3);return t.map(o=>({candidate:o,distance:Be(n,o.toLowerCase(),r)??Number.POSITIVE_INFINITY})).filter(({distance:o})=>Number.isFinite(o)).sort((o,i)=>o.distance!==i.distance?o.distance-i.distance:o.candidate.localeCompare(i.candidate))[0]?.candidate}function ap(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function BT(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),n=e.token.trim(),r=n.length===0?"<empty>":n,o=[...new Set(e.allowed.map(f=>f.trim()))].filter(Boolean).sort((f,p)=>f.localeCompare(p));if(t.length===0||r.length===0||o.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let i=t.split(" "),s=e.trailing_args??[],a=e.display_name??`pm ${t}`,c=e.token_kind??"subcommand",l=e.retry_command?void 0:GT(r,o),d=ap([...i,r,...s]),u=e.retry_command??(l?ap([...i,l,...s]):void 0);return new h(`Unknown ${a} ${c} "${r}". Allowed: ${o.join(", ")}${e.message_suffix??""}`,e.exit_code??g.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:o,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}(function(){try{var e=typeof window<"u"?window:typeof 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 HT="__pm_suppress_host_output",cc="@unbrained/pm-cli:suppress-host-output:v1";function cp(e){return e===void 0?{__pm_suppress_host_output:cc}:{__pm_suppress_host_output:cc,result:e}}function hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[HT]===cc}import Kn from"node:fs";import pt from"node:path";import{fileURLToPath as WT}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 KT="@unbrained/pm-cli";function YT(e){try{return JSON.parse(Kn.readFileSync(e,"utf8")).name===KT}catch{return!1}}function XT(e){let t=Kn.existsSync(e)&&Kn.statSync(e).isDirectory()?pt.resolve(e):pt.dirname(pt.resolve(e));for(;;){let n=pt.join(t,"package.json");if(Kn.existsSync(n)&&YT(n))return t;let r=pt.dirname(t);if(r===t)return;t=r}}function mt(e,t=[]){let n=WT(e),r=XT(n);return r||pt.resolve(pt.dirname(n),...t)}function lc(e,t=[]){try{let n=pt.join(mt(e,t),"package.json");if(!Kn.existsSync(n))return;let r=JSON.parse(Kn.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function JT(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?pt.resolve(o.trim()):n?mt(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]="64223a83-1287-57ac-915d-dbd5e375a6eb")}catch{}})();var Yn=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],lp=Yn,Xn=["draft","open","in_progress","blocked","closed","canceled"],bi=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Jn=["string","number","boolean","string_array","array","object"],wi=["create","update","update_many","list","search","calendar","context"],Ei=["allow","warn","reject"],a2=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],c2=["project","global"],l2=["low","medium","high","critical"],vi=["low","medium","high","critical"],Ti=["low","medium","high"];var dp=["minimal","default","strict","custom"],d2=["none","warn","strict"],u2=["progressive","strict"],f2=["off","warn","strict"],p2=["off","warn","strict"];var ki=["daily","weekly","monthly","yearly"],Ur=["mon","tue","wed","thu","fri","sat","sun"];function dc(e){return Ur.indexOf(e)}var up=["draft","research","review","approved","executing","paused","completed","superseded"],Ai=["pending","in_progress","completed","blocked","skipped","superseded"],fp=["codex","claude-code","cursor","generic"],pp=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],m2=["brief","standard","deep","full"],_2=["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 nk 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 Ot(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function QT(e){let t=e.key.trim();if(t.length===0)return null;let n=Ot(e.aliases),r=e.description?.trim();return{key:t,values:Ot(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 ZT=e=>e,_p=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function ek(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 tk(e,t){let n=new Map;for(let r of e??[]){let o=ek(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 mp(e,t){return t?Ot(e):void 0}function uc(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Si(e,t={}){let n=t.resolvePolicyCommand??ZT,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=Ot(e.aliases),l=(e.options??[]).map(u=>QT(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=tk(e.command_option_policies,n);return{name:r,description:uc(e.description),default_status:uc(e.default_status),folder:uc(e.folder),aliases:c.length>0?c:void 0,required_create_fields:mp(e.required_create_fields,o),required_create_repeatables:mp(e.required_create_repeatables,i),options:s?l:void 0,command_option_policies:a?d: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 rk=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],ok=["dep","comment","note","learning","file","test","doc"],pc=["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"],ik=["title","description","type","status","priority","tags","body",...pc,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],sk=["title","description","body","status","closeReason","priority","type","tags",...pc,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],yp={"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"},ak={...yp},ck={...yp},hp=[["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"]],bp=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function wp(e){return Object.fromEntries(e)}var lk=wp([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...hp,["author","--author"],["message","--message"],["dep","--dep"],...bp]),dk=wp([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...hp,...bp,["author","--author"],["message","--message"],["force","--force"]]);function uk(e){return e.trim().replace(/^--+/,"").toLowerCase()}function fk(e){return e==="create"?ik:sk}function pk(e){return e==="create"?ak:ck}function mc(e,t){let n=uk(t);if(n.length===0)return;let r=pk(e)[n];return r||fk(e).find(o=>o.toLowerCase()===n)}function mk(e,t){return(e==="create"?lk:dk)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function qr(e){let t=_k(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function xi(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=nk.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 _k(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 gk(e){return Si(e,{resolvePolicyCommand:_p})}function zr(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function yk(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:zr(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:zr(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function hk(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 bk(e){if(Array.isArray(e.options))return e.options.map(t=>yk(t)).filter(t=>t!==null)}function wk(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>hk(t)).filter(t=>t!==null)}function Ek(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:zr(t,"aliases"),required_create_fields:zr(t,"required_create_fields"),required_create_repeatables:zr(t,"required_create_repeatables"),options:bk(t),command_option_policies:wk(t)}}function vk(e,t){return e.required_create_fields?Ot(e.required_create_fields):t?.required_create_fields??[]}function Tk(e,t){return e.required_create_repeatables?Ot(e.required_create_repeatables):t?.required_create_repeatables??[]}function kk(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Ak(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Sk(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=xi(e.folder??t?.folder??qr(n)),s={name:n,folder:i,aliases:Ot([...t?.aliases??[],...e.aliases??[]]),required_create_fields:vk(e,t),required_create_repeatables:Tk(e,t),options:kk(e,t),command_option_policies:Ak(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function gp(e,t){for(let n of e){let r=gk(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Sk(r,i))}}function xk(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=Ek(o);i&&t.push(i)}}return t}function Vr(e,t=null){let n=new Map;for(let c of lp)n.set(c.toLowerCase(),{name:c,folder:_e[c],aliases:[],required_create_fields:[...rk],required_create_repeatables:[...ok],options:[],command_option_policies:[]});gp(e.item_types?.definitions??[],n),gp(xk(t),n);let r=[...n.values()].sort((c,l)=>c.name.localeCompare(l.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 l of c.aliases)i[l.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,l)=>c.localeCompare(l));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Ep(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function vp(e,t){let n=Ep(e,t);if(n)return t.by_type[n]}function Ck(e,t,n,r){for(let o of r){let i=mc(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 fc(e,t,n){if(n){e.add(t);return}e.delete(t)}function Ok(e,t,n,r){let o=mc(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&&fc(e.required,o,r.required),r.visible!==void 0&&fc(e.hidden,o,!r.visible),r.enabled!==void 0&&fc(e.disabled,o,!r.enabled)}function Ik(e,t,n){for(let r of t.command_option_policies)r.command===n&&Ok(e,t,n,r)}function Rk(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 Nk(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Ck(a,e,t,n),Ik(a,e,t),Rk(a,e,t),{required:[...o],hidden:[...i].sort((c,l)=>c.localeCompare(l)),disabled:[...s].sort((c,l)=>c.localeCompare(l)),errors:r}}function Dk(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 Pk(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 Lk(e,t,n){let r=vp(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Dk(r),s={};for(let[c,l]of Object.entries(t??{})){let d=c.trim(),u=l.trim();if(d.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${d}" must not be empty`);continue}let f=i.get(d.toLowerCase());if(!f){let _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${d}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let p=Pk(f,u,o);p!==void 0&&(s[f.key]=p)}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,l)=>c.localeCompare(l));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as Mk,readdirSync as Fk,statSync as $k}from"node:fs";import jk from"node:os";import D 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 Uk={json_markdown:".md",toon:".toon"},zk={".md":"json_markdown",".toon":"toon"},qk=new Set([".git","coverage","dist","node_modules"]),Ci=[".md",".toon"];function Gr(e){try{return $k(e),!0}catch{return!1}}function Tp(e){try{let t=JSON.parse(Mk(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Vk(e){let t=D.resolve(e);for(;;){let n=D.join(t,pi),r=D.join(n,mi);if(Gr(r))return n;let o=D.join(t,mi);if(Gr(o)&&Tp(o))return t;let i=D.dirname(t);if(i===t)return;t=i}}function kp(e){return Vk(e)??D.resolve(e,pi)}function I2(e,t){let n=t?D.resolve(t):void 0;try{return Fk(D.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!qk.has(r.name)).map(r=>D.join(D.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Gr(ge(r))).filter(r=>Tp(ge(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function Br(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=D.resolve(e,r);if(!Gr(ge(o))){let i=D.join(o,pi);if(Gr(ge(i)))return i}return o}return kp(e)}function Gk(e){let t=D.resolve(e),n=D.dirname(t);return D.basename(t)==="pm"&&D.basename(n)===".agents"?D.dirname(n):t}function It(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:D.join(jk.homedir(),".pm-cli");return D.resolve(e,n)}function ge(e){return D.join(e,mi)}function Bk(e,t,n=_e){let r=n[t]??qr(t);return D.join(e,r)}function Qn(e,t,n,r="toon",o=_e){return D.join(Bk(e,t,o),`${n}${Uk[r]}`)}function Hr(e){let t=e.replaceAll("\\","/"),n=D.posix.extname(t).toLowerCase();return zk[n]??null}function Zn(e,t){return D.join(e,"history",`${t}.jsonl`)}function Ap(e,t){return D.join(e,"locks",`${t}.lock`)}function _c(e){return D.join(e,"runtime")}function Oi(e){return D.join(_c(e),"test-runs")}function Hk(e){return D.join(Oi(e),"runs")}function R2(e,t){return D.join(Hk(e),`${t}.json`)}function Wk(e){return D.join(Oi(e),"stdout")}function Kk(e){return D.join(Oi(e),"stderr")}function N2(e,t){return D.join(Wk(e),`${t}.log`)}function D2(e,t){return D.join(Kk(e),`${t}.log`)}function Yk(e){return D.join(Oi(e),"results")}function P2(e,t){return D.join(Yk(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]="aa7d04c7-b057-569c-816a-f53322c74261")}catch{}})();var gc=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7d44fba-603b-5ef2-8490-51112b929433")}catch{}})();function Ni(e){return e.trim().toLowerCase().replaceAll("-","_")}function Xk(e){if(e===void 0)return;let t=Ni(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function hc(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)hc(n,t);return Object.freeze(e)}for(let n of Object.values(e))hc(n,t);return Object.freeze(e)}function Jk(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 Qk(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function Zk(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 eA(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=Ni(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 tA(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function nA(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}`)}function rA(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var bc=class{#e=new Map;#n=new Map;constructor(t=gc){for(let n of t)this.register(n)}register(t){let n=eA(t);if(tA(t,n),nA(t,n),Jk(t,n),Qk(t,n),Zk(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Xk(t.inverse),o=[...new Set((t.aliases??[]).map(Ni))].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,traversal:rA(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?hc(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=Ni(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 wc(){return new bc}var sn=wc();function $2(e){return sn.require(e).kind}function j2(e){return sn.resolve(e)?.kind}function U2(e,t=sn){return t.resolve(e)?.ordering===!0}function oA(e,t,n,r=sn){let o=Wr(e),i=Wr(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 Ii(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function iA(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=oA(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 Ri(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Wr(e){return typeof e=="string"?e.trim():""}function yc(e,t){let n=Wr(e);return n&&t.has(n)?n:void 0}function sA(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Sp=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=sn){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}=iA(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(Ii));for(let i of this.#r)Ri(this.#s,i.source,i),Ri(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(Ri(this.#s,i.target,i),Ri(this.#a,i.source,i))}static fromItems(t,n=sn){let r=new Set(t.map(i=>Wr(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Wr(i.id);if(!s)continue;let a=yc(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=yc(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let l of i.dependencies??[]){let d=yc(l.id,r);d&&n.resolve(l.kind)&&o.push({source:s,target:d,kind:l.kind,createdAt:l.created_at,author:l.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],l=a===void 0?c:c===void 0||Ii(a,c)<=0?a:c;o.at(-1)!==l&&o.push(l),a===l&&(i+=1),c===l&&(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)||Ii(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(p=>this.#e.require(p).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],l=[{id:t,depth:0}],d=0,u=0,f=!1;e:for(let p=0;p<l.length;p+=1){n.signal?.throwIfAborted();let _=l[p];d+=1;let y=this.#t(_.id,o,r);if(u+=y.length,_.depth>=s){y.some(b=>!a.has(b.id))&&(f=!0);continue}for(let b of y)if(!a.has(b.id)){if(c.length>=i){f=!0;break e}a.add(b.id),c.push(b.id),l.push({id:b.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:d,inspectedEdges:u,truncated:f,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(p=>this.#e.require(p).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,l=new Set([t]),d=0,u=0,f=!1;for(let p=0;p<a.length;p+=1){r.signal?.throwIfAborted();let _=a[p];d+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(b=>!l.has(b.id))&&(f=!0);continue}for(let b of y)if(!l.has(b.id)){if(c.set(b.id,_.id),b.id===n)return{value:sA(t,n,c),meta:{visitedNodes:d,inspectedEdges:u,truncated:!1}};l.add(b.id),a.push({id:b.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:d,inspectedEdges:u,truncated:f}}}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 l of this.#s.get(c)??[])i.has(l.source)&&i.has(l.target)&&this.#c(l,s)&&a.add(l);return{value:{nodes:o,edges:[...a].sort(Ii)},meta:r.meta}}};function z2(e,t,n=sn){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 Kr(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Rt(e){return Qe.includes(e)}function xp(e){let t=e.trim().toLowerCase();return Rt(t)?t:null}function Cp(e){return e.filter(t=>!Rt(t))}function Ec(e){let t=e.trim().toLowerCase();return t.length===0?null:Ja[t]??null}function Op(e){let t=Kr([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Ec(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:Kr(n),legacy_aliases:o}}function aA(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Ec(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 Qe){let a=Be(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function Ip(e,t,n){let r=Qe.join(","),o=aA(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function Rp(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function cA(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(p=>p.trim()).filter(p=>p.length>0),l=Ec(o),u=(s==="none"?void 0:s)??l??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ai,suggested_capability:u,suggestion_source:u?l===u?"legacy_alias":"nearest_match":void 0,legacy_alias_target:l??void 0}}function lA(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...Qe],a=[];for(let c of o.split(",")){let[l,d]=c.split(">"),u=l?.trim(),f=d?.trim().toLowerCase();!u||!f||!Rt(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ai,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48fff41d-2667-50a1-bfbb-40908804babd")}catch{}})();function Yr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function vc(){return{overrides:[],handlers:[]}}function Tc(){return{overrides:[]}}function kc(){return{overrides:[]}}function Ac(){return{overrides:[]}}function Sc(){return{overrides:[]}}function Di(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function X(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function dA(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function Ce(e){return e?$(e):{}}function Oe(e){return e?$(e):dA()}function $(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]="f7c79f37-1cae-59c9-b500-eb87d0089f94")}catch{}})();var uA=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),fA=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function pA(e,t){for(let n of fA){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=>uA.has(n)?X(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function mA(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=>X(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function _A(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.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>X(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function xc(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(!pA(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 s=mA(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=_A(i);if(s===null)return null;n.preflight_ownership=s}return n}function X2(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49cea84c-1d1b-523b-8c98-7ac16c69ae82")}catch{}})();var gA=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function yA(e){return{unknownKeys:Object.keys(e).filter(t=>!gA.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function hA(e){let t=yA(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function Np(e,t,n){return hA(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import bA 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 wA(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 EA(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Pi(o))}return n}function Pi(e){let t=wA(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Pi(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Pi(r)}return EA(e)}function K(e){return JSON.stringify(Pi(e))}function Dp(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 vA(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function TA(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function kA(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(!Dp(o,n,r,fe))return!1;return!0}function AA(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(!Dp([o,i],n,r,([a,c],[l,d])=>fe(a,l)&&fe(c,d)))return!1;return!0}function SA(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)=>fe(n,t[r]))}function xA(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]||!fe(e[i],t[i]))return!1}return!0}var CA=[vA,TA,kA,AA,SA];function fe(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 CA){let r=n(e,t);if(r!==void 0)return r}return xA(e,t)}function an(e){return bA.createHash("sha256").update(e,"utf8").digest("hex")}function I(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]="d1dd5d4f-5f08-5e52-b109-d066f92ae3b3")}catch{}})();var OA=5e3;async function Xr(e,t,n){let r=[];for(let o of e)try{await o.run($(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Pp(e,t){return Xr(e.beforeCommand,"beforeCommand",t)}function IA(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 h(`Extension mutation guard ${t.name} returned an invalid decision.`,g.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 h(`Extension mutation guard ${t.name} returned an invalid denial.`,g.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 h(s||`Extension mutation guard ${t.name} denied ${n}.`,g.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Cc(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:$(t.before),after:t.after===null?null:$(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 h(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},OA),o.unref?.()})])}catch(i){throw i instanceof h?i:new h(`Extension mutation guard ${n.name} failed before ${t.operation}.`,g.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)}IA(r,n,t.operation)}}async function Lp(e,t){return Xr(e.afterCommand,"afterCommand",t)}async function Oc(e,t){return Xr(e.onWrite,"onWrite",t)}async function Ic(e,t){return Xr(e.onRead,"onRead",t)}async function Rc(e,t){return Xr(e.onIndex,"onIndex",t)}function RA(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 Li(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 NA(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 Nc(e,t){let n=X(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:$(t.args),options:$(t.options),global:$(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",NA(o)],["errorCode",Li(o,"code")],["remediation",Li(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:RA(o),...Object.fromEntries([["errorCode",Li(o,"code")],["remediation",Li(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function Dc(e,t){let n=X(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:$(t.args),options:Ce(t.options),global:Oe(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:$(t.args),options:Ce(t.options),global:Oe(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:$(t.args),options:Ce(t.options),global:Oe(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)?$(o.args):$(t.args),s=o.options?Ce(o.options):Ce(t.options),a=o.global?Oe(o.global):Oe(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:$(t.args),options:Ce(t.options),global:Oe(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 Pc(e,t){let n={command:X(t.command),args:$(t.args),options:Ce(t.options),global:Oe(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},r=$(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:$(n.args),options:Ce(n.options),global:Oe(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:$(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?$(i.args):n.args,options:i.options?Ce(i.options):n.options,global:i.global?Oe(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Mp(e){return{handled:!1,result:e.payload,warnings:[]}}function Fp(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function $p(e){return{service:e.service,command:e.command?X(e.command):void 0,args:e.args?$(e.args):void 0,options:e.options?Ce(e.options):void 0,global:e.global?Oe(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:$(e.payload)}}function DA(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 jp(e,t){return DA(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 Up(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&fe(e,n.payload)}function zp(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function Lc(e,t){let n=Fp(e,t.service);if(n.length===0)return Mp(t);let r=[];for(let o of n)try{let i=$p(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(Up(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=zp(o,jp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Mc(e,t){let n=Fp(e,t.service);if(n.length===0)return Mp(t);let r=[];for(let o of n)try{let i=$p(t),s=await Promise.resolve(o.run(i));if(Up(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=zp(o,jp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function Fc(e,t){let n=X(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=Ce(t.options),i=Oe(t.global),s=r.run({command:n,args:$(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:$(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 PA(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($(n))}catch{return!1}}function $c(e,t){let n=typeof t.command=="string"?X(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&PA(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?$(t.args):[],i=Ce(t.options),s=Oe(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:$(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 fn from"node:fs/promises";import un from"node:path";import{pathToFileURL as oS}from"node:url";import qp 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 jc(e,t){let n=qp.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!qp.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 Mi=Jn;function Fi(e){let t=e.trim().toLowerCase();return Mi.includes(t)?t:null}function Vp(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 Mi)if(Be(t,r,n)!==null)return r;return null}import LA from"node:fs/promises";import Jr 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 Gp(e,t){let n=Jr.dirname(t.manifest_path),r=Jr.relative(n,t.entry_path);if(r.startsWith("..")||Jr.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Jr.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await LA.cp(n,o,{recursive:!0,force:!0}),Jr.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 Bp(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]="065f61c6-2123-5a6d-984a-569bb14d6911")}catch{}})();function Hp(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return X(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function Wp(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a30142c8-b04d-5878-8497-c902ff299e94")}catch{}})();function Kp(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 pe(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function te(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 Yp(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 cn(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 Qr(e,t){if(cn(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]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var Uc=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="764d9a7d-90a2-578f-ab5d-bd0c039596df")}catch{}})();var MA=new Set(Uc);function FA(e){if(e!==void 0&&!MA.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${Uc.join(", ")}`)}function Xp(e){te("registerCommand definition.action",e.action),te("registerCommand definition.family",e.family),te("registerCommand definition.description",e.description),te("registerCommand definition.intent",e.intent),te("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");FA(e.family)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="057f439e-ac5c-5715-9fd0-4410e003d481")}catch{}})();function $A(e){let t=se("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return te("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function Jp(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=$A(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function zc(e,t,n){return{registration:t,action:n,command:e.command,args:$(e.args),options:$(e.options),global:$(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ee7e43-8811-57ed-8bfe-0345ee5d3308")}catch{}})();var qc=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),Vc=new Set(qc.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 jA=/^--[a-z0-9][a-z0-9_-]*(?:[ =](?:<[^<>]+>|\[[^[\]]+\]))?$/;function UA(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return Vc.has(n)?"host_owned_flag_collision":jA.test(t)?null:"malformed_long_flag"}function Qp(e,t){let n=[e,t].find(i=>typeof i=="string"&&Vc.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=UA(r);return o===null?null:{token:r,failure:o}}function Zp(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 em(e){return typeof e=="string"?e:String(e)}function Zr(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 Gc(e,t){let n=Zr(e),r=Zr(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 tm(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=em(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!Zr(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=Gc(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 nm(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=em(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())||!Zr(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=Gc(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 Fe(e){return typeof e!="string"?"":e.trim().toLowerCase()}function j(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function zA(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 er(e){return new Set((e??[]).map(t=>zA(t)).filter(t=>t.length>0))}function rm(e){let t=Fe(e);return ci.includes(t)?t:"off"}function om(e){let t=Fe(e);return li.includes(t)?t:"off"}function eo(e){let t=Fe(e);return di.includes(t)?t:"none"}function Bc(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Hf.includes(t)?t:void 0}function im(e){if(typeof e=="string"){let t=Bc(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Bc(e.global)??"block",project:Bc(e.project)??"block"}:{global:"block",project:"block"}}function qA(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function G(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function VA(e){let t=Fe(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?eo(e.sandbox_profile):void 0,allowedCapabilities:j(e.allowed_capabilities),blockedCapabilities:j(e.blocked_capabilities),allowedSurfaces:er(e.allowed_surfaces),blockedSurfaces:er(e.blocked_surfaces),allowedCommands:j(e.allowed_commands),blockedCommands:j(e.blocked_commands),allowedActions:j(e.allowed_actions),blockedActions:j(e.blocked_actions),allowedServices:j(e.allowed_services),blockedServices:j(e.blocked_services)}}}function sm(e){let t=new Map;for(let n of e??[]){let r=VA(n);r&&t.set(r.name,r.normalized)}return t}function GA(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of G([...e.allowedCapabilities,...e.blockedCapabilities]))Rt(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of G([...o.allowedCapabilities,...o.blockedCapabilities]))Rt(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(ui);for(let o of G([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of G([...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 am(e){let t=e.extensions?.policy??{},n=j(t.allowed_capabilities),r=j(t.blocked_capabilities),o=er(t.allowed_surfaces),i=er(t.blocked_surfaces),s=sm(t.extension_overrides);return{mode:rm(t.mode),trustMode:om(t.trust_mode),pmMaxVersionExceededMode:im(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:j(t.trusted_extensions),defaultSandboxProfile:eo(t.default_sandbox_profile),allowedExtensions:j(t.allowed_extensions),blockedExtensions:j(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:j(t.allowed_commands),blockedCommands:j(t.blocked_commands),allowedActions:j(t.allowed_actions),blockedActions:j(t.blocked_actions),allowedServices:j(t.allowed_services),blockedServices:j(t.blocked_services),overridesByName:s,warnings:GA({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function cm(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:G(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:G(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:G(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:G(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:G(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:G(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:G(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:G(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:G(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:G(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:qA(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:G(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:G(e.allowedExtensions),blocked_extensions:G(e.blockedExtensions),allowed_capabilities:G(e.allowedCapabilities),blocked_capabilities:G(e.blockedCapabilities),allowed_surfaces:G(e.allowedSurfaces),blocked_surfaces:G(e.blockedSurfaces),allowed_commands:G(e.allowedCommands),blocked_commands:G(e.blockedCommands),allowed_actions:G(e.allowedActions),blocked_actions:G(e.blockedActions),allowed_services:G(e.allowedServices),blocked_services:G(e.blockedServices),extension_overrides:t}}function lm(e){let t=sm(e.extension_overrides);return{mode:rm(e.mode),trustMode:om(e.trust_mode),pmMaxVersionExceededMode:im(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:j(e.trusted_extensions),defaultSandboxProfile:eo(e.default_sandbox_profile),allowedExtensions:j(e.allowed_extensions),blockedExtensions:j(e.blocked_extensions),allowedCapabilities:j(e.allowed_capabilities),blockedCapabilities:j(e.blocked_capabilities),allowedSurfaces:er(e.allowed_surfaces),blockedSurfaces:er(e.blocked_surfaces),allowedCommands:j(e.allowed_commands),blockedCommands:j(e.blocked_commands),allowedActions:j(e.allowed_actions),blockedActions:j(e.blocked_actions),allowedServices:j(e.allowed_services),blockedServices:j(e.blocked_services),overridesByName:t,warnings:[]}}function Nt(e,t){return e.overridesByName.get(Fe(t))??null}function tr(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function dm(e,t,n){let r=n.trim().toLowerCase(),o=Nt(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return tr(i,s,r,"capability_not_allowlisted","capability_blocked")}function BA(e,t,n){let r=Nt(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return tr(o,i,n,"surface_not_allowlisted","surface_blocked")}function HA(e,t,n){let r=X(n);if(r.length===0)return null;let o=Nt(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return tr(i,s,r,"command_not_allowlisted","command_blocked")}function WA(e,t,n){let r=Fe(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Nt(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return tr(i,s,r,"action_not_allowlisted","action_blocked")}function KA(e,t,n){let r=Fe(n);if(r.length===0)return null;let o=Nt(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return tr(i,s,r,"service_not_allowlisted","service_blocked")}function YA(e,t){let n=Fe(t.name);return Nt(e,t.name)?.disabled===!0?"extension_override_disabled":tr(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function XA(e,t){if(e.trustMode==="off")return null;let n=Nt(e,t.name),r=Fe(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 JA(e,t){if(e.mode==="off")return null;let r=Nt(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 $i(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 um(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=YA(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=XA(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=JA(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:$i("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:$i("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function fm(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=dm(e,t,n);return r?{allowed:e.mode==="warn",warning:$i(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function QA(e,t,n,r,o){let i=typeof r=="string"?dm(e,t,r):null,s=BA(e,t,n),a=o.command?HA(e,t,o.command):null,c=o.action?WA(e,t,o.action):null,l=o.service?KA(e,t,o.service):null;return i??s??a??c??l}function ZA(e,t,n,r){let o={method:Fe(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=X(r.command)),r.action&&(o.action=Fe(r.action).replace(/\s+/g,"-")),r.service&&(o.service=Fe(r.service)),o}function pm(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=QA(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=$i(e.mode==="warn"?"violation":"blocked","registration",t,a,ZA(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]="7316b9ef-38e1-5ee0-9107-da15ec7804d4")}catch{}})();function mm(e){return e==="toon"||e==="json"}function _m(e){return Gn.includes(e)}function ln(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var gm=Symbol("extension_registration_trace");function _t(e,t){let n=new TypeError(e);return Object.defineProperty(n,gm,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function ym(e){return e instanceof Error?e[gm]:void 0}function to(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>to(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={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=to(t[r]);return n}return e}function no(e){if(Array.isArray(e))return e.map(t=>no(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]=no(t[r]);return n}return e}function nr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return to(t)}function ro(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return no(t)}function ji(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>nr(e,n))}function ve(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function oo(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Hc(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Wc(e,t){return X(`${e} ${t}`)}function io(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var eS=new Set(["low","medium","high"]),tS=new Set(["number","string_set"]),nS=new Set(["string","number","boolean"]);function hm(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function rS(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=se(r,n);if(!tS.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(te(`${r}.description`,o.description),o.parameters===void 0)return;let i=se(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;hm(`${c}.name`,s);let l=se(c,a);if(!nS.has(String(l.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);pe(`${c}.required`,l.required),te(`${c}.description`,l.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function bm(e){let t=se("registerAssuranceMeasurementProvider provider",e),n=hm("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!eS.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=se("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);rS(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();function wm(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]="e4e1b7c2-6551-5e56-b26a-30062aed5b97")}catch{}})();var iS=100,Em=null,sS=Object.freeze(fi()),vm=0;function aS(e=Date.now()){return vm+=1,`${vm}-${e}`}function Tm(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function cS(e){if(e==null)return;let t=on(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 Kc(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Nm(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function dn(e){if(e!=null)return typeof e!="boolean"?null:e}function lS(e){let t=Nm(e.priority);return t===void 0?iS:t}function dS(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=eo(t);return n!==t.trim().toLowerCase()?null:n}function Yc(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function uS(e){if(e==null)return;let t=on(e);if(!t)return null;let n=Yc(t.source),r=Yc(t.signature),o=Yc(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 fS(e){if(e==null)return;let t=on(e);if(!t)return null;let n=dn(t.fs_read),r=dn(t.fs_write),o=dn(t.network),i=dn(t.env_read),s=dn(t.env_write),a=dn(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 pS(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=Op(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function mS(e){if(e==null)return;let t=on(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=>X(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function _S(e){let t=Nm(e.manifest_version);if(t===null)return null;let n=Tm(e,"pm_min_version");if(n===null)return null;let r=Tm(e,"pm_max_version");if(r===null)return null;let o=cS(e.engines);if(o===null)return null;let i=dn(e.trusted);if(i===null)return null;let s=dS(e);if(s===null)return null;let a=uS(e.provenance);if(a===null)return null;let c=fS(e.permissions);if(c===null)return null;let l=pS(e.capabilities);if(l===null)return null;let d=mS(e.activation);if(d===null)return null;let u=xc(e.contributions);return u===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:l.capabilities,legacy_capability_aliases:l.legacy_aliases,activation:d,contributions:u}}function gS(e){if(typeof e!="object"||e===null)return null;let t=e,n=Kc(t,"name");if(n===null)return null;let r=Kc(t,"version");if(r===null)return null;let o=Kc(t,"entry");if(o===null)return null;let i=lS(t);if(i===null)return null;let s=_S(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 yS(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function hS(e,t){let[n,r]=await Promise.all([fn.realpath(e),fn.realpath(t)]);return jc(n,r)}function Dm(e,t=process.cwd()){return{global:un.join(It(t),"extensions"),project:un.join(e,"extensions")}}async function bS(e){try{return(await fn.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort((n,r)=>n.localeCompare(r))}catch{return[]}}function wS(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 km(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function ES(e){let t=new Map;try{let n=JSON.parse(await fn.readFile(un.join(e,".managed-extensions.json"),"utf8")),o=on(n)?.entries;if(!Array.isArray(o))return t;for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=km(s.source?.package),c=[s.source?.input,s.source?.name,a].map(u=>km(u)).filter(u=>u!==void 0),l=xc(s.contributions),d={aliases:[...new Set(c)],...a?{package_name:a}:{},...l?{contributions:l}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&t.set(`directory:${s.directory.trim()}`,d),typeof s.name=="string"&&s.name.trim().length>0&&t.set(`name:${s.name.trim()}`,d)}}catch{return t}return t}function Am(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 vS(e,t){let n=[...Am(e),...Am(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 Sm(e,t,n,r,o){let i=[],s=[],a=[],c=await bS(t),l=await ES(t);for(let d of c){let u=await AS(e,t,d,n,r,l,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function TS(){return{diagnostics:[],warnings:[],candidates:[]}}function xm(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 kS(e,t,n,r,o,i,s){let a=Np(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&a.push(Rp(e,t.name,t.legacy_capability_aliases));for(let c of Cp(t.capabilities))a.push(Ip(e,t.name,c));return r?o||a.push(`extension_entry_missing:${e}:${t.name}`):a.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&a.push(i.warning),s.warning&&a.push(s.warning),a}async function AS(e,t,n,r,o,i,s){let a=un.join(t,n),c=un.join(a,"manifest.json");if(!await ee(c))return xm(e,n,c,`extension_manifest_missing:${e}:${n}`);let l,d;try{let W=JSON.parse(await fn.readFile(c,"utf8"));d=on(W),l=gS(W)}catch{d=null,l=null}if(!l||!d)return xm(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=un.resolve(a,l.entry),f=jc(a,u),p=f?await ee(u):!1,_=f&&p?await hS(a,u):f,y=yS(l.name,r,o),b=await xS(e,l),E=await CS(e,l,s),T=kS(e,l,d,_,p,b,E),O=_&&p&&b.allowed&&E.allowed,M=i.get(`directory:${n}`)??i.get(`name:${l.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:l.name,version:l.version,entry:l.entry,priority:l.priority,entry_path:u,enabled:y,status:O?"ok":"warn"},warnings:T,candidate:wm({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:l,sourceIdentity:M,extensionReady:O,enabledForLoad:y})}}async function Pm(e){let t=Dm(e.pmRoot,e.cwd??process.cwd()),n=Kr(e.settings.extensions.enabled),r=Kr(e.settings.extensions.disabled),o=am(e.settings),i=cm(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?TS():await Sm("global",t.global,s,a,o.pmMaxVersionExceededMode.global),l=await Sm("project",t.project,s,a,o.pmMaxVersionExceededMode.project),d=[...o.warnings],u=vS(c.candidates,l.candidates),f=[];for(let p of u){let _={layer:p.layer,name:p.manifest.name,trusted:p.manifest.trusted===!0,provenanceVerified:p.manifest.provenance?.verified===!0,sandboxProfile:p.manifest.sandbox_profile,permissions:p.manifest.permissions&&typeof p.manifest.permissions=="object"?{fs_read:p.manifest.permissions.fs_read,fs_write:p.manifest.permissions.fs_write,network:p.manifest.permissions.network,env_read:p.manifest.permissions.env_read,env_write:p.manifest.permissions.env_write,process_spawn:p.manifest.permissions.process_spawn}:void 0},y=um(o,_);if(y.warning&&d.push(y.warning),!!y.allowed){for(let b of p.manifest.capabilities){let E=fm(o,_,b);E.warning&&d.push(E.warning)}f.push(wS(p))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...l.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...l.warnings,...d])],policy:i}}function Ui(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function SS(){try{let e=mt(import.meta.url,["../../.."]),t=await fn.readFile(un.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 Lm(){return Em??=SS(),Em}function Mm(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 xS(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=tm(t.pm_min_version,await Lm()),r=Mm(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function CS(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=nm(t.pm_max_version,await Lm(),n),o=Mm(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Cm(e){try{let t=await fn.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function OS(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Gp(t.module_graph_snapshot_root,e));let r=new URL(oS(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[i,s]=await Promise.all([Cm(e.entry_path),Cm(e.manifest_path)]),a=t.reload_token??aS();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 IS(e){let t=await Pm(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 OS(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:Ui(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Om=5e3,RS=2147483647;function NS(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 Fm(e){let t=Jf(e);return t?NS(t):null}async function _G(e,t,n={}){let r=DS(n?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(d=>`${d.layer}:${d.name}`)),i=[];for(let d of e.loaded){if(o.has(`${d.layer}:${d.name}`))continue;let u=Fm(d.module);!u||typeof u.deactivate!="function"||i.push({extension:d,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:d,deactivate:u})=>{try{return await PS(u,r),{ok:!0}}catch(f){return{ok:!1,layer:d.layer,name:d.name,error:Ui(f)}}})),a=[],c=[],l=0;for(let d of s){if(d.ok){l+=1;continue}a.push(`extension_deactivate_failed:${d.layer}:${d.name}`),c.push({layer:d.layer,name:d.name,error:d.error})}return{deactivated:l,warnings:a,failed:c}}function DS(e){return typeof e!="number"||e<0?Om:e===0||e===1/0?0:Number.isFinite(e)?Math.min(RS,Math.max(1,Math.floor(e))):Om}async function PS(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)}}var LS=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","visible"]);function Xc(e,t){return ji(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function MS(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Im(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=MS(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Rm(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=ve(`registerCommand definition.arguments[${r}].name`,i.name);if(pe(`registerCommand definition.arguments[${r}].required`,i.required),pe(`registerCommand definition.arguments[${r}].variadic`,i.variadic),te(`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 Jc(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=>!LS.has(c)).sort((c,l)=>c.localeCompare(l));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`);te(`registerFlags flags[${t}].long`,i),te(`registerFlags flags[${t}].short`,s);let a=Qp(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${Zp(a.token,a.failure)}`);if(te(`registerFlags flags[${t}].value_name`,r.value_name),te(`registerFlags flags[${t}].description`,r.description),pe(`registerFlags flags[${t}].required`,r.required),pe(`registerFlags flags[${t}].enabled`,r.enabled),pe(`registerFlags flags[${t}].visible`,r.visible),pe(`registerFlags flags[${t}].list`,r.list),pe(`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(Yp(`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.`);FS(`registerFlags flags[${t}]`,r)}}function FS(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=sc(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?ac(t.default):[t.default];for(let[i,s]of o.entries())if(!sp(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function $S(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);ve(`registerItemFields fields[${t}].name`,r.name);let o=ve(`registerItemFields fields[${t}].type`,r.type);if(Fi(o)===null){let i=Vp(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Mi.join(", ")}).${s}`)}pe(`registerItemFields fields[${t}].optional`,r.optional)}}function jS(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);ve(`${i}.command`,s.command),ve(`${i}.option`,s.option),pe(`${i}.enabled`,s.enabled),pe(`${i}.required`,s.required),pe(`${i}.visible`,s.visible)}}function US(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);ve(`${i}.key`,s.key),cn(`${i}.values`,s.values),pe(`${i}.required`,s.required),cn(`${i}.aliases`,s.aliases)}}function zS(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);ve(`${r}.name`,o.name),te(`${r}.folder`,o.folder),cn(`${r}.aliases`,o.aliases),cn(`${r}.required_create_fields`,o.required_create_fields),cn(`${r}.required_create_repeatables`,o.required_create_repeatables),jS(t,o.command_option_policies),US(t,o.options)}}function qS(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(pe("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 $m=["types","statuses","fields","workflows","config","templates","packages"],VS={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 GS(e){let t=se("registerProfile profile",e);if(ve("registerProfile profile.name",t.name),ve("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 $m){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`);VS[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function BS(e){e.summary===void 0&&(e.summary="");for(let t of $m)e[t]===void 0&&(e[t]=[]);return e}function HS(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Rt(r)&&t.add(r)}return t}function J(e,t,n){let r=HS(e);if(r!==null&&!r.has(t))throw _t(`${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 WS(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>Qe.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function KS(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 Qc=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#l;#d;#u;constructor(t,n,r,o,i,s,a,c,l,d,u){this.#e=t,this.extension=WS(t),this.#n=KS(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#l=l,this.#d=d,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=pm(this.#u,this.#n,t,n,r,o);return i.warning&&this.#l.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:to(o),hint:i}}registerCommandOverride(t,n){let r=X(t);if(r.length===0)throw _t("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 _t(`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.#l.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 _t("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 _t("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=X(t.name);if(n.length===0)throw _t("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 _t(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{Xp(t);let o=Im(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=Qr("registerCommand definition.examples",t.examples),c=Qr("registerCommand definition.failure_hints",t.failure_hints),l=Rm(t.arguments);t.flags!==void 0&&(J(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(Jc(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Xc("registerCommand definition.flags",t.flags)})));let d={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:a,failure_hints:c,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};i&&(d.description=i),s&&(d.intent=s),this.#t.commands.push(d)}catch(o){let i=Ui(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=_t(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#l.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#d.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(J(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(J(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=X(ve("registerParser command",t));oo("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(J(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Hp(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){J(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!_m(o))throw new TypeError(`registerService service must be one of: ${Gn.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(oo("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...Kp(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(J(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(!mm(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 X(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(J(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=X(ve("registerFlags targetCommand",t));Jc(n);let o=Xc("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(J(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;$S(t);let n=ji("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(J(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;zS(t);let n=ji("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(J(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=wc();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(J(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;qS(t);let n=ro("registerMigration definition",t);this.#t.migrations.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerMigration definition",t)},n))}registerProfile(t){if(J(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=no(t);GS(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:BS(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(J(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(Jc(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Xc(`${t} options.flags`,r.flags)})))}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},a=Jp(t,s,r?.description!==void 0);te(`${t} options.action`,s.action),te(`${t} options.description`,s.description),te(`${t} options.intent`,s.intent);let c=Im(n,s.action),l=Qr(`${t} options.examples`,s.examples),d=Qr(`${t} options.failure_hints`,s.failure_hints),u=Rm(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:l,failure_hints:d,arguments:u},p=s.description?.trim();p&&(f.description=p);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,n,r){if(J(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Hc(ve("registerImporter name",t));oo("registerImporter importer",n);let i=Wc(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(zc(s,o,"import"))})}registerExporter(t,n,r){if(J(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Hc(ve("registerExporter name",t));oo("registerExporter exporter",n);let i=Wc(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(zc(a,o,"export"));return s?.receipt==="suppress"&&!hi(c)?cp(c):c}})}registerSearchProvider(t){if(J(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=ro("registerSearchProvider provider",t);this.#t.search_providers.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(J(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=ro("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(J(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(bm(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=ro("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(io({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:nr("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){J(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(ln("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){J(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(ln("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){J(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(ln("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){J(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(ln("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){J(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(ln("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){J(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(ln("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function YS(e,t,n,r,o,i,s,a,c,l,d){return new Qc(e,t,n,r,o,i,s,a,c,l,d)}function XS(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,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function JS(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let l=a.get(c.command)??[];l.push(c),a.set(c.command,l)}for(let c of[...a.keys()].sort((l,d)=>l.localeCompare(d))){let l=a.get(c);if(l.length<=1)continue;let d=l[l.length-1];for(let u of l.slice(0,-1))t.push(`${s}:${c}:${d.layer}:${d.name}:${u.layer}:${u.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 l of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${l.layer}:${l.name}`)}return t}function QS(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 ZS(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}var ex=new Set(["output_format"]);function tx(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||ex.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 nx(e){let t=lm(e.policy??sS),n=Yr(),r=vc(),o=Tc(),i=kc(),s=Ac(),a=Sc(),c=Di(),l=[],d=[];for(let p of e.loaded){let _=Fm(p.module);if(!_)continue;let y=l.length,b=Bp({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(YS(p,n,r,o,i,s,a,c,d,l,t)),l.length>y&&(b(),d.push(`extension_activation_rolled_back:${p.layer}:${p.name}`))}catch(E){b(),d.push(`extension_activate_failed:${p.layer}:${p.name}`);let T=ym(E);l.push({layer:p.layer,name:p.name,entry_path:p.entry_path,error:Ui(E),trace:T})}}let u=[...JS(r),...ZS(o),...Wp(i),...tx(s),...QS(a)],f=[...new Set([...d,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:l,warnings:f,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:XS(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 rx(e){return{...e,hooks:Yr(),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 TG(){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 jm(){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]="a35f3cdc-810e-59bd-8408-03ce792db57f")}catch{}})();var ox={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},Um=":";function zm(e,t){return`${e}${Um}${Zc(t)}`}function ix(e){return e.slice(e.indexOf(Um)+1)}function Zc(e){return e.trim().toLowerCase()}function sx(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=xp(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function qm(e){let t=new Map,n=(d,u)=>{for(let f of d){let p=zm(f.layer,f.name),_=t.get(p);_===void 0&&(_=new Set,t.set(p,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:l}=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(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(l.beforeCommand,"hooks"),n(l.beforeMutation,"hooks"),n(l.afterCommand,"hooks"),n(l.onWrite,"hooks"),n(l.onRead,"hooks"),n(l.onIndex,"hooks"),t}function ax(e,t={}){let n=qm(e),r=new Set;t.extensionName!==void 0&&r.add(Zc(t.extensionName));for(let i of t.extensionNames??[])r.add(Zc(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(ix(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function cx(e,t){let n=qm(t),r=[];for(let o of e){let i=sx(o.capabilities);if(i.length===0)continue;let s=n.get(zm(o.layer,o.name))??new Set,a=[...s].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>!s.has(l));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as lx}from"node:fs";import{AsyncLocalStorage as dx}from"node:async_hooks";import gt 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 Dt=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,pn=null,Hi,zi=[],Gm=new dx;function q(){return Gm.getStore()}function RG(e){return Gm.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var ux=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Vm(e){let t=gt.resolve(e);for(;;){if(lx(gt.join(t,".git")))return t;let n=gt.dirname(t);if(n===t)return;t=n}}function Wi(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=Vm(t)??gt.resolve(t),r=Vm(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=gt.relative(n,gt.resolve(e)),i=o.length>0&&!o.startsWith(`..${gt.sep}`)&&o!==".."&&!gt.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(gt.sep).join("/")}:{}}}function fx(e){let t=q();if(t){t.hooks=e;return}Dt=e}function px(e){let t=q();if(t){t.commands=e;return}so=e}function mx(e){let t=q();if(t){t.parsers=e;return}qi=e}function _x(e){let t=q();if(t){t.preflight=e;return}Vi=e}function gx(e){let t=q();if(t){t.services=e;return}ao=e}function yx(e){let t=q();if(t){t.renderers=e;return}Gi=e}function hx(e){let t=q();if(t){t.registrations=e;return}Bi=e}function Pt(){let e=q();return e?e.registrations:Bi}function bx(){let e=q();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}Dt=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,pn=null,Hi=null}function wx(e){let t=e?{...e,...Wi(e.pm_root)}:null,n=q();if(n){n.commandContext=t;return}pn=t}function Bm(){let e=q(),t=e?e.commandContext:pn;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function rr(e){let t=q();if(t){t.commandResult=e;return}Hi=e}function Ex(){let e=q();return e?e.commandResult:Hi}function Ki(e){if(!e)return;let t=q();t?t.affectedItems.push(e):zi.push(e)}function co(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"||ux.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function vx(){let e=q(),t=e?.affectedItems??zi;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:zi=[],n}function Tx(){let e=q();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}Dt=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,pn=null,Hi=void 0,zi=[]}async function ye(e){let t=q(),n=t?t.hooks:Dt;return n?Oc(n,e):[]}async function Yi(e){let t=q(),n=t?t.hooks:Dt;n&&await Cc(n,e)}async function He(e){let t=q(),n=t?t.hooks:Dt;return n?Ic(n,e):[]}function el(){let e=q();return((e?e.hooks:Dt)?.onRead?.length??0)>0}async function kx(e){let t=q(),n=t?t.hooks:Dt;return n?Rc(n,e):[]}function Hm(e){let t=q(),n=t?t.commands:so,r=t?t.commandContext:pn;return!n||!r?{overridden:!1,result:e,warnings:[]}:Fc(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 Ax(e){let t=q(),n=t?t.commands:so;return n?Nc(n,{...e,...Wi(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function Sx(e){let t=q(),n=t?t.parsers:qi;return n?Dc(n,{...e,...Wi(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 xx(e){let t=q(),n=t?t.preflight:Vi;return n?Pc(n,{...e,...Wi(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 Wm(e,t){let n=q(),r=n?n.renderers:Gi,o=n?n.commandContext:pn;return r?$c(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 Km(e,t){let n=q(),r=n?n.commandContext:pn;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 $e(e,t){let n=q(),r=n?n.services:ao;return r?Mc(r,Km(e,t)):{handled:!1,result:t,warnings:[]}}function tl(e,t){let n=q(),r=n?n.services:ao;return r?Lc(r,Km(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 mn=new Set(Me),Xi=Object.freeze({get size(){return mn.size},has(e){return mn.has(e)},entries(){return mn.entries()},keys(){return mn.keys()},values(){return mn.values()},forEach(e,t){mn.forEach(n=>e.call(t,n,n,Xi))},[Symbol.iterator](){return mn.values()}});function Ym(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Xm(e){return typeof e!="string"?null:Fi(e)}function Cx(e){try{return structuredClone(e)}catch{return e}}function Ox(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new h(`--field entries must use name=value syntax, received: ${e}`,g.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function Ix(e){return`--${e.replaceAll("_","-")}`}function Rx(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 h(`--field ${t}=... must be valid JSON ${n}`,g.USAGE)}function Nx(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new h(`--field ${e}=... must be a number`,g.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new h(`--field ${e}=... must be a number`,g.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 h(`--field ${e}=... must be one of true|false|1|0|yes|no`,g.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):Rx(n,e,t)}function nl(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Ym(r.name),i=Xm(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new h(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,g.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 Jm(e){if(Xi.has(e))throw new h(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...Xi].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,g.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function lo(e){return[...nl(e).keys()].sort((t,n)=>t.localeCompare(n))}function Dx(e,t){if(!e||e.length===0)return{};let n=nl(t),r={};for(let o of e){let{key:i,value:s}=Ox(o),a=n.get(i);if(!a){if(Xi.has(i)){let l=Ix(i);throw new h(`--field ${i} is a core item field, not an extension field`,g.USAGE,{code:"core_item_field_requires_dedicated_flag",field:i,recovery:{provided_fields:[i],suggested_flags:[l]},nextSteps:[`Set the core field with its dedicated flag: pm update <id> ${l} <value>`,`When closing an item, pm close <id> also accepts ${l} <value>.`]})}let c=[...n.keys()].sort((l,d)=>l.localeCompare(d));throw new h(`--field ${i} is not declared by an active extension item-field registration`,g.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."]})}Jm(a.name),r[a.name]=Nx(a.name,a.type,s)}return r}function Px(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 Lx(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function Mx(e,t,n={}){if(t){nl(t);for(let r of t.item_fields)for(let o of r.fields){let i=Ym(o.name);if(!i)continue;Jm(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=Cx(o.default));let s=e[i];if(s===void 0)continue;let a=Xm(o.type);if(a&&!Px(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Lx(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}catch{}})();function Lt(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function zG(e,t){let n=Lt(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>Lt(r.definition.id)===n)??null}function Fx(e,t){let n=Lt(t);return!e||!n?null:[...e.search_providers].reverse().find(o=>(Lt(o.runtime_definition?.name)??Lt(o.definition?.name))===n)??null}function $x(e,t){let n=Lt(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(o=>(Lt(o.runtime_definition?.name)??Lt(o.definition?.name))===n)??null}function qG(e){return e.runtime_definition??e.definition}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var yt="-",Zm=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function HG(e,t){if(e.startsWith("```")||e.includes(`
5
- `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)}function e_(e){let t=e.trim();if(t==="")return[];let r=(Vx(t)??t.split(",")).map(o=>o.trim()).filter(Boolean).map(o=>o.toLowerCase());return Array.from(new Set(r)).sort((o,i)=>o.localeCompare(i))}function t_(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of e_(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function n_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function jx(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function Ux(e,t,n){let r=e.map(s=>s.trim()).filter(Boolean);for(let s of t??[]){let a=s.trim();if(a.includes(";"))throw new h('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',g.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});a.length>0&&!r.includes(a)&&r.push(a)}let o=[],i=r;for(let s of n??[]){let a=s.trim();if(a.length!==0){if(!i.includes(a)){o.push(a);continue}i=i.filter(c=>c!==a)}}return{criteria:i,unmatchedRemovals:o}}function zx(e,t){let n=n_(e);if(!t||t.length===0)return Array.from(new Set(n)).sort((o,i)=>o.localeCompare(i));let r=new Set(n);for(let o of t_(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function qx(e,t){let n=Array.from(new Set(n_(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(t_(t));return r.size===0?n:n.filter(o=>!r.has(o))}function Vx(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"").filter(r=>r.length>0)}function rl(e){return e.replace(/\r\n/g,`
6
- `)}function r_(e){let t=rl(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
1
+ var nT=Object.defineProperty;var yq=(e,t)=>{for(var n in t)nT(e,n,{get:t[n],enumerable:!0})};import*as ne from"node:fs/promises";import ii from"node:path";import rT 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]="23fc5fcb-5c80-57ab-8d91-8d15ee35ab53")}catch{}})();var oT=[10,25,50,100];async function si(e){await ne.mkdir(e,{recursive:!0})}async function ee(e){try{return await ne.access(e),!0}catch{return!1}}function Bf(e){return le(e)||sn(e,"ENOTDIR")}function le(e){return sn(e,"ENOENT")}async function Y(e){try{return await ne.readFile(e,"utf8")}catch(t){if(Bf(t))return null;throw t}}async function L(e,t){let n=ii.dirname(e);await si(n);let r=ii.join(n,`.${ii.basename(e)}.${process.pid}.${Date.now()}.${rT.randomBytes(4).toString("hex")}.tmp`);await ne.writeFile(r,t,"utf8");try{await ne.rename(r,e)}catch(o){if(process.platform==="win32"&&(sn(o,"EPERM")||sn(o,"EBUSY"))){let i=o;for(let s of oT){await new Promise(a=>setTimeout(a,s));try{await ne.rename(r,e);return}catch(a){if(i=a,!sn(a,"EPERM")&&!sn(a,"EBUSY"))break}}try{await ne.unlink(r)}catch{}throw i}if(sn(o,"EXDEV")){try{await ne.copyFile(r,e)}finally{try{await ne.unlink(r)}catch{}}return}try{await ne.unlink(r)}catch{}throw o}}async function Rt(e,t){let n=ii.dirname(e);await si(n);let r=await ne.open(e,"a");try{await r.writeFile(`${t}
2
+ `,"utf8")}finally{await r.close()}}async function $r(e){try{await ne.unlink(e)}catch(t){if(!Bf(t))throw t}}function sn(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]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var tt=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],ai=2,Xa=Object.freeze({migration:"schema",validation:"schema"}),vq=Object.freeze({version:ai,capabilities:[...tt],legacy_aliases:{...Xa}}),ci=["off","warn","enforce"],li=["off","warn","enforce"],di=["none","restricted","strict"],Hf=["block","warn"],ui=["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","services.assuranceprovider"],Gn=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function fi(){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]="27c5eac3-4580-5f6f-8ae9-b04d0281766d")}catch{}})();var Wf=["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"],iT=["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",...Wf,"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"],Me=iT;(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var Qa=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"]}]),Za=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),pi=".agents/pm",mi="settings.json",sT="Closed at creation via pm create",aT=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],cT=["decisions","events","reminders","milestones","meetings","plans"],Sq=[...aT,...cT],_e={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},ec={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}},lT=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],Ja={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 Kf(e){return e?[...e]:void 0}var x={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"},ux:{deprecation_hints:!0},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:[...lT],lifecycle_closure_like_blocked_reason_patterns:[...Ja.blocked_reason],lifecycle_closure_like_resolution_patterns:[...Ja.resolution],lifecycle_closure_like_actual_result_patterns:[...Ja.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...ec.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1,allow_untrusted_linked_tests:!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:Qa.map(e=>({...e,aliases:Kf(e.aliases),roles:Kf(e.roles)})),fields:[],workflow:{...Za},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:fi()},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:""}}},Bn={metadata:{},body:""},g={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},dT=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 _i(e){let t=(e??"").trim().toLowerCase();if(t.length===0)return"unknown";let n=dT[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]="922e2e27-1499-5466-98e4-322d0d742e40")}catch{}})();var h=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 $(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function uT(e){return $(e)??void 0}function jr(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 Hn(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function q(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function gi(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 Xf(e){let t=gi(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function Iq(e,t,n){let r=gi(e);return r===null||r<t||r>n?null:r}function fT(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function an(e){return typeof e!="object"||e===null?null:e}function Yf(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Jf(e){let t=Yf(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=Yf(t.default);return typeof n?.activate=="function"?n:null}function pT(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 Wn(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import mT from"node:crypto";import{AsyncLocalStorage as _T}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]="aacc48ae-e9b2-5c8e-945f-89d05aff48e8")}catch{}})();var tc=new _T,Qf=1024;function gT(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function yT(e){let n={...gT(e),clockReads:0,tokenReads:0};return r=>tc.run(n,r)}async function Lq(e,t){return yT(e)(t)}function Zf(){let e=tc.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 ep(e){let t=tc.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Qf)throw new Error(`Reproducible token length must be an integer between 0 and ${Qf}`);let n="";for(;n.length<e;){let r=mT.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]="7887e752-b1b8-5c5e-9dd8-93b41cb757af")}catch{}})();var hT=/^([+-]?)(\d+)([hdwm])$/i,bT=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,wT=/^(\d{4})(\d{2})(\d{2})$/,ET=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,vT=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,TT=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,kT=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function oe(){return Zf()??new Date().toISOString()}function _t(e){return Number.isFinite(Date.parse(e))}function np(e){let t=kT.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,l]=t,[d,u,f,p,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=oc(d,u-1)&&p<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var AT=1e4,yi=new Map;function tp(e){let t=yi.get(e);if(t!==void 0)return t;let n=Date.parse(e);return yi.size>=AT&&Wn(yi),yi.set(e,n),n}function de(e,t){let n=tp(e),r=tp(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function zq(e,t){return!(t.deadlineBefore&&(!e.deadline||de(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||de(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&de(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&de(e.updated_at,t.updatedBefore)>0||t.createdAfter&&de(e.created_at,t.createdAfter)<0||t.createdBefore&&de(e.created_at,t.createdBefore)>0)}function nc(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function rc(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 ST(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function xT(e){let t=[],n=l=>ST(t,e,l),r=wT.exec(e);if(r){let[,l,d,u]=r;n(`${l}-${d}-${u}`)}let o=ET.exec(e);if(o){let[,l,d,u,f,p,_,y,b]=o,E=_?`:${_}`:"";n(`${l}-${d}-${u}T${f}:${p}${E}${nc(y)}${rc(b)}`)}let i=vT.exec(e);if(i){let[,l,d,u,f,p,_]=i,y=f?`:${f}`:"";n(`${l}T${d}:${u}${y}${nc(p)}${rc(_)}`)}let s=TT.exec(e);if(s){let[,l,d,u,f,p,_]=s,y=f?`:${f}`:"";n(`${l}T${d}:${u}${y}${nc(p)}${rc(_)}`)}let a=10,c=e.slice(0,a);if(OT(c)){let l=a;for(;l<e.length&&IT(e[l]);)l+=1;l<e.length&&n(`${c}T${e.slice(l)}`)}return t}function CT(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of xT(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function OT(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 IT(e){return e?e===" "||e===" "||e===`
3
+ `||e==="\r"||e==="\f"||e==="\v":!1}function oc(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var RT=["January","February","March","April","May","June","July","August","September","October","November","December"],NT=/^(\d{4})-(\d{2})-(\d{2})/,DT=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function PT(e,t,n){let r=NT.exec(t)??DT.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 h(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,g.USAGE);let c=oc(o,i-1);if(s<1||s>c)throw new h(`Invalid ${a} value "${e}". ${RT[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,g.USAGE)}function LT(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,oc(i,s));return n.setUTCFullYear(i,s,a),n}function MT(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=hT.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 LT(t,a).toISOString();let l=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*l).toISOString()}PT(e,r,n);let i=CT(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=bT.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 h(`Invalid ${s} value "${e}". ${a}`,g.USAGE)}return new Date(i).toISOString()}import{mkdir as FT,readFile as $T}from"node:fs/promises";import rp 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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}catch{}})();function jT(e){let t=e.trim();if(!t)throw new h("--rollback requires a non-empty checkpoint ID",g.USAGE);if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new h("--rollback checkpoint ID must match [a-zA-Z0-9._-]+",g.USAGE);return t}function UT(e,t){let n=t.replace(/[-:.TZ]/g,"").slice(0,14),r=Math.random().toString(36).slice(2,8);return`${e}-${n}-${r}`}function op(e,t){return rp.join(e,"checkpoints",t)}function ip(e,t,n){return rp.join(op(e,t),`${n}.json`)}async function zT(e,t,n,r){let o=op(e,t);await FT(o,{recursive:!0});let i=ip(e,t,n);return await L(i,`${JSON.stringify(r,null,2)}
4
+ `),i}function qT(e,t){if(!Array.isArray(e.items))throw new h(`Checkpoint ${t} is missing items`,g.GENERIC_FAILURE);return e.items.map(n=>{if(!n||typeof n!="object")throw new h(`Checkpoint ${t} contains an invalid item entry`,g.GENERIC_FAILURE);let r=n;if(typeof r.id!="string"||r.id.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without ID`,g.GENERIC_FAILURE);if(typeof r.target_updated_at!="string"||r.target_updated_at.trim().length===0)throw new h(`Checkpoint ${t} contains an item entry without target_updated_at`,g.GENERIC_FAILURE);return{id:r.id.trim(),target_updated_at:r.target_updated_at.trim()}})}async function VT(e,t,n,r){let o=jT(n),i=ip(e,t,o);if(!await ee(i))throw new h(`Checkpoint ${o} not found`,g.NOT_FOUND);let s=await $T(i,"utf8"),a;try{a=JSON.parse(s)}catch(d){throw new h(`Checkpoint ${o} contains invalid JSON: ${q(d)}`,g.GENERIC_FAILURE)}if(!a||typeof a!="object")throw new h(`Checkpoint ${o} is invalid`,g.GENERIC_FAILURE);let c=a;if(c.schema_version!==r)throw new h(`Checkpoint ${o} has unsupported schema version`,g.GENERIC_FAILURE);let l=qT(c,o);return{record:c,items:l,path:i,id:typeof c.id=="string"?c.id:o,created_at:typeof c.created_at=="string"?c.created_at:oe(),author:typeof c.author=="string"?c.author:"unknown"}}async function GT(e,t){let n=[],r=[];for(let o of e)try{let i=await t(o.id,o.target_updated_at);n.push({id:o.id,status:"restored",changed_fields:i.changed_fields,warnings:i.warnings}),r.push(o.id)}catch(i){n.push({id:o.id,status:"failed",error:q(i)})}return{rows:n,restored_ids:r,failed_count:n.filter(o=>o.status==="failed").length}}(function(){try{var e=typeof window<"u"?window:typeof 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 BT=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function ic(e){return typeof e!="string"?null:BT[e.trim().toLowerCase()]??null}function sc(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 sp(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof 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 We(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 l=s[0];for(let d=1;d<=t.length;d+=1){let u=e[c-1]===t[d-1]?0:1,f=i[d-1]+u,p=s[d-1]+1,_=i[d]+1,y=Math.min(f,p,_);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(y=Math.min(y,o[d-2]+1)),s[d]=y,y<l&&(l=y)}if(l>n)return null;for(let d=0;d<r;d+=1)o[d]=i[d],i[d]=s[d]}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]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}catch{}})();var n2=[{code:"unknown_lifecycle_action"}];function HT(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Math.floor(n.length/3);return t.map(o=>({candidate:o,distance:We(n,o.toLowerCase(),r)??Number.POSITIVE_INFINITY})).filter(({distance:o})=>Number.isFinite(o)).sort((o,i)=>o.distance!==i.distance?o.distance-i.distance:o.candidate.localeCompare(i.candidate))[0]?.candidate}function ap(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function WT(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),n=e.token.trim(),r=n.length===0?"<empty>":n,o=[...new Set(e.allowed.map(f=>f.trim()))].filter(Boolean).sort((f,p)=>f.localeCompare(p));if(t.length===0||r.length===0||o.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let i=t.split(" "),s=e.trailing_args??[],a=e.display_name??`pm ${t}`,c=e.token_kind??"subcommand",l=e.retry_command?void 0:HT(r,o),d=ap([...i,r,...s]),u=e.retry_command??(l?ap([...i,l,...s]):void 0);return new h(`Unknown ${a} ${c} "${r}". Allowed: ${o.join(", ")}${e.message_suffix??""}`,e.exit_code??g.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:o,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}(function(){try{var e=typeof window<"u"?window:typeof 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 KT="__pm_suppress_host_output",ac="@unbrained/pm-cli:suppress-host-output:v1";function cp(e){return e===void 0?{__pm_suppress_host_output:ac}:{__pm_suppress_host_output:ac,result:e}}function hi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[KT]===ac}import Kn from"node:fs";import gt from"node:path";import{fileURLToPath as YT}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 XT="@unbrained/pm-cli";function JT(e){try{return JSON.parse(Kn.readFileSync(e,"utf8")).name===XT}catch{return!1}}function QT(e){let t=Kn.existsSync(e)&&Kn.statSync(e).isDirectory()?gt.resolve(e):gt.dirname(gt.resolve(e));for(;;){let n=gt.join(t,"package.json");if(Kn.existsSync(n)&&JT(n))return t;let r=gt.dirname(t);if(r===t)return;t=r}}function yt(e,t=[]){let n=YT(e),r=QT(n);return r||gt.resolve(gt.dirname(n),...t)}function cc(e,t=[]){try{let n=gt.join(yt(e,t),"package.json");if(!Kn.existsSync(n))return;let r=JSON.parse(Kn.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function ZT(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?gt.resolve(o.trim()):n?yt(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]="64223a83-1287-57ac-915d-dbd5e375a6eb")}catch{}})();var Yn=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],lp=Yn,Xn=["draft","open","in_progress","blocked","closed","canceled"],bi=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Jn=["string","number","boolean","string_array","array","object"],wi=["create","update","update_many","list","search","calendar","context"],Ei=["allow","warn","reject"],l2=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],d2=["project","global"],u2=["low","medium","high","critical"],vi=["low","medium","high","critical"],Ti=["low","medium","high"];var dp=["minimal","default","strict","custom"],f2=["none","warn","strict"],p2=["progressive","strict"],m2=["off","warn","strict"],_2=["off","warn","strict"];var ki=["daily","weekly","monthly","yearly"],Ur=["mon","tue","wed","thu","fri","sat","sun"];function lc(e){return Ur.indexOf(e)}var up=["draft","research","review","approved","executing","paused","completed","superseded"],Ai=["pending","in_progress","completed","blocked","skipped","superseded"],fp=["codex","claude-code","cursor","generic"],pp=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],g2=["brief","standard","deep","full"],y2=["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 ok 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 Nt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ek(e){let t=e.key.trim();if(t.length===0)return null;let n=Nt(e.aliases),r=e.description?.trim();return{key:t,values:Nt(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 tk=e=>e,_p=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function nk(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 rk(e,t){let n=new Map;for(let r of e??[]){let o=nk(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 mp(e,t){return t?Nt(e):void 0}function dc(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Si(e,t={}){let n=t.resolvePolicyCommand??tk,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=Nt(e.aliases),l=(e.options??[]).map(u=>ek(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=rk(e.command_option_policies,n);return{name:r,description:dc(e.description),default_status:dc(e.default_status),folder:dc(e.folder),aliases:c.length>0?c:void 0,required_create_fields:mp(e.required_create_fields,o),required_create_repeatables:mp(e.required_create_repeatables,i),options:s?l:void 0,command_option_policies:a?d: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 ik=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],sk=["dep","comment","note","learning","file","test","doc"],fc=["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"],ak=["title","description","type","status","priority","tags","body",...fc,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ck=["title","description","body","status","closeReason","priority","type","tags",...fc,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],yp={"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"},lk={...yp},dk={...yp},hp=[["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"]],bp=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function wp(e){return Object.fromEntries(e)}var uk=wp([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...hp,["author","--author"],["message","--message"],["dep","--dep"],...bp]),fk=wp([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...hp,...bp,["author","--author"],["message","--message"],["force","--force"]]);function pk(e){return e.trim().replace(/^--+/,"").toLowerCase()}function mk(e){return e==="create"?ak:ck}function _k(e){return e==="create"?lk:dk}function pc(e,t){let n=pk(t);if(n.length===0)return;let r=_k(e)[n];return r||mk(e).find(o=>o.toLowerCase()===n)}function gk(e,t){return(e==="create"?uk:fk)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function qr(e){let t=yk(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function xi(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=ok.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 yk(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 hk(e){return Si(e,{resolvePolicyCommand:_p})}function zr(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function bk(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:zr(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:zr(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function wk(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 Ek(e){if(Array.isArray(e.options))return e.options.map(t=>bk(t)).filter(t=>t!==null)}function vk(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>wk(t)).filter(t=>t!==null)}function Tk(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:zr(t,"aliases"),required_create_fields:zr(t,"required_create_fields"),required_create_repeatables:zr(t,"required_create_repeatables"),options:Ek(t),command_option_policies:vk(t)}}function kk(e,t){return e.required_create_fields?Nt(e.required_create_fields):t?.required_create_fields??[]}function Ak(e,t){return e.required_create_repeatables?Nt(e.required_create_repeatables):t?.required_create_repeatables??[]}function Sk(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function xk(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Ck(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=xi(e.folder??t?.folder??qr(n)),s={name:n,folder:i,aliases:Nt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:kk(e,t),required_create_repeatables:Ak(e,t),options:Sk(e,t),command_option_policies:xk(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function gp(e,t){for(let n of e){let r=hk(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Ck(r,i))}}function Ok(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=Tk(o);i&&t.push(i)}}return t}function Vr(e,t=null){let n=new Map;for(let c of lp)n.set(c.toLowerCase(),{name:c,folder:_e[c],aliases:[],required_create_fields:[...ik],required_create_repeatables:[...sk],options:[],command_option_policies:[]});gp(e.item_types?.definitions??[],n),gp(Ok(t),n);let r=[...n.values()].sort((c,l)=>c.name.localeCompare(l.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 l of c.aliases)i[l.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,l)=>c.localeCompare(l));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Ep(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function vp(e,t){let n=Ep(e,t);if(n)return t.by_type[n]}function Ik(e,t,n,r){for(let o of r){let i=pc(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 uc(e,t,n){if(n){e.add(t);return}e.delete(t)}function Rk(e,t,n,r){let o=pc(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&&uc(e.required,o,r.required),r.visible!==void 0&&uc(e.hidden,o,!r.visible),r.enabled!==void 0&&uc(e.disabled,o,!r.enabled)}function Nk(e,t,n){for(let r of t.command_option_policies)r.command===n&&Rk(e,t,n,r)}function Dk(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 Pk(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Ik(a,e,t,n),Nk(a,e,t),Dk(a,e,t),{required:[...o],hidden:[...i].sort((c,l)=>c.localeCompare(l)),disabled:[...s].sort((c,l)=>c.localeCompare(l)),errors:r}}function Lk(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 Mk(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 Fk(e,t,n){let r=vp(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Lk(r),s={};for(let[c,l]of Object.entries(t??{})){let d=c.trim(),u=l.trim();if(d.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${d}" must not be empty`);continue}let f=i.get(d.toLowerCase());if(!f){let _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${d}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let p=Mk(f,u,o);p!==void 0&&(s[f.key]=p)}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,l)=>c.localeCompare(l));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as $k,readdirSync as jk,statSync as Uk}from"node:fs";import zk from"node:os";import D 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 qk={json_markdown:".md",toon:".toon"},Vk={".md":"json_markdown",".toon":"toon"},Gk=new Set([".git","coverage","dist","node_modules"]),Ci=[".md",".toon"];function Gr(e){try{return Uk(e),!0}catch{return!1}}function Tp(e){try{let t=JSON.parse($k(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Bk(e){let t=D.resolve(e);for(;;){let n=D.join(t,pi),r=D.join(n,mi);if(Gr(r))return n;let o=D.join(t,mi);if(Gr(o)&&Tp(o))return t;let i=D.dirname(t);if(i===t)return;t=i}}function kp(e){return Bk(e)??D.resolve(e,pi)}function N2(e,t){let n=t?D.resolve(t):void 0;try{return jk(D.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!Gk.has(r.name)).map(r=>D.join(D.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Gr(ge(r))).filter(r=>Tp(ge(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function Br(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=D.resolve(e,r);if(!Gr(ge(o))){let i=D.join(o,pi);if(Gr(ge(i)))return i}return o}return kp(e)}function Hk(e){let t=D.resolve(e),n=D.dirname(t);return D.basename(t)==="pm"&&D.basename(n)===".agents"?D.dirname(n):t}function Dt(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:D.join(zk.homedir(),".pm-cli");return D.resolve(e,n)}function ge(e){return D.join(e,mi)}function Wk(e,t,n=_e){let r=n[t]??qr(t);return D.join(e,r)}function Qn(e,t,n,r="toon",o=_e){return D.join(Wk(e,t,o),`${n}${qk[r]}`)}function Hr(e){let t=e.replaceAll("\\","/"),n=D.posix.extname(t).toLowerCase();return Vk[n]??null}function Zn(e,t){return D.join(e,"history",`${t}.jsonl`)}function Ap(e,t){return D.join(e,"locks",`${t}.lock`)}function mc(e){return D.join(e,"runtime")}function Oi(e){return D.join(mc(e),"test-runs")}function Kk(e){return D.join(Oi(e),"runs")}function D2(e,t){return D.join(Kk(e),`${t}.json`)}function Yk(e){return D.join(Oi(e),"stdout")}function Xk(e){return D.join(Oi(e),"stderr")}function P2(e,t){return D.join(Yk(e),`${t}.log`)}function L2(e,t){return D.join(Xk(e),`${t}.log`)}function Jk(e){return D.join(Oi(e),"results")}function M2(e,t){return D.join(Jk(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]="aa7d04c7-b057-569c-816a-f53322c74261")}catch{}})();var _c=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!1}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d7d44fba-603b-5ef2-8490-51112b929433")}catch{}})();function Ni(e){return e.trim().toLowerCase().replaceAll("-","_")}function Qk(e){if(e===void 0)return;let t=Ni(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function yc(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)yc(n,t);return Object.freeze(e)}for(let n of Object.values(e))yc(n,t);return Object.freeze(e)}function Zk(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 eA(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function tA(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 nA(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=Ni(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 rA(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function oA(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}`)}function iA(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var hc=class{#e=new Map;#n=new Map;constructor(t=_c){for(let n of t)this.register(n)}register(t){let n=nA(t);if(rA(t,n),oA(t,n),Zk(t,n),eA(t,n),tA(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Qk(t.inverse),o=[...new Set((t.aliases??[]).map(Ni))].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,traversal:iA(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?yc(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=Ni(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 bc(){return new hc}var cn=bc();function U2(e){return cn.require(e).kind}function z2(e){return cn.resolve(e)?.kind}function q2(e,t=cn){return t.resolve(e)?.ordering===!0}function sA(e,t,n,r=cn){let o=Wr(e),i=Wr(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 Ii(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function aA(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=sA(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 Ri(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Wr(e){return typeof e=="string"?e.trim():""}function gc(e,t){let n=Wr(e);return n&&t.has(n)?n:void 0}function cA(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Sp=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=cn){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}=aA(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(Ii));for(let i of this.#r)Ri(this.#s,i.source,i),Ri(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(Ri(this.#s,i.target,i),Ri(this.#a,i.source,i))}static fromItems(t,n=cn){let r=new Set(t.map(i=>Wr(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Wr(i.id);if(!s)continue;let a=gc(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=gc(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let l of i.dependencies??[]){let d=gc(l.id,r);d&&n.resolve(l.kind)&&o.push({source:s,target:d,kind:l.kind,createdAt:l.created_at,author:l.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],l=a===void 0?c:c===void 0||Ii(a,c)<=0?a:c;o.at(-1)!==l&&o.push(l),a===l&&(i+=1),c===l&&(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)||Ii(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(p=>this.#e.require(p).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],l=[{id:t,depth:0}],d=0,u=0,f=!1;e:for(let p=0;p<l.length;p+=1){n.signal?.throwIfAborted();let _=l[p];d+=1;let y=this.#t(_.id,o,r);if(u+=y.length,_.depth>=s){y.some(b=>!a.has(b.id))&&(f=!0);continue}for(let b of y)if(!a.has(b.id)){if(c.length>=i){f=!0;break e}a.add(b.id),c.push(b.id),l.push({id:b.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:d,inspectedEdges:u,truncated:f,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(p=>this.#e.require(p).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,l=new Set([t]),d=0,u=0,f=!1;for(let p=0;p<a.length;p+=1){r.signal?.throwIfAborted();let _=a[p];d+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(b=>!l.has(b.id))&&(f=!0);continue}for(let b of y)if(!l.has(b.id)){if(c.set(b.id,_.id),b.id===n)return{value:cA(t,n,c),meta:{visitedNodes:d,inspectedEdges:u,truncated:!1}};l.add(b.id),a.push({id:b.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:d,inspectedEdges:u,truncated:f}}}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 l of this.#s.get(c)??[])i.has(l.source)&&i.has(l.target)&&this.#c(l,s)&&a.add(l);return{value:{nodes:o,edges:[...a].sort(Ii)},meta:r.meta}}};function V2(e,t,n=cn){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 Kr(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Pt(e){return tt.includes(e)}function xp(e){let t=e.trim().toLowerCase();return Pt(t)?t:null}function Cp(e){return e.filter(t=>!Pt(t))}function wc(e){let t=e.trim().toLowerCase();return t.length===0?null:Xa[t]??null}function Op(e){let t=Kr([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=wc(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:Kr(n),legacy_aliases:o}}function lA(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=wc(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 tt){let a=We(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function Ip(e,t,n){let r=tt.join(","),o=lA(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function Rp(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function dA(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(p=>p.trim()).filter(p=>p.length>0),l=wc(o),u=(s==="none"?void 0:s)??l??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ai,suggested_capability:u,suggestion_source:u?l===u?"legacy_alias":"nearest_match":void 0,legacy_alias_target:l??void 0}}function uA(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...tt],a=[];for(let c of o.split(",")){let[l,d]=c.split(">"),u=l?.trim(),f=d?.trim().toLowerCase();!u||!f||!Pt(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ai,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48fff41d-2667-50a1-bfbb-40908804babd")}catch{}})();function Yr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Ec(){return{overrides:[],handlers:[]}}function vc(){return{overrides:[]}}function Tc(){return{overrides:[]}}function kc(){return{overrides:[]}}function Ac(){return{overrides:[]}}function Di(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function X(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function fA(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function Ce(e){return e?j(e):{}}function Oe(e){return e?j(e):fA()}function j(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]="f7c79f37-1cae-59c9-b500-eb87d0089f94")}catch{}})();var pA=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),mA=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function _A(e,t){for(let n of mA){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=>pA.has(n)?X(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function gA(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=>X(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function yA(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.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>X(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function Sc(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(!_A(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 s=gA(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=yA(i);if(s===null)return null;n.preflight_ownership=s}return n}function Q2(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="49cea84c-1d1b-523b-8c98-7ac16c69ae82")}catch{}})();var hA=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function bA(e){return{unknownKeys:Object.keys(e).filter(t=>!hA.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function wA(e){let t=bA(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function Np(e,t,n){return wA(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import EA 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 vA(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 TA(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Pi(o))}return n}function Pi(e){let t=vA(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Pi(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Pi(r)}return TA(e)}function B(e){return JSON.stringify(Pi(e))}function Dp(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 kA(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function AA(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function SA(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(!Dp(o,n,r,ue))return!1;return!0}function xA(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(!Dp([o,i],n,r,([a,c],[l,d])=>ue(a,l)&&ue(c,d)))return!1;return!0}function CA(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)=>ue(n,t[r]))}function OA(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]||!ue(e[i],t[i]))return!1}return!0}var IA=[kA,AA,SA,xA,CA];function ue(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 IA){let r=n(e,t);if(r!==void 0)return r}return OA(e,t)}function Lt(e){return EA.createHash("sha256").update(e,"utf8").digest("hex")}function I(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]="d1dd5d4f-5f08-5e52-b109-d066f92ae3b3")}catch{}})();var RA=5e3;async function Xr(e,t,n){let r=[];for(let o of e)try{await o.run(j(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Pp(e,t){return Xr(e.beforeCommand,"beforeCommand",t)}function NA(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 h(`Extension mutation guard ${t.name} returned an invalid decision.`,g.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 h(`Extension mutation guard ${t.name} returned an invalid denial.`,g.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 h(s||`Extension mutation guard ${t.name} denied ${n}.`,g.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function xc(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:j(t.before),after:t.after===null?null:j(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 h(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,g.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},RA),o.unref?.()})])}catch(i){throw i instanceof h?i:new h(`Extension mutation guard ${n.name} failed before ${t.operation}.`,g.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)}NA(r,n,t.operation)}}async function Lp(e,t){return Xr(e.afterCommand,"afterCommand",t)}async function Cc(e,t){return Xr(e.onWrite,"onWrite",t)}async function Oc(e,t){return Xr(e.onRead,"onRead",t)}async function Ic(e,t){return Xr(e.onIndex,"onIndex",t)}function DA(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 Li(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 PA(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 Rc(e,t){let n=X(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:j(t.args),options:j(t.options),global:j(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",PA(o)],["errorCode",Li(o,"code")],["remediation",Li(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:DA(o),...Object.fromEntries([["errorCode",Li(o,"code")],["remediation",Li(o,"remediation")]].filter(s=>s[1]!==void 0))}}}async function Nc(e,t){let n=X(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:j(t.args),options:Ce(t.options),global:Oe(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:j(t.args),options:Ce(t.options),global:Oe(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:j(t.args),options:Ce(t.options),global:Oe(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)?j(o.args):j(t.args),s=o.options?Ce(o.options):Ce(t.options),a=o.global?Oe(o.global):Oe(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:j(t.args),options:Ce(t.options),global:Oe(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 Dc(e,t){let n={command:X(t.command),args:j(t.args),options:Ce(t.options),global:Oe(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},r=j(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:j(n.args),options:Ce(n.options),global:Oe(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:j(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?j(i.args):n.args,options:i.options?Ce(i.options):n.options,global:i.global?Oe(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Mp(e){return{handled:!1,result:e.payload,warnings:[]}}function Fp(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function $p(e){return{service:e.service,command:e.command?X(e.command):void 0,args:e.args?j(e.args):void 0,options:e.options?Ce(e.options):void 0,global:e.global?Oe(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:j(e.payload)}}function LA(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 jp(e,t){return LA(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 Up(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&ue(e,n.payload)}function zp(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function Pc(e,t){let n=Fp(e,t.service);if(n.length===0)return Mp(t);let r=[];for(let o of n)try{let i=$p(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(Up(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=zp(o,jp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function Lc(e,t){let n=Fp(e,t.service);if(n.length===0)return Mp(t);let r=[];for(let o of n)try{let i=$p(t),s=await Promise.resolve(o.run(i));if(Up(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=zp(o,jp(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function Mc(e,t){let n=X(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=Ce(t.options),i=Oe(t.global),s=r.run({command:n,args:j(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:j(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 MA(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(j(n))}catch{return!1}}function Fc(e,t){let n=typeof t.command=="string"?X(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&MA(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?j(t.args):[],i=Ce(t.options),s=Oe(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:j(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 pn from"node:fs/promises";import fn from"node:path";import{pathToFileURL as sS}from"node:url";import qp 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 $c(e,t){let n=qp.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!qp.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 Mi=Jn;function Fi(e){let t=e.trim().toLowerCase();return Mi.includes(t)?t:null}function Vp(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 Mi)if(We(t,r,n)!==null)return r;return null}import FA from"node:fs/promises";import Jr 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 Gp(e,t){let n=Jr.dirname(t.manifest_path),r=Jr.relative(n,t.entry_path);if(r.startsWith("..")||Jr.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=Jr.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await FA.cp(n,o,{recursive:!0,force:!0}),Jr.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 Bp(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]="065f61c6-2123-5a6d-984a-569bb14d6911")}catch{}})();function Hp(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return X(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function Wp(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a30142c8-b04d-5878-8497-c902ff299e94")}catch{}})();function Kp(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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 fe(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function te(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 Yp(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 ln(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 Qr(e,t){if(ln(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]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var jc=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="764d9a7d-90a2-578f-ab5d-bd0c039596df")}catch{}})();var $A=new Set(jc);function jA(e){if(e!==void 0&&!$A.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${jc.join(", ")}`)}function Xp(e){te("registerCommand definition.action",e.action),te("registerCommand definition.family",e.family),te("registerCommand definition.description",e.description),te("registerCommand definition.intent",e.intent),te("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");jA(e.family)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="057f439e-ac5c-5715-9fd0-4410e003d481")}catch{}})();function UA(e){let t=se("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return te("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function Jp(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=UA(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function Uc(e,t,n){return{registration:t,action:n,command:e.command,args:j(e.args),options:j(e.options),global:j(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="08ee7e43-8811-57ed-8bfe-0345ee5d3308")}catch{}})();var zc=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields"},{flag:"--output-limit",value_name:"count"},{flag:"--output-budget",value_name:"tokens"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state"},{flag:"--output-cursor",value_name:"cursor"},{flag:"--output-row-contract"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"]},{flag:"--no-extensions"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"}]),qc=new Set(zc.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 zA=/^--[a-z0-9][a-z0-9_-]*(?:[ =](?:<[^<>]+>|\[[^[\]]+\]))?$/;function qA(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return qc.has(n)?"host_owned_flag_collision":zA.test(t)?null:"malformed_long_flag"}function Qp(e,t){let n=[e,t].find(i=>typeof i=="string"&&qc.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=qA(r);return o===null?null:{token:r,failure:o}}function Zp(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 em(e){return typeof e=="string"?e:String(e)}function Zr(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 Vc(e,t){let n=Zr(e),r=Zr(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 tm(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=em(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!Zr(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=Vc(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 nm(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=em(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())||!Zr(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=Vc(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 Fe(e){return typeof e!="string"?"":e.trim().toLowerCase()}function U(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function VA(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 er(e){return new Set((e??[]).map(t=>VA(t)).filter(t=>t.length>0))}function rm(e){let t=Fe(e);return ci.includes(t)?t:"off"}function om(e){let t=Fe(e);return li.includes(t)?t:"off"}function eo(e){let t=Fe(e);return di.includes(t)?t:"none"}function Gc(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Hf.includes(t)?t:void 0}function im(e){if(typeof e=="string"){let t=Gc(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:Gc(e.global)??"block",project:Gc(e.project)??"block"}:{global:"block",project:"block"}}function GA(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function H(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function BA(e){let t=Fe(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?eo(e.sandbox_profile):void 0,allowedCapabilities:U(e.allowed_capabilities),blockedCapabilities:U(e.blocked_capabilities),allowedSurfaces:er(e.allowed_surfaces),blockedSurfaces:er(e.blocked_surfaces),allowedCommands:U(e.allowed_commands),blockedCommands:U(e.blocked_commands),allowedActions:U(e.allowed_actions),blockedActions:U(e.blocked_actions),allowedServices:U(e.allowed_services),blockedServices:U(e.blocked_services)}}}function sm(e){let t=new Map;for(let n of e??[]){let r=BA(n);r&&t.set(r.name,r.normalized)}return t}function HA(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of H([...e.allowedCapabilities,...e.blockedCapabilities]))Pt(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of H([...o.allowedCapabilities,...o.blockedCapabilities]))Pt(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(ui);for(let o of H([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of H([...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 am(e){let t=e.extensions?.policy??{},n=U(t.allowed_capabilities),r=U(t.blocked_capabilities),o=er(t.allowed_surfaces),i=er(t.blocked_surfaces),s=sm(t.extension_overrides);return{mode:rm(t.mode),trustMode:om(t.trust_mode),pmMaxVersionExceededMode:im(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:U(t.trusted_extensions),defaultSandboxProfile:eo(t.default_sandbox_profile),allowedExtensions:U(t.allowed_extensions),blockedExtensions:U(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:U(t.allowed_commands),blockedCommands:U(t.blocked_commands),allowedActions:U(t.allowed_actions),blockedActions:U(t.blocked_actions),allowedServices:U(t.allowed_services),blockedServices:U(t.blocked_services),overridesByName:s,warnings:HA({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function cm(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:H(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:H(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:H(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:H(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:H(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:H(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:H(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:H(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:H(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:H(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:GA(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:H(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:H(e.allowedExtensions),blocked_extensions:H(e.blockedExtensions),allowed_capabilities:H(e.allowedCapabilities),blocked_capabilities:H(e.blockedCapabilities),allowed_surfaces:H(e.allowedSurfaces),blocked_surfaces:H(e.blockedSurfaces),allowed_commands:H(e.allowedCommands),blocked_commands:H(e.blockedCommands),allowed_actions:H(e.allowedActions),blocked_actions:H(e.blockedActions),allowed_services:H(e.allowedServices),blocked_services:H(e.blockedServices),extension_overrides:t}}function lm(e){let t=sm(e.extension_overrides);return{mode:rm(e.mode),trustMode:om(e.trust_mode),pmMaxVersionExceededMode:im(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:U(e.trusted_extensions),defaultSandboxProfile:eo(e.default_sandbox_profile),allowedExtensions:U(e.allowed_extensions),blockedExtensions:U(e.blocked_extensions),allowedCapabilities:U(e.allowed_capabilities),blockedCapabilities:U(e.blocked_capabilities),allowedSurfaces:er(e.allowed_surfaces),blockedSurfaces:er(e.blocked_surfaces),allowedCommands:U(e.allowed_commands),blockedCommands:U(e.blocked_commands),allowedActions:U(e.allowed_actions),blockedActions:U(e.blocked_actions),allowedServices:U(e.allowed_services),blockedServices:U(e.blocked_services),overridesByName:t,warnings:[]}}function Mt(e,t){return e.overridesByName.get(Fe(t))??null}function tr(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function dm(e,t,n){let r=n.trim().toLowerCase(),o=Mt(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return tr(i,s,r,"capability_not_allowlisted","capability_blocked")}function WA(e,t,n){let r=Mt(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return tr(o,i,n,"surface_not_allowlisted","surface_blocked")}function KA(e,t,n){let r=X(n);if(r.length===0)return null;let o=Mt(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return tr(i,s,r,"command_not_allowlisted","command_blocked")}function YA(e,t,n){let r=Fe(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Mt(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return tr(i,s,r,"action_not_allowlisted","action_blocked")}function XA(e,t,n){let r=Fe(n);if(r.length===0)return null;let o=Mt(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return tr(i,s,r,"service_not_allowlisted","service_blocked")}function JA(e,t){let n=Fe(t.name);return Mt(e,t.name)?.disabled===!0?"extension_override_disabled":tr(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function QA(e,t){if(e.trustMode==="off")return null;let n=Mt(e,t.name),r=Fe(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 ZA(e,t){if(e.mode==="off")return null;let r=Mt(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 $i(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 um(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=JA(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=QA(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=ZA(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:$i("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:$i("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function fm(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=dm(e,t,n);return r?{allowed:e.mode==="warn",warning:$i(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function eS(e,t,n,r,o){let i=typeof r=="string"?dm(e,t,r):null,s=WA(e,t,n),a=o.command?KA(e,t,o.command):null,c=o.action?YA(e,t,o.action):null,l=o.service?XA(e,t,o.service):null;return i??s??a??c??l}function tS(e,t,n,r){let o={method:Fe(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=X(r.command)),r.action&&(o.action=Fe(r.action).replace(/\s+/g,"-")),r.service&&(o.service=Fe(r.service)),o}function pm(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=eS(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=$i(e.mode==="warn"?"violation":"blocked","registration",t,a,tS(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]="7316b9ef-38e1-5ee0-9107-da15ec7804d4")}catch{}})();function mm(e){return e==="toon"||e==="json"}function _m(e){return Gn.includes(e)}function dn(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var gm=Symbol("extension_registration_trace");function ht(e,t){let n=new TypeError(e);return Object.defineProperty(n,gm,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function ym(e){return e instanceof Error?e[gm]:void 0}function to(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>to(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={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=to(t[r]);return n}return e}function no(e){if(Array.isArray(e))return e.map(t=>no(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]=no(t[r]);return n}return e}function nr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return to(t)}function ro(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return no(t)}function ji(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>nr(e,n))}function Ee(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function oo(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function Bc(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Hc(e,t){return X(`${e} ${t}`)}function io(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var nS=new Set(["low","medium","high"]),rS=new Set(["number","string_set"]),oS=new Set(["string","number","boolean"]);function hm(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function iS(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=se(r,n);if(!rS.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(te(`${r}.description`,o.description),o.parameters===void 0)return;let i=se(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;hm(`${c}.name`,s);let l=se(c,a);if(!oS.has(String(l.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);fe(`${c}.required`,l.required),te(`${c}.description`,l.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function bm(e){let t=se("registerAssuranceMeasurementProvider provider",e),n=hm("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!nS.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=se("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);iS(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8725b7dd-ec6f-5c71-897a-7a84ce93f5f0")}catch{}})();function wm(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]="e4e1b7c2-6551-5e56-b26a-30062aed5b97")}catch{}})();var aS=100,Em=null,cS=Object.freeze(fi()),vm=0;function lS(e=Date.now()){return vm+=1,`${vm}-${e}`}function Tm(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function dS(e){if(e==null)return;let t=an(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 Wc(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Nm(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function un(e){if(e!=null)return typeof e!="boolean"?null:e}function uS(e){let t=Nm(e.priority);return t===void 0?aS:t}function fS(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=eo(t);return n!==t.trim().toLowerCase()?null:n}function Kc(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function pS(e){if(e==null)return;let t=an(e);if(!t)return null;let n=Kc(t.source),r=Kc(t.signature),o=Kc(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 mS(e){if(e==null)return;let t=an(e);if(!t)return null;let n=un(t.fs_read),r=un(t.fs_write),o=un(t.network),i=un(t.env_read),s=un(t.env_write),a=un(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 _S(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=Op(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function gS(e){if(e==null)return;let t=an(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=>X(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function yS(e){let t=Nm(e.manifest_version);if(t===null)return null;let n=Tm(e,"pm_min_version");if(n===null)return null;let r=Tm(e,"pm_max_version");if(r===null)return null;let o=dS(e.engines);if(o===null)return null;let i=un(e.trusted);if(i===null)return null;let s=fS(e);if(s===null)return null;let a=pS(e.provenance);if(a===null)return null;let c=mS(e.permissions);if(c===null)return null;let l=_S(e.capabilities);if(l===null)return null;let d=gS(e.activation);if(d===null)return null;let u=Sc(e.contributions);return u===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:l.capabilities,legacy_capability_aliases:l.legacy_aliases,activation:d,contributions:u}}function hS(e){if(typeof e!="object"||e===null)return null;let t=e,n=Wc(t,"name");if(n===null)return null;let r=Wc(t,"version");if(r===null)return null;let o=Wc(t,"entry");if(o===null)return null;let i=uS(t);if(i===null)return null;let s=yS(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 bS(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function wS(e,t){let[n,r]=await Promise.all([pn.realpath(e),pn.realpath(t)]);return $c(n,r)}function Dm(e,t=process.cwd()){return{global:fn.join(Dt(t),"extensions"),project:fn.join(e,"extensions")}}async function ES(e){try{return(await pn.readdir(e,{withFileTypes:!0})).filter(n=>n.isDirectory()).map(n=>n.name).sort((n,r)=>n.localeCompare(r))}catch{return[]}}function vS(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 km(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function TS(e){let t=new Map;try{let n=JSON.parse(await pn.readFile(fn.join(e,".managed-extensions.json"),"utf8")),o=an(n)?.entries;if(!Array.isArray(o))return t;for(let i of o){if(typeof i!="object"||i===null)continue;let s=i,a=km(s.source?.package),c=[s.source?.input,s.source?.name,a].map(u=>km(u)).filter(u=>u!==void 0),l=Sc(s.contributions),d={aliases:[...new Set(c)],...a?{package_name:a}:{},...l?{contributions:l}:{}};typeof s.directory=="string"&&s.directory.trim().length>0&&t.set(`directory:${s.directory.trim()}`,d),typeof s.name=="string"&&s.name.trim().length>0&&t.set(`name:${s.name.trim()}`,d)}}catch{return t}return t}function Am(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 kS(e,t){let n=[...Am(e),...Am(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 Sm(e,t,n,r,o){let i=[],s=[],a=[],c=await ES(t),l=await TS(t);for(let d of c){let u=await xS(e,t,d,n,r,l,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function AS(){return{diagnostics:[],warnings:[],candidates:[]}}function xm(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 SS(e,t,n,r,o,i,s){let a=Np(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&a.push(Rp(e,t.name,t.legacy_capability_aliases));for(let c of Cp(t.capabilities))a.push(Ip(e,t.name,c));return r?o||a.push(`extension_entry_missing:${e}:${t.name}`):a.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&a.push(i.warning),s.warning&&a.push(s.warning),a}async function xS(e,t,n,r,o,i,s){let a=fn.join(t,n),c=fn.join(a,"manifest.json");if(!await ee(c))return xm(e,n,c,`extension_manifest_missing:${e}:${n}`);let l,d;try{let F=JSON.parse(await pn.readFile(c,"utf8"));d=an(F),l=hS(F)}catch{d=null,l=null}if(!l||!d)return xm(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=fn.resolve(a,l.entry),f=$c(a,u),p=f?await ee(u):!1,_=f&&p?await wS(a,u):f,y=bS(l.name,r,o),b=await OS(e,l),E=await IS(e,l,s),T=SS(e,l,d,_,p,b,E),O=_&&p&&b.allowed&&E.allowed,P=i.get(`directory:${n}`)??i.get(`name:${l.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:l.name,version:l.version,entry:l.entry,priority:l.priority,entry_path:u,enabled:y,status:O?"ok":"warn"},warnings:T,candidate:wm({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:l,sourceIdentity:P,extensionReady:O,enabledForLoad:y})}}async function Pm(e){let t=Dm(e.pmRoot,e.cwd??process.cwd()),n=Kr(e.settings.extensions.enabled),r=Kr(e.settings.extensions.disabled),o=am(e.settings),i=cm(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?AS():await Sm("global",t.global,s,a,o.pmMaxVersionExceededMode.global),l=await Sm("project",t.project,s,a,o.pmMaxVersionExceededMode.project),d=[...o.warnings],u=kS(c.candidates,l.candidates),f=[];for(let p of u){let _={layer:p.layer,name:p.manifest.name,trusted:p.manifest.trusted===!0,provenanceVerified:p.manifest.provenance?.verified===!0,sandboxProfile:p.manifest.sandbox_profile,permissions:p.manifest.permissions&&typeof p.manifest.permissions=="object"?{fs_read:p.manifest.permissions.fs_read,fs_write:p.manifest.permissions.fs_write,network:p.manifest.permissions.network,env_read:p.manifest.permissions.env_read,env_write:p.manifest.permissions.env_write,process_spawn:p.manifest.permissions.process_spawn}:void 0},y=um(o,_);if(y.warning&&d.push(y.warning),!!y.allowed){for(let b of p.manifest.capabilities){let E=fm(o,_,b);E.warning&&d.push(E.warning)}f.push(vS(p))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...l.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...l.warnings,...d])],policy:i}}function Ui(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function CS(){try{let e=yt(import.meta.url,["../../.."]),t=await pn.readFile(fn.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 Lm(){return Em??=CS(),Em}function Mm(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 OS(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=tm(t.pm_min_version,await Lm()),r=Mm(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function IS(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=nm(t.pm_max_version,await Lm(),n),o=Mm(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Cm(e){try{let t=await pn.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function RS(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Gp(t.module_graph_snapshot_root,e));let r=new URL(sS(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[i,s]=await Promise.all([Cm(e.entry_path),Cm(e.manifest_path)]),a=t.reload_token??lS();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 NS(e){let t=await Pm(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 RS(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:Ui(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Om=5e3,DS=2147483647;function PS(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 Fm(e){let t=Jf(e);return t?PS(t):null}async function yG(e,t,n={}){let r=LS(n?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(d=>`${d.layer}:${d.name}`)),i=[];for(let d of e.loaded){if(o.has(`${d.layer}:${d.name}`))continue;let u=Fm(d.module);!u||typeof u.deactivate!="function"||i.push({extension:d,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:d,deactivate:u})=>{try{return await MS(u,r),{ok:!0}}catch(f){return{ok:!1,layer:d.layer,name:d.name,error:Ui(f)}}})),a=[],c=[],l=0;for(let d of s){if(d.ok){l+=1;continue}a.push(`extension_deactivate_failed:${d.layer}:${d.name}`),c.push({layer:d.layer,name:d.name,error:d.error})}return{deactivated:l,warnings:a,failed:c}}function LS(e){return typeof e!="number"||e<0?Om:e===0||e===1/0?0:Number.isFinite(e)?Math.min(DS,Math.max(1,Math.floor(e))):Om}async function MS(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)}}var FS=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","visible"]);function Yc(e,t){return ji(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function $S(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function Im(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=$S(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function Rm(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=Ee(`registerCommand definition.arguments[${r}].name`,i.name);if(fe(`registerCommand definition.arguments[${r}].required`,i.required),fe(`registerCommand definition.arguments[${r}].variadic`,i.variadic),te(`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 Xc(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=>!FS.has(c)).sort((c,l)=>c.localeCompare(l));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`);te(`registerFlags flags[${t}].long`,i),te(`registerFlags flags[${t}].short`,s);let a=Qp(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${Zp(a.token,a.failure)}`);if(te(`registerFlags flags[${t}].value_name`,r.value_name),te(`registerFlags flags[${t}].description`,r.description),fe(`registerFlags flags[${t}].required`,r.required),fe(`registerFlags flags[${t}].enabled`,r.enabled),fe(`registerFlags flags[${t}].visible`,r.visible),fe(`registerFlags flags[${t}].list`,r.list),fe(`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(Yp(`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.`);jS(`registerFlags flags[${t}]`,r)}}function jS(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=ic(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?sc(t.default):[t.default];for(let[i,s]of o.entries())if(!sp(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function US(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);Ee(`registerItemFields fields[${t}].name`,r.name);let o=Ee(`registerItemFields fields[${t}].type`,r.type);if(Fi(o)===null){let i=Vp(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Mi.join(", ")}).${s}`)}fe(`registerItemFields fields[${t}].optional`,r.optional)}}function zS(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);Ee(`${i}.command`,s.command),Ee(`${i}.option`,s.option),fe(`${i}.enabled`,s.enabled),fe(`${i}.required`,s.required),fe(`${i}.visible`,s.visible)}}function qS(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);Ee(`${i}.key`,s.key),ln(`${i}.values`,s.values),fe(`${i}.required`,s.required),ln(`${i}.aliases`,s.aliases)}}function VS(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);Ee(`${r}.name`,o.name),te(`${r}.folder`,o.folder),ln(`${r}.aliases`,o.aliases),ln(`${r}.required_create_fields`,o.required_create_fields),ln(`${r}.required_create_repeatables`,o.required_create_repeatables),zS(t,o.command_option_policies),qS(t,o.options)}}function GS(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(fe("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 $m=["types","statuses","fields","workflows","config","templates","packages"],BS={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 HS(e){let t=se("registerProfile profile",e);if(Ee("registerProfile profile.name",t.name),Ee("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let n of $m){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`);BS[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function WS(e){e.summary===void 0&&(e.summary="");for(let t of $m)e[t]===void 0&&(e[t]=[]);return e}function KS(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Pt(r)&&t.add(r)}return t}function J(e,t,n){let r=KS(e);if(r!==null&&!r.has(t))throw ht(`${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 YS(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>tt.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function XS(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 Jc=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#l;#d;#u;constructor(t,n,r,o,i,s,a,c,l,d,u){this.#e=t,this.extension=YS(t),this.#n=XS(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#l=l,this.#d=d,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=pm(this.#u,this.#n,t,n,r,o);return i.warning&&this.#l.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:to(o),hint:i}}registerCommandOverride(t,n){let r=X(t);if(r.length===0)throw ht("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 ht(`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.#l.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 ht("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 ht("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=X(t.name);if(n.length===0)throw ht("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 ht(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{Xp(t);let o=Im(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=Qr("registerCommand definition.examples",t.examples),c=Qr("registerCommand definition.failure_hints",t.failure_hints),l=Rm(t.arguments);t.flags!==void 0&&(J(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(Xc(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Yc("registerCommand definition.flags",t.flags)})));let d={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:a,failure_hints:c,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};i&&(d.description=i),s&&(d.intent=s),this.#t.commands.push(d)}catch(o){let i=Ui(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=ht(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#l.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#d.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(J(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(J(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=X(Ee("registerParser command",t));oo("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(J(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Hp(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){J(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!_m(o))throw new TypeError(`registerService service must be one of: ${Gn.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(oo("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...Kp(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(J(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(!mm(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 X(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(J(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=X(Ee("registerFlags targetCommand",t));Xc(n);let o=Yc("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(J(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;US(t);let n=ji("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(J(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;VS(t);let n=ji("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(J(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=bc();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(J(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;GS(t);let n=ro("registerMigration definition",t);this.#t.migrations.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerMigration definition",t)},n))}registerProfile(t){if(J(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=no(t);HS(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:WS(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(J(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(Xc(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Yc(`${t} options.flags`,r.flags)})))}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},a=Jp(t,s,r?.description!==void 0);te(`${t} options.action`,s.action),te(`${t} options.description`,s.description),te(`${t} options.intent`,s.intent);let c=Im(n,s.action),l=Qr(`${t} options.examples`,s.examples),d=Qr(`${t} options.failure_hints`,s.failure_hints),u=Rm(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:l,failure_hints:d,arguments:u},p=s.description?.trim();p&&(f.description=p);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,n,r){if(J(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=Bc(Ee("registerImporter name",t));oo("registerImporter importer",n);let i=Hc(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(Uc(s,o,"import"))})}registerExporter(t,n,r){if(J(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=Bc(Ee("registerExporter name",t));oo("registerExporter exporter",n);let i=Hc(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(Uc(a,o,"export"));return s?.receipt==="suppress"&&!hi(c)?cp(c):c}})}registerSearchProvider(t){if(J(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=ro("registerSearchProvider provider",t);this.#t.search_providers.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(J(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=ro("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(io({layer:this.#e.layer,name:this.#e.name,definition:nr("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(J(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(bm(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=ro("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(io({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:nr("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){J(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(dn("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){J(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(dn("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){J(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(dn("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){J(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(dn("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){J(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(dn("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){J(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(dn("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function JS(e,t,n,r,o,i,s,a,c,l,d){return new Jc(e,t,n,r,o,i,s,a,c,l,d)}function QS(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,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function ZS(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let l=a.get(c.command)??[];l.push(c),a.set(c.command,l)}for(let c of[...a.keys()].sort((l,d)=>l.localeCompare(d))){let l=a.get(c);if(l.length<=1)continue;let d=l[l.length-1];for(let u of l.slice(0,-1))t.push(`${s}:${c}:${d.layer}:${d.name}:${u.layer}:${u.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 l of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${l.layer}:${l.name}`)}return t}function ex(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 tx(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}var nx=new Set(["output_format"]);function rx(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||nx.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 ox(e){let t=lm(e.policy??cS),n=Yr(),r=Ec(),o=vc(),i=Tc(),s=kc(),a=Ac(),c=Di(),l=[],d=[];for(let p of e.loaded){let _=Fm(p.module);if(!_)continue;let y=l.length,b=Bp({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(JS(p,n,r,o,i,s,a,c,d,l,t)),l.length>y&&(b(),d.push(`extension_activation_rolled_back:${p.layer}:${p.name}`))}catch(E){b(),d.push(`extension_activate_failed:${p.layer}:${p.name}`);let T=ym(E);l.push({layer:p.layer,name:p.name,entry_path:p.entry_path,error:Ui(E),trace:T})}}let u=[...ZS(r),...tx(o),...Wp(i),...rx(s),...ex(a)],f=[...new Set([...d,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:l,warnings:f,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:QS(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 ix(e){return{...e,hooks:Yr(),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 AG(){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 jm(){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]="a35f3cdc-810e-59bd-8408-03ce792db57f")}catch{}})();var sx={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},Um=":";function zm(e,t){return`${e}${Um}${Qc(t)}`}function ax(e){return e.slice(e.indexOf(Um)+1)}function Qc(e){return e.trim().toLowerCase()}function cx(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=xp(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function qm(e){let t=new Map,n=(d,u)=>{for(let f of d){let p=zm(f.layer,f.name),_=t.get(p);_===void 0&&(_=new Set,t.set(p,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:l}=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(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(l.beforeCommand,"hooks"),n(l.beforeMutation,"hooks"),n(l.afterCommand,"hooks"),n(l.onWrite,"hooks"),n(l.onRead,"hooks"),n(l.onIndex,"hooks"),t}function lx(e,t={}){let n=qm(e),r=new Set;t.extensionName!==void 0&&r.add(Qc(t.extensionName));for(let i of t.extensionNames??[])r.add(Qc(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(ax(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function dx(e,t){let n=qm(t),r=[];for(let o of e){let i=cx(o.capabilities);if(i.length===0)continue;let s=n.get(zm(o.layer,o.name))??new Set,a=[...s].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>!s.has(l));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as ux}from"node:fs";import{AsyncLocalStorage as fx}from"node:async_hooks";import bt 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 Ft=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,mn=null,Hi,zi=[],Gm=new fx;function V(){return Gm.getStore()}function DG(e){return Gm.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var px=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Vm(e){let t=bt.resolve(e);for(;;){if(ux(bt.join(t,".git")))return t;let n=bt.dirname(t);if(n===t)return;t=n}}function Wi(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=Vm(t)??bt.resolve(t),r=Vm(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=bt.relative(n,bt.resolve(e)),i=o.length>0&&!o.startsWith(`..${bt.sep}`)&&o!==".."&&!bt.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(bt.sep).join("/")}:{}}}function mx(e){let t=V();if(t){t.hooks=e;return}Ft=e}function _x(e){let t=V();if(t){t.commands=e;return}so=e}function gx(e){let t=V();if(t){t.parsers=e;return}qi=e}function yx(e){let t=V();if(t){t.preflight=e;return}Vi=e}function hx(e){let t=V();if(t){t.services=e;return}ao=e}function bx(e){let t=V();if(t){t.renderers=e;return}Gi=e}function wx(e){let t=V();if(t){t.registrations=e;return}Bi=e}function $t(){let e=V();return e?e.registrations:Bi}function Ex(){let e=V();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}Ft=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,mn=null,Hi=null}function vx(e){let t=e?{...e,...Wi(e.pm_root)}:null,n=V();if(n){n.commandContext=t;return}mn=t}function Bm(){let e=V(),t=e?e.commandContext:mn;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function rr(e){let t=V();if(t){t.commandResult=e;return}Hi=e}function Tx(){let e=V();return e?e.commandResult:Hi}function Ki(e){if(!e)return;let t=V();t?t.affectedItems.push(e):zi.push(e)}function co(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"||px.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function kx(){let e=V(),t=e?.affectedItems??zi;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:zi=[],n}function Ax(){let e=V();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}Ft=null,so=null,qi=null,Vi=null,ao=null,Gi=null,Bi=null,mn=null,Hi=void 0,zi=[]}async function ye(e){let t=V(),n=t?t.hooks:Ft;return n?Cc(n,e):[]}async function Yi(e){let t=V(),n=t?t.hooks:Ft;n&&await xc(n,e)}async function Ke(e){let t=V(),n=t?t.hooks:Ft;return n?Oc(n,e):[]}function Zc(){let e=V();return((e?e.hooks:Ft)?.onRead?.length??0)>0}async function Sx(e){let t=V(),n=t?t.hooks:Ft;return n?Ic(n,e):[]}function Hm(e){let t=V(),n=t?t.commands:so,r=t?t.commandContext:mn;return!n||!r?{overridden:!1,result:e,warnings:[]}:Mc(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 xx(e){let t=V(),n=t?t.commands:so;return n?Rc(n,{...e,...Wi(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function Cx(e){let t=V(),n=t?t.parsers:qi;return n?Nc(n,{...e,...Wi(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 Ox(e){let t=V(),n=t?t.preflight:Vi;return n?Dc(n,{...e,...Wi(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 Wm(e,t){let n=V(),r=n?n.renderers:Gi,o=n?n.commandContext:mn;return r?Fc(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 Km(e,t){let n=V(),r=n?n.commandContext:mn;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 $e(e,t){let n=V(),r=n?n.services:ao;return r?Lc(r,Km(e,t)):{handled:!1,result:t,warnings:[]}}function el(e,t){let n=V(),r=n?n.services:ao;return r?Pc(r,Km(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 _n=new Set(Me),Xi=Object.freeze({get size(){return _n.size},has(e){return _n.has(e)},entries(){return _n.entries()},keys(){return _n.keys()},values(){return _n.values()},forEach(e,t){_n.forEach(n=>e.call(t,n,n,Xi))},[Symbol.iterator](){return _n.values()}});function Ym(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Xm(e){return typeof e!="string"?null:Fi(e)}function Ix(e){try{return structuredClone(e)}catch{return e}}function Rx(e){let t=e.trim(),n=t.indexOf("=");if(n<=0)throw new h(`--field entries must use name=value syntax, received: ${e}`,g.USAGE);let r=t.slice(0,n).trim(),o=t.slice(n+1);return{key:r,value:o}}function Nx(e){return`--${e.replaceAll("_","-")}`}function Dx(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 h(`--field ${t}=... must be valid JSON ${n}`,g.USAGE)}function Px(e,t,n){if(t==="string")return n;if(t==="number"){let r=n.trim();if(r.length===0)throw new h(`--field ${e}=... must be a number`,g.USAGE);let o=Number(r);if(!Number.isFinite(o))throw new h(`--field ${e}=... must be a number`,g.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 h(`--field ${e}=... must be one of true|false|1|0|yes|no`,g.USAGE)}return t==="string_array"?n.split(/[\n,|]/u).map(r=>r.trim()).filter(r=>r.length>0):Dx(n,e,t)}function tl(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Ym(r.name),i=Xm(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new h(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,g.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 Jm(e){if(Xi.has(e))throw new h(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...Xi].sort((t,n)=>t.localeCompare(n)).join(", ")}.`,g.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function lo(e){return[...tl(e).keys()].sort((t,n)=>t.localeCompare(n))}function Lx(e,t){if(!e||e.length===0)return{};let n=tl(t),r={};for(let o of e){let{key:i,value:s}=Rx(o),a=n.get(i);if(!a){if(Xi.has(i)){let l=Nx(i);throw new h(`--field ${i} is a core item field, not an extension field`,g.USAGE,{code:"core_item_field_requires_dedicated_flag",field:i,recovery:{provided_fields:[i],suggested_flags:[l]},nextSteps:[`Set the core field with its dedicated flag: pm update <id> ${l} <value>`,`When closing an item, pm close <id> also accepts ${l} <value>.`]})}let c=[...n.keys()].sort((l,d)=>l.localeCompare(d));throw new h(`--field ${i} is not declared by an active extension item-field registration`,g.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."]})}Jm(a.name),r[a.name]=Px(a.name,a.type,s)}return r}function Mx(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 Fx(e,t){return!t||t.length===0?!0:t.some(n=>Object.is(n,e))}function $x(e,t,n={}){if(t){tl(t);for(let r of t.item_fields)for(let o of r.fields){let i=Ym(o.name);if(!i)continue;Jm(i),!(i in e)&&!n.skipDefaultFields?.has(i)&&Object.prototype.hasOwnProperty.call(o,"default")&&(e[i]=Ix(o.default));let s=e[i];if(s===void 0)continue;let a=Xm(o.type);if(a&&!Mx(s,a))throw new TypeError(`Item field "${i}" must be of type ${a}`);let c=Array.isArray(o.values)?o.values:void 0;if(!Fx(s,c))throw new TypeError(`Item field "${i}" must match one of the configured allowed values`)}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}catch{}})();function jt(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t.length>0?t:null}function VG(e,t){let n=jt(t);return!e||!n?null:[...e.assurance_providers??[]].reverse().find(r=>jt(r.definition.id)===n)??null}function jx(e,t){let n=jt(t);return!e||!n?null:[...e.search_providers].reverse().find(o=>(jt(o.runtime_definition?.name)??jt(o.definition?.name))===n)??null}function Ux(e,t){let n=jt(t);return!e||!n?null:[...e.vector_store_adapters].reverse().find(o=>(jt(o.runtime_definition?.name)??jt(o.definition?.name))===n)??null}function GG(e){return e.runtime_definition??e.definition}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var wt="-",Zm=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function KG(e,t){if(e.startsWith("```")||e.includes(`
5
+ `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)}function e_(e){let t=e.trim();if(t==="")return[];let r=(Bx(t)??t.split(",")).map(o=>o.trim()).filter(Boolean).map(o=>o.toLowerCase());return Array.from(new Set(r)).sort((o,i)=>o.localeCompare(i))}function t_(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of e_(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function n_(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function zx(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function qx(e,t,n){let r=e.map(s=>s.trim()).filter(Boolean);for(let s of t??[]){let a=s.trim();if(a.includes(";"))throw new h('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',g.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});a.length>0&&!r.includes(a)&&r.push(a)}let o=[],i=r;for(let s of n??[]){let a=s.trim();if(a.length!==0){if(!i.includes(a)){o.push(a);continue}i=i.filter(c=>c!==a)}}return{criteria:i,unmatchedRemovals:o}}function Vx(e,t){let n=n_(e);if(!t||t.length===0)return Array.from(new Set(n)).sort((o,i)=>o.localeCompare(i));let r=new Set(n);for(let o of t_(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function Gx(e,t){let n=Array.from(new Set(n_(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(t_(t));return r.size===0?n:n.filter(o=>!r.has(o))}function Bx(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"").filter(r=>r.length>0)}function nl(e){return e.replace(/\r\n/g,`
6
+ `)}function r_(e){let t=nl(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
7
7
  `);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
8
- `)}function Gx(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&e[o+1]===","){n+=",",o+=1;continue}if(i==="\\"&&e[o+1]!==void 0){n+=`${i}${e[o+1]}`,o+=1;continue}if(i==='"'){r=!r,n+=i;continue}if(i===","&&!r){t.push(n),n="";continue}n+=i}return n.trim()&&t.push(n),t}function o_(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function Bx(e){let t=e.indexOf("="),n=e.indexOf(":"),r=t>=0,o=n>=0;return r&&o?Math.min(t,n):r?t:o?n:-1}function Hx(e,t){if((t==="--add"||t==="--add-glob")&&(/[./\\]/.test(e)||/\.[a-z]{1,6}$/i.test(e.trim())))return"For file/doc paths use: path=<file-path>[,scope=project|global]. The scope field is optional and defaults to project (example: path=src/api.ts or path=README.md,scope=project). ";if(t!=="--event")return"";let n=e.toLowerCase(),r=n.includes("recur_")||n.includes("recurrence")?' Recurrence list values must stay in one field and use "|" delimiters (for example recur_by_weekday=mon|wed or recur_by_month_day=1|15).':"",o=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${r}${o}`}function Qm(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=Hx(e,t);return`Invalid ${t} value "${r}". Expected key=value entries separated by commas. `+o+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${t} ${yt} to read piped stdin input.`}function Wx(e){let t=r_(e).trim();if(t.length===0||!t.includes(`
9
- `)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=rl(t).split(`
8
+ `)}function Hx(e){let t=[],n="",r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(i==="\\"&&e[o+1]===","){n+=",",o+=1;continue}if(i==="\\"&&e[o+1]!==void 0){n+=`${i}${e[o+1]}`,o+=1;continue}if(i==='"'){r=!r,n+=i;continue}if(i===","&&!r){t.push(n),n="";continue}n+=i}return n.trim()&&t.push(n),t}function o_(e){let t=e.trim();if(t.startsWith('"')&&t.endsWith('"')){try{let n=JSON.parse(t);if(typeof n=="string")return n}catch{}return t.slice(1,-1).replace(/\\"/g,'"')}return e}function Wx(e){let t=e.indexOf("="),n=e.indexOf(":"),r=t>=0,o=n>=0;return r&&o?Math.min(t,n):r?t:o?n:-1}function Kx(e,t){if((t==="--add"||t==="--add-glob")&&(/[./\\]/.test(e)||/\.[a-z]{1,6}$/i.test(e.trim())))return"For file/doc paths use: path=<file-path>[,scope=project|global]. The scope field is optional and defaults to project (example: path=src/api.ts or path=README.md,scope=project). ";if(t!=="--event")return"";let n=e.toLowerCase(),r=n.includes("recur_")||n.includes("recurrence")?' Recurrence list values must stay in one field and use "|" delimiters (for example recur_by_weekday=mon|wed or recur_by_month_day=1|15).':"",o=n.includes("recur_byweekday")?" Use recur_by_weekday (with underscores) for weekday recurrence filters.":"";return`${r}${o}`}function Qm(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=Kx(e,t);return`Invalid ${t} value "${r}". Expected key=value entries separated by commas. `+o+`Also accepts markdown-style key/value lines (for example "- path: README.md"). Use ${t} ${wt} to read piped stdin input.`}function Yx(e){let t=r_(e).trim();if(t.length===0||!t.includes(`
9
+ `)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=nl(t).split(`
10
10
  `).map(i=>i.trim()).filter(i=>i.length>0);for(let i of o){let s=i.match(/^(?:[-*+]\s+)?([a-zA-Z0-9_.-]+)\s*(=|:)\s*(.*)$/);if(s){let a=s[1].trim();n[a]=o_(s[3].trim()),r=a;continue}if(r&&Zm.has(r.toLowerCase())){n[r]=`${n[r]}
11
- ${i}`;continue}return null}return n}function Kx(e,t){let n=r_(e).trim();if(!n)throw new h(`${t} cannot be empty`,g.USAGE);let r=Wx(n);if(r)return r;let o={},i,s=Gx(n);for(let a of s){let c=Bx(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new h(Qm(e,t),g.USAGE);let d=o_(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&Zm.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new h(Qm(e,t),g.USAGE)}return o}var Yx=/^[A-Za-z]:[\\/]/,Xx=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Jx(e){let t=e.trim();return Yx.test(t)?!1:Xx.test(t)}function WG(e,t,n,r){if(!(r||!e.includes(",")))throw new h(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,g.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function Qx(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new h(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,g.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new h(`${t} provides key "${i}" more than once after case normalization.`,g.USAGE);e[s]=e[i],delete e[i]}}}async function Zx(e){if(process.stdin.isTTY===!0)throw new h(`${e} value "${yt}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,g.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(rl(r))}),process.stdin.on("error",o=>{n(o)})})}var _n=Symbol("all-mutation-stdin-fields"),We=new WeakMap;function i_(e){return We.set(e,_n),e}function eC(e,t){let n=We.get(e);return n===_n||We.set(e,new Set([...n??[],...t])),e}function tC(e,t){let n=We.get(e);return n===void 0||We.set(t,n===_n?n:new Set(n)),t}function KG(e,t){let n=We.get(e),r=We.get(t);return n===void 0||r===_n?t:n===_n?(We.set(t,n),t):(We.set(t,new Set([...r??[],...n])),t)}function nC(e){return We.get(e)!==_n}function Ji(e,t){let n=We.get(e);return n!==_n&&!n?.has(t)}function rC(e){let t;for(let n of e){if(n.resolveToken===!1||n.value===void 0)continue;let o=(Array.isArray(n.value)?n.value:[n.value]).filter(i=>i.trim()===yt).length;if(o>1)throw new h(`${n.optionName} accepts "${yt}" stdin token at most once per command invocation`,g.USAGE);if(o!==0){if(t!==void 0&&t!==n.optionName)throw new h(`Only one option may use "${yt}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);t=n.optionName}}}async function YG(e,t,n){let r=e,o=[...t,...n];rC(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:Ji(e,a)})));let i=or(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,Ji(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,Ji(e,a));return i_(s)}function or(){let e,t,n=async i=>{if(t&&t!==i)throw new h(`Only one option may use "${yt}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);return t=i,e||(e=Zx(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==yt?i:await n(s)},resolveList:async(i,s,a=!0)=>{if(!a)return i;if(!i)return;let c=i.map((u,f)=>u.trim()===yt?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new h(`${s} accepts "${yt}" stdin token at most once per command invocation`,g.USAGE);let l=await n(s),d=[...i];return d[c[0]]=l,d}}}function oC(e,t){let n=Number(e);if(!Number.isFinite(n))throw new h(`Invalid ${t} value "${e}"`,g.USAGE);return n}function iC(e,t){let n=e.trim(),r=Number(n);if(n===""||!Number.isInteger(r)||r<0)throw new h(`Invalid ${t} value "${e}". Expected a non-negative integer.`,g.USAGE);return r}import{readFile as sC}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]="411f4336-eb02-5167-9dce-ea99822a8a14")}catch{}})();var aC=e=>sC(e,"utf8"),cC=async e=>await or().resolveValue("-",e);function ol(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function lC(e){let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(typeof r=="number"&&Number.isFinite(r))t.push(String(r));else return"";let n=ol(t.join(`
12
- `));return n.length>0?n.join(","):""}function s_(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return lC(e);if(typeof e!="string")return"";let t=ol(e);return t.length>0?t.join(","):""}async function dC(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??cC)(t);else if(r.startsWith("@")){let s=r.slice(1).trim();if(s.length===0)throw new h(`${t} @path requires a non-empty file path.`,g.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${t} @<path>, ${t} -, or inline IDs.`});o=await(n.readFile??aC)(s)}}catch(s){if(s instanceof h)throw s;let a=s instanceof Error?s.message:String(s);throw new h(`${t} could not read ${r==="-"?"stdin":`"${r.slice(1).trim()}"`}: ${a}`,g.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${t} -, ${t} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${t} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${t} - --dry-run`]})}let i=s_(o);if(i!=="")return i;throw new h(`${t} requires at least one non-empty item ID.`,g.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @path."})}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]="d6056922-237d-525a-b354-687493a4e123")}catch{}})();var uC=2e3,Qi=new Map;function Ie(e){if(typeof e!="string")return"";let t=Qi.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Qi.size>=uC&&Wn(Qi),Qi.set(e,n),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]="633ef301-42a3-5b73-a4ed-7af0e0e40371")}catch{}})();var he=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),d_=ec,sl=Za,fC=["create","update"],pC=new Set(bi),mC=new Set(Jn),_C=new Set(wi),gC=new Set(Ei),yC=new Set(["string","number","boolean","array","object"]),hC=16;function u_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var bC=[e=>e.type===void 0||typeof e.type=="string"&&yC.has(e.type),e=>!Object.hasOwn(e,"const")||es(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>es(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||u_(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function es(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=Array.isArray(e)?e.every(r=>es(r,t)):Object.values(e).every(r=>es(r,t));return t.delete(e),n}function Zi(e,t=0,n=new Set){if(!u_(e)||t>hC||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,l=r.required,d=r.min_length,u=r.min_items,f=r.format,p=r.additional_properties;if(!bC.every(T=>T(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([T,O])=>[T,Zi(O,t+1,n)])),y=c===void 0?void 0:Zi(c,t+1,n),b=s===void 0?void 0:s.map(T=>Zi(T,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...b??[]].some(T=>T===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:d,min_items:u,format:f,properties:_,required:l===void 0?void 0:[...new Set(l)],additional_properties:p,items:y,one_of:b}).filter(([,T])=>T!==void 0))}function fo(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 Re(e){if(typeof e!="string"||e.length===0)return;let t=Ie(e);return t.length>0?t:void 0}function wC(e){return e.startsWith("--")?e.slice(2):e}function c_(e){return typeof e=="string"?wC(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function f_(e){return e.replaceAll("_","-")}function EC(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 il(e,t){let n=Re(e.id);if(!n)return null;let r=[...new Set(fo(e.aliases).map(Ie).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=fo(e.roles).filter(a=>pC.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 vC(e){return{draft_status:Re(e?.draft_status),open_status:Re(e?.open_status),in_progress_status:Re(e?.in_progress_status),blocked_status:Re(e?.blocked_status),close_status:Re(e?.close_status),canceled_status:Re(e?.canceled_status)}}function p_(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Ie(t[0]),r=Ie(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function TC(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)p_(n,r);return{typeKey:t.toLowerCase(),record:n}}function kC(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=TC(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)p_(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 m_(e){let t=Ie(e.key??"");if(!t)return null;let n=Ie(e.metadata_key??e.front_matter_key??t),r=c_(e.cli_flag??f_(t));if(!r)return null;let o=fo(e.cli_aliases).map(u=>c_(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=mC.has(i)?i:"string",a=(()=>{let u=fo(e.commands).filter(f=>_C.has(f));return u.length>0?u:[...fC]})(),c=e.description?.trim(),l=fo(e.required_types),d=e.value_schema===void 0?void 0:Zi(e.value_schema);return e.value_schema!==void 0&&d===void 0?null:{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"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:l,allow_unset:e.allow_unset!==!1,value_schema:d}}function AC(e){let t=new Map;for(let[r,o]of e.entries()){let i=il(o,r);i&&t.set(i.id,i)}let n=l_([...t.values()]);return n.length>0?n:l_(sl.map((r,o)=>il(r,o)).filter(r=>r!==null))}function l_(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function SC(e){let t=new Map;for(let n of e??[]){let r=m_(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function xC(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 CC(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==f_(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function OC(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return gC.has(t)?t:"allow"}function Ze(e){let t={...he,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:sl,r=AC(n),o=SC(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(xC),fields:o.map(CC),workflow:{...d_,...vC(e?.workflow)},type_workflows:kC(e?.type_workflows),unknown_field_policy:OC(e?.unknown_field_policy)}}function IC(e){return`${JSON.stringify(e,null,2)}
13
- `}function RC(){return{definitions:[]}}function NC(){return{statuses:sl}}function DC(){return{fields:[]}}function PC(){return{workflow:d_}}function LC(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function MC(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 FC(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 $C(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 jC(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 UC(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 Te(e,t,n){let r=t?.trim()||n;return a_.isAbsolute(r)?r:a_.join(e,r)}function zC(e,t){return Te(e,t.files.types,he.types)}async function __(e,t){let n=Ze(t),r=[{path:Te(e,n.files.types,he.types),seed:RC()},{path:Te(e,n.files.statuses,he.statuses),seed:NC()},{path:Te(e,n.files.fields,he.fields),seed:DC()},{path:Te(e,n.files.workflows,he.workflows),seed:PC()}],o=[];for(let i of r)await ee(i.path)||(await P(i.path,IC(i.seed)),o.push(i.path));return{created_paths:o}}async function g_(e,t){let n=Ze(t),r=[],o=Te(e,n.files.types,he.types),i=Te(e,n.files.statuses,he.statuses),s=Te(e,n.files.fields,he.fields),a=Te(e,n.files.workflows,he.workflows),c,l,d,u,f,p=async(O,M)=>{let W=await Y(O);if(W!==null)return LC(W,M,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=MC(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await p(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(l=FC(y),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await p(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=$C(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let E=await p(a,"runtime_schema_workflows_invalid_json");return E!==void 0&&(u=jC(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=UC(E)),{schema:Ze({...n,statuses:[...n.statuses,...l??[]],fields:[...n.fields,...d??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function uo(e,t,n,r=!1){let i=n.map(a=>Re(a)).filter(a=>typeof a=="string").find(a=>e.some(c=>c.id===a));if(r&&i!==void 0)return i;let s=e.find(a=>a.roles.includes(t));return s!==void 0?s.id:i??e[0]?.id}function qC(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function VC(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function al(e){let t=Ze(e),n=t.statuses.map((E,T)=>il(E,T)).filter(E=>E!==null),{aliasToId:r,byId:o}=qC(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:l,terminalStatuses:d}=VC(n),u=t.workflow,f=Re(u.open_status)??uo(n,"default_open",["open","in_progress",Xn[0]]),p=Re(u.in_progress_status)??uo(n,"active",["in_progress","in-progress",f],!0),_=Re(u.blocked_status)??uo(n,"blocked",["blocked"]),y=Re(u.close_status)??uo(n,"default_close",["closed","done","complete"]),b=Re(u.canceled_status)??uo(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:d,terminal_done_statuses:l,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:p,blocked_status:_,close_status:y,canceled_status:b}}function ts(e,t){let n=Ie(e);if(n)return t.alias_to_id.get(n)}function cl(e){let t=Ze(e),n=new Map,r=t.fields.map(c=>m_(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,l)=>c.key.localeCompare(l.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 l of c.cli_aliases)s.set(l,c);for(let l of c.commands){let d=a.get(l)??[];d.push(c),a.set(l,d)}}for(let[c,l]of a.entries())l.sort((d,u)=>d.key.localeCompare(u.key)),a.set(c,l);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function y_(e){return EC(e.key)}function GC(e,t){let n=ts(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]="91a3969e-59b3-506e-9349-ca08e73a1228")}catch{}})();var BC=16;function ll(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 HC(e){return[...new Set([y_(e),ll(e.key),ll(e.cli_flag),...e.cli_aliases.map(t=>ll(t))])]}function ns(e,t){for(let n of HC(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function w_(e){return Array.isArray(e)?e.flatMap(t=>w_(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 h_(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 h(`${t} must be one of true|false|1|0|yes|no`,g.USAGE)}function b_(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 h(`${t} must be a number`,g.USAGE);return r}function WC(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 h(`${t} must be valid JSON ${n}`,g.USAGE)}function KC(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function YC(e,t,n){if(t.const!==void 0&&K(e)!==K(t.const))return`${n} must equal ${K(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>K(r)===K(e)))return`${n} must be one of ${t.enum.map(r=>K(r)).join("|")}`;if(!KC(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!np(e))return`${n} must be an RFC 3339 date-time`}}function XC(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=rs(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function JC(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=rs(s,a,`${n}.${i}`,r+1);if(c)return c}}function rs(e,t,n,r=0){if(r>BC)return`${n} value schema exceeds maximum depth`;let o=YC(e,t,n);if(o)return o;let i=XC(e,t,n,r);if(i)return i;let s=JC(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(rs(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function gn(e,t,n){if(!e.value_schema||t===void 0)return t;let r=rs(t,e.value_schema,n);if(r)throw new h(r,g.USAGE);return t}function yn(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:gn(e,WC(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=w_(t);return e.type==="number"?gn(e,i.map(s=>b_(s,r)),r):e.type==="boolean"?gn(e,i.map(s=>h_(s,r)),r):gn(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?gn(e,b_(o,r),r):e.type==="boolean"?gn(e,h_(o,r),r):gn(e,typeof o=="string"?o:String(o),r)}function QC(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 ZC(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=ns(e,i);if(s===void 0){QC(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=yn(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function eO(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=ns(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=yn(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 ir=1,E_=1;function gB(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=ir?t:ir}function v_(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=ir))return e}function tO(e,t=E_){return e<t?"outdated":e>t?"ahead":"current"}function yB(e,t=E_){let n=[],r=[];for(let o of e){let i=tO(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 nO={"in-progress":"in_progress",cancelled:"canceled"};function hn(e,t){if(t){let o=ts(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=nO[n]??n;if(Xn.includes(r))return r}function T_(e,t){return hn(e,t)??e}function rO(e,t){return t.terminal_statuses.has(T_(e,t))}import{encode as aO}from"@toon-format/toon";import{isDeepStrictEqual as k_}from"node:util";import{decode as oO}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 dl(e){return{value:oO(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 iO=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function sO(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(iO);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function os(e){return sO(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]="051655a4-8ba7-5118-9758-d9ca377fa7e4")}catch{}})();var ml=new Set(["schema","tracker","auto"]),x_=new Set(["source","isolated","snapshot"]),cO=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),lO=new Set(["passed","failed","stopped","canceled"]),dO=new Set(Ai);function cr(e){return e.replaceAll("\\","/")}function C_(e){for(let t of e)if(t!==0)return t;return 0}function ss(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var O_=["id","title","description","created_at","updated_at"],uO=new Set(Me);function I_(e){if(e?.schema)return{statusRegistry:al(e.schema),fieldRegistry:cl(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function fO(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Mt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new h(`Invalid item metadata: ${e}`,g.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 _o(e,t){throw new h(t,g.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 R_(e){let t=new Set(uO);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function C(e,t){e||Mt(t)}function go(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Mt(t),e}function ul(e,t){let n=e[t];C(typeof n=="string",`${t} must be a string`),C(ft(n),`${t} must be a valid ISO timestamp`)}function A_(e,t,n){let r=e[t];r!==void 0&&C(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function _l(e,t,n){let r=e[t];r!==void 0&&(C(typeof r=="string",`${n} must be a string`),C(ft(r),`${n} must be a valid ISO timestamp`))}function pO(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){C(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();C(Ur.includes(n),`event.recurrence.by_weekday entries must be one of: ${Ur.join(", ")}`)}}}function mO(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)C(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function _O(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)C(typeof t=="string","event.recurrence.exdates entries must be strings"),C(ft(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function gO(e){let t=go(e,"event.recurrence must be an object");C(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();C(ki.includes(n),`event.recurrence.freq must be one of: ${ki.join(", ")}`),A_(t,"interval","event.recurrence.interval"),A_(t,"count","event.recurrence.count"),_l(t,"until","event.recurrence.until"),pO(t.by_weekday),mO(t.by_month_day),_O(t.exdates)}function yO(e){for(let r of O_)C(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;C(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&C(typeof n=="number"&&Number.isInteger(n)&&n>=ir,`pm_format_version must be an integer >= ${ir}`),t}function hO(e,t){let n=e.status;C(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=hn(n,r),i=r?r.definitions.map(s=>s.id):[...Xn];C(o!==void 0,`status must be one of: ${i.join(", ")}`)}function bO(e){let t=e.priority;C(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;C(Array.isArray(n),"tags must be an array");for(let r of n)C(typeof r=="string","tags entries must be strings")}function wO(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){C(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"||Ti.includes(n);C(r,`confidence string value must be one of: ${[...Ti,"med"].join(", ")}`);return}C(!1,"confidence must be a number or string")}}function EO(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Mt("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||vi.includes(n);C(r,`severity value must be one of: ${[...vi,"med"].join(", ")}`)}function vO(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Mt("regression must be a boolean")}function TO(e){let t=e.reminders;if(t!==void 0){C(Array.isArray(t),"reminders must be an array");for(let n of t){let r=go(n,"reminders entries must be objects");C(typeof r.at=="string","reminder.at must be a string"),C(ft(r.at),"reminder.at must be a valid ISO timestamp"),C(typeof r.text=="string","reminder.text must be a string"),C(r.text.trim().length>0,"reminder.text must not be empty")}}}function kO(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(C(typeof e[t]=="string",`event.${t} must be a string`),C(e[t].trim().length>0,`event.${t} must not be empty`))}function AO(e){e.recurrence!==void 0&&(gO(e.recurrence),e.recurrence.until!==void 0&&C(ue(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function SO(e){let t=go(e,"events entries must be objects");C(typeof t.start_at=="string","event.start_at must be a string"),C(ft(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(C(typeof t.end_at=="string","event.end_at must be a string"),C(ft(t.end_at),"event.end_at must be a valid ISO timestamp"),C(ue(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),kO(t),t.all_day!==void 0&&C(typeof t.all_day=="boolean","event.all_day must be a boolean"),AO(t)}function xO(e){let t=e.events;if(t!==void 0){C(Array.isArray(t),"events must be an array");for(let n of t)SO(n)}}function CO(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&C(typeof n=="string",`${t} must be a string`)}}function OO(e){let t=e.type_options;if(t===void 0)return;let n=go(t,"type_options must be an object");for(let[r,o]of Object.entries(n))C(r.trim().length>0,"type_options keys must be non-empty"),C(typeof o=="string","type_options values must be strings"),C(o.trim().length>0,"type_options values must be non-empty strings")}function IO(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){fO(r,t)&&Mt(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=yn(r,o,`metadata field "${r.metadata_key}"`)}catch(i){Mt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function RO(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=R_(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Mt(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function gl(e,t){let n=go(e,"item metadata must be an object"),r=yO(n);hO(n,t),bO(n),wO(n),EO(n),vO(n),ul(n,"created_at"),ul(n,"updated_at"),n.deadline!==void 0&&ul(n,"deadline"),TO(n),xO(n),_l(n,"closed_at","closed_at"),_l(n,"completed_at","completed_at"),CO(n),OO(n),IO(n,r,t),RO(n,t)}function NO(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=ue(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 fl(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=ue(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 DO(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=ue(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function PO(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!ki.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Ur.includes(s)))).sort((s,a)=>dc(s)-dc(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=>ft(s)))).sort((s,a)=>ue(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 LO(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(MO).sort(FO)}function MO(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:PO(e.recurrence)};return ss(t),t}function FO(e,t){return C_([ue(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 $O(e){if(!(!e||e.length===0))return e.map(t=>({path:cr(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function jO(e){if(!e||e.length===0)return;let t=e.map(VO).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)=>C_([ue(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 sr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function UO(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function pl(e){return typeof e=="string"?e:""}function zO(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 is(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function qO(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:is(n.requested_pm_context_mode,ml),pm_context_mode:is(n.pm_context_mode,ml),workspace_context_mode:is(n.workspace_context_mode,x_),trust_reason:is(n.trust_reason,cO)}));return t.length>0?t:void 0}function VO(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=lO.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:pl(e.started_at),finished_at:pl(e.finished_at),recorded_at:pl(e.recorded_at),attempt:UO(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:sr(e.passed)??0,failed:sr(e.failed)??0,skipped:sr(e.skipped)??0,items:sr(e.items),linked_tests:sr(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:zO(e.measurements),executions:qO(e.executions)};return ss(o),o}function GO(e){if(!(!Array.isArray(e)||e.length===0))return e.map(YO)}function po(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 hl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function bl(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function S_(e){if(!hl(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!bl(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function BO(e){if(!hl(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!bl(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function HO(e){let t=e?.trim().toLowerCase();if(!(!t||!ml.has(t)))return t}function WO(e){let t=e?.trim().toLowerCase();if(!(!t||!x_.has(t)))return t}function KO(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!hl(e))return{provenance_invalid:!0};let n=S(e.author),r=S(e.created_at),o=e.source_kind;return!n||!r||!ft(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:S(e.source_ref)}}}function YO(e){let t={command:e.command?.trim()||void 0,path:e.path?cr(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:HO(e.pm_context_mode),workspace_context_mode:WO(e.workspace_context_mode),...KO(e.provenance,e.provenance_invalid),env_set:S_(e.env_set),env_clear:po(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:po(e.assert_stdout_contains),assert_stdout_regex:po(e.assert_stdout_regex),assert_stderr_contains:po(e.assert_stderr_contains),assert_stderr_regex:po(e.assert_stderr_regex),assert_stdout_min_lines:sr(e.assert_stdout_min_lines),assert_json_field_equals:S_(e.assert_json_field_equals),assert_json_field_gte:BO(e.assert_json_field_gte),note:e.note?.trim()||void 0};return ss(t),t}function XO(e){if(!(!e||e.length===0))return[...e].map(t=>({path:cr(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 S(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function JO(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.id),i=S(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=S(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 QO(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:cr(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function ZO(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.command),i=S(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=cr(i));let a=S(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function eI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:cr(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function tI(e){if(e===null||typeof e!="object")return;let t=e,n=S(t.id),r=S(t.title),o=S(t.status),i=o&&dO.has(o)?o:void 0,s=gi(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 l={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return nI(l,t),l}function nI(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=S(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",JO],["files","files",QO],["tests","tests",ZO],["docs","docs",eI]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function rI(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=tI(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function oI(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=S(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=S(r.rationale);c&&(a.rationale=c);let l=S(r.evidence);l&&(a.evidence=l);let d=S(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function iI(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=S(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=S(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function sI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.text);if(!o)continue;let i={text:o},s=S(r.command);s&&(i.command=s);let a=S(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function aI(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 ar(e){let t=0;for(;t<e.length&&e[t]===`
14
- `;)t+=1;return e.slice(t).trimEnd()}function cI(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ti.includes(t))return t}function lI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(vi.includes(t))return t}function mo(e){return e||void 0}function dI(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))bl(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function uI(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]=yn(r,o,`metadata field "${r.metadata_key}"`))}}function fI(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=R_(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&Mt(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function yo(e,t={}){let n=I_(t),r=hn(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:v_(e.pm_format_version),source_type:S(e.source_type),type_options:aI(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:NO(e.dependencies),comments:fl(e.comments),notes:fl(e.notes),learnings:fl(e.learnings),files:$O(e.files),tests:GO(e.tests),test_runs:jO(e.test_runs),docs:XO(e.docs),deadline:mo(e.deadline),reminders:DO(e.reminders),events:LO(e.events),closed_at:mo(e.closed_at),completed_at:mo(e.completed_at),assignee:S(e.assignee),claim_principal:S(e.claim_principal),source_owner:S(e.source_owner),author:mo(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:S(e.definition_of_ready),order:e.order,goal:S(e.goal),objective:S(e.objective),value:S(e.value),impact:S(e.impact),outcome:S(e.outcome),why_now:S(e.why_now),parent:S(e.parent),reviewer:S(e.reviewer),risk:e.risk??void 0,confidence:cI(e.confidence),sprint:S(e.sprint),release:S(e.release),blocked_by:S(e.blocked_by),blocked_reason:S(e.blocked_reason),unblock_note:S(e.unblock_note),reporter:S(e.reporter),severity:lI(e.severity),environment:S(e.environment),repro_steps:S(e.repro_steps),resolution:S(e.resolution),expected_result:S(e.expected_result),actual_result:S(e.actual_result),affected_version:S(e.affected_version),fixed_version:S(e.fixed_version),component:S(e.component),regression:e.regression,customer_impact:S(e.customer_impact),close_reason:mo(e.close_reason),plan_mode:S(e.plan_mode),plan_scope:S(e.plan_scope),plan_harness:S(e.plan_harness),plan_resume_context:S(e.plan_resume_context),plan_steps:rI(e.plan_steps),plan_decisions:oI(e.plan_decisions),plan_discoveries:iI(e.plan_discoveries),plan_validation:sI(e.plan_validation)};return dI(i,e),uI(i,n),fI(i,n),ss(i),i}function N_(e){return I(e,Me)}function pI(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 mI(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=pI(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 _I(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(`
15
- `,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 yl(e,t){return yo(e,{...t,onWarning:void 0})}function gI(e,t,n={}){let r=_I(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=mI(r.content);o||(e.trimStart().startsWith("{")&&_o("json_markdown","JSON front matter is not valid JSON"),_o("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{_o("json_markdown","JSON front matter is not valid JSON")}return gl(s,t),{metadata:yl(s,n),body:ar(i)}}function yI(e,t,n={}){let r;try{r=dl(e).value}catch{_o("toon","TOON item document is not valid TOON")}C(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!O_.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&_o("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return gl(o.front_matter,t),C(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:yl(o.front_matter,n),body:ar(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return C(i===void 0||typeof i=="string","TOON item document body must be a string"),gl(s,t),{metadata:yl(s,n),body:ar(typeof i=="string"?i:"")}}function hI(e,t={}){let n=yo(e.metadata,t),r=N_(n),o=JSON.stringify(r,null,2),i=ar(e.body??"");return i?`${o}
11
+ ${i}`;continue}return null}return n}function Xx(e,t){let n=r_(e).trim();if(!n)throw new h(`${t} cannot be empty`,g.USAGE);let r=Yx(n);if(r)return r;let o={},i,s=Hx(n);for(let a of s){let c=Wx(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new h(Qm(e,t),g.USAGE);let d=o_(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&Zm.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new h(Qm(e,t),g.USAGE)}return o}var Jx=/^[A-Za-z]:[\\/]/,Qx=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Zx(e){let t=e.trim();return Jx.test(t)?!1:Qx.test(t)}function YG(e,t,n,r){if(!(r||!e.includes(",")))throw new h(`${t} received an ambiguous comma-bearing bare ${n}. Repeat ${t} for multiple values, or quote or escape literal commas in a structured key=<value> entry.`,g.USAGE,{code:"bare_comma_entry_ambiguous",required:`Use one ${t} per bare ${n}, or quote or escape literal commas in a structured key=<value> entry.`})}function eC(e,t,n){let r=new Set(n.map(i=>i.toLowerCase())),o=Object.keys(e).filter(i=>!r.has(i.toLowerCase()));if(o.length>0)throw new h(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,g.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new h(`${t} provides key "${i}" more than once after case normalization.`,g.USAGE);e[s]=e[i],delete e[i]}}}async function tC(e){if(process.stdin.isTTY===!0)throw new h(`${e} value "${wt}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,g.USAGE);return process.stdin.setEncoding("utf8"),await new Promise((t,n)=>{let r="";process.stdin.on("data",o=>{r+=o}),process.stdin.on("end",()=>{t(nl(r))}),process.stdin.on("error",o=>{n(o)})})}var gn=Symbol("all-mutation-stdin-fields"),Ye=new WeakMap;function i_(e){return Ye.set(e,gn),e}function nC(e,t){let n=Ye.get(e);return n===gn||Ye.set(e,new Set([...n??[],...t])),e}function rC(e,t){let n=Ye.get(e);return n===void 0||Ye.set(t,n===gn?n:new Set(n)),t}function XG(e,t){let n=Ye.get(e),r=Ye.get(t);return n===void 0||r===gn?t:n===gn?(Ye.set(t,n),t):(Ye.set(t,new Set([...r??[],...n])),t)}function oC(e){return Ye.get(e)!==gn}function Ji(e,t){let n=Ye.get(e);return n!==gn&&!n?.has(t)}function iC(e){let t;for(let n of e){if(n.resolveToken===!1||n.value===void 0)continue;let o=(Array.isArray(n.value)?n.value:[n.value]).filter(i=>i.trim()===wt).length;if(o>1)throw new h(`${n.optionName} accepts "${wt}" stdin token at most once per command invocation`,g.USAGE);if(o!==0){if(t!==void 0&&t!==n.optionName)throw new h(`Only one option may use "${wt}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);t=n.optionName}}}async function JG(e,t,n){let r=e,o=[...t,...n];iC(o.map(([a,c])=>({value:r[a],optionName:c,resolveToken:Ji(e,a)})));let i=or(),s={...r};for(let[a,c]of t)s[a]=await i.resolveValue(r[a],c,Ji(e,a));for(let[a,c]of n)s[a]=await i.resolveList(r[a],c,Ji(e,a));return i_(s)}function or(){let e,t,n=async i=>{if(t&&t!==i)throw new h(`Only one option may use "${wt}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);return t=i,e||(e=tC(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==wt?i:await n(s)},resolveList:async(i,s,a=!0)=>{if(!a)return i;if(!i)return;let c=i.map((u,f)=>u.trim()===wt?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new h(`${s} accepts "${wt}" stdin token at most once per command invocation`,g.USAGE);let l=await n(s),d=[...i];return d[c[0]]=l,d}}}function sC(e,t){let n=Number(e);if(!Number.isFinite(n))throw new h(`Invalid ${t} value "${e}"`,g.USAGE);return n}function aC(e,t){let n=e.trim(),r=Number(n);if(n===""||!Number.isInteger(r)||r<0)throw new h(`Invalid ${t} value "${e}". Expected a non-negative integer.`,g.USAGE);return r}import{readFile as cC}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]="411f4336-eb02-5167-9dce-ea99822a8a14")}catch{}})();var lC=e=>cC(e,"utf8"),dC=async e=>await or().resolveValue("-",e);function rl(e){return[...new Set(e.split(/[,\r\n]+/).map(t=>t.trim()).filter(t=>t.length>0))]}function uC(e){let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(typeof r=="number"&&Number.isFinite(r))t.push(String(r));else return"";let n=rl(t.join(`
12
+ `));return n.length>0?n.join(","):""}function s_(e){if(e===void 0)return;if(typeof e=="number")return Number.isFinite(e)?String(e):"";if(Array.isArray(e))return uC(e);if(typeof e!="string")return"";let t=rl(e);return t.length>0?t.join(","):""}async function fC(e,t="--ids",n={}){if(e===void 0)return;let r=e.trim(),o=e;try{if(r==="-")o=await(n.readStdin??dC)(t);else if(r.startsWith("@")){let s=r.slice(1).trim();if(s.length===0)throw new h(`${t} @path requires a non-empty file path.`,g.USAGE,{code:"bulk_ids_input_missing_path",required:`Pass ${t} @<path>, ${t} -, or inline IDs.`});o=await(n.readFile??lC)(s)}}catch(s){if(s instanceof h)throw s;let a=s instanceof Error?s.message:String(s);throw new h(`${t} could not read ${r==="-"?"stdin":`"${r.slice(1).trim()}"`}: ${a}`,g.NOT_FOUND,{code:"bulk_ids_input_unreadable",required:`Provide readable newline/comma-delimited IDs via ${t} -, ${t} @<path>, or inline argv text.`,nextSteps:[`Retry with inline IDs: ${t} pm-a1b2,pm-c3d4`,`Or pipe IDs: pm list --id-only | pm update-many ${t} - --dry-run`]})}let i=s_(o);if(i!=="")return i;throw new h(`${t} requires at least one non-empty item ID.`,g.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more comma- or newline-delimited IDs through argv, stdin, or @path."})}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]="d6056922-237d-525a-b354-687493a4e123")}catch{}})();var pC=2e3,Qi=new Map;function Ie(e){if(typeof e!="string")return"";let t=Qi.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Qi.size>=pC&&Wn(Qi),Qi.set(e,n),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]="633ef301-42a3-5b73-a4ed-7af0e0e40371")}catch{}})();var he=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),d_=Za,il=Qa,mC=["create","update"],_C=new Set(bi),gC=new Set(Jn),yC=new Set(wi),hC=new Set(Ei),bC=new Set(["string","number","boolean","array","object"]),wC=16;function u_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var EC=[e=>e.type===void 0||typeof e.type=="string"&&bC.has(e.type),e=>!Object.hasOwn(e,"const")||es(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>es(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||u_(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function es(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=Array.isArray(e)?e.every(r=>es(r,t)):Object.values(e).every(r=>es(r,t));return t.delete(e),n}function Zi(e,t=0,n=new Set){if(!u_(e)||t>wC||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,l=r.required,d=r.min_length,u=r.min_items,f=r.format,p=r.additional_properties;if(!EC.every(T=>T(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([T,O])=>[T,Zi(O,t+1,n)])),y=c===void 0?void 0:Zi(c,t+1,n),b=s===void 0?void 0:s.map(T=>Zi(T,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...b??[]].some(T=>T===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:d,min_items:u,format:f,properties:_,required:l===void 0?void 0:[...new Set(l)],additional_properties:p,items:y,one_of:b}).filter(([,T])=>T!==void 0))}function fo(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 Re(e){if(typeof e!="string"||e.length===0)return;let t=Ie(e);return t.length>0?t:void 0}function vC(e){return e.startsWith("--")?e.slice(2):e}function c_(e){return typeof e=="string"?vC(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function f_(e){return e.replaceAll("_","-")}function TC(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 ol(e,t){let n=Re(e.id);if(!n)return null;let r=[...new Set(fo(e.aliases).map(Ie).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=fo(e.roles).filter(a=>_C.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 kC(e){return{draft_status:Re(e?.draft_status),open_status:Re(e?.open_status),in_progress_status:Re(e?.in_progress_status),blocked_status:Re(e?.blocked_status),close_status:Re(e?.close_status),canceled_status:Re(e?.canceled_status)}}function p_(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Ie(t[0]),r=Ie(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function AC(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)p_(n,r);return{typeKey:t.toLowerCase(),record:n}}function SC(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=AC(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)p_(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 m_(e){let t=Ie(e.key??"");if(!t)return null;let n=Ie(e.metadata_key??e.front_matter_key??t),r=c_(e.cli_flag??f_(t));if(!r)return null;let o=fo(e.cli_aliases).map(u=>c_(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=gC.has(i)?i:"string",a=(()=>{let u=fo(e.commands).filter(f=>yC.has(f));return u.length>0?u:[...mC]})(),c=e.description?.trim(),l=fo(e.required_types),d=e.value_schema===void 0?void 0:Zi(e.value_schema);return e.value_schema!==void 0&&d===void 0?null:{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"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:l,allow_unset:e.allow_unset!==!1,value_schema:d}}function xC(e){let t=new Map;for(let[r,o]of e.entries()){let i=ol(o,r);i&&t.set(i.id,i)}let n=l_([...t.values()]);return n.length>0?n:l_(il.map((r,o)=>ol(r,o)).filter(r=>r!==null))}function l_(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function CC(e){let t=new Map;for(let n of e??[]){let r=m_(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function OC(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 IC(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==f_(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function RC(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return hC.has(t)?t:"allow"}function nt(e){let t={...he,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:il,r=xC(n),o=CC(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(OC),fields:o.map(IC),workflow:{...d_,...kC(e?.workflow)},type_workflows:SC(e?.type_workflows),unknown_field_policy:RC(e?.unknown_field_policy)}}function NC(e){return`${JSON.stringify(e,null,2)}
13
+ `}function DC(){return{definitions:[]}}function PC(){return{statuses:il}}function LC(){return{fields:[]}}function MC(){return{workflow:d_}}function FC(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function $C(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 jC(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 UC(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 zC(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 qC(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 ve(e,t,n){let r=t?.trim()||n;return a_.isAbsolute(r)?r:a_.join(e,r)}function VC(e,t){return ve(e,t.files.types,he.types)}async function __(e,t){let n=nt(t),r=[{path:ve(e,n.files.types,he.types),seed:DC()},{path:ve(e,n.files.statuses,he.statuses),seed:PC()},{path:ve(e,n.files.fields,he.fields),seed:LC()},{path:ve(e,n.files.workflows,he.workflows),seed:MC()}],o=[];for(let i of r)await ee(i.path)||(await L(i.path,NC(i.seed)),o.push(i.path));return{created_paths:o}}async function g_(e,t){let n=nt(t),r=[],o=ve(e,n.files.types,he.types),i=ve(e,n.files.statuses,he.statuses),s=ve(e,n.files.fields,he.fields),a=ve(e,n.files.workflows,he.workflows),c,l,d,u,f,p=async(O,P)=>{let F=await Y(O);if(F!==null)return FC(F,P,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=$C(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await p(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(l=jC(y),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await p(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=UC(b),d===void 0&&r.push("runtime_schema_fields_invalid_shape"));let E=await p(a,"runtime_schema_workflows_invalid_json");return E!==void 0&&(u=zC(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=qC(E)),{schema:nt({...n,statuses:[...n.statuses,...l??[]],fields:[...n.fields,...d??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function uo(e,t,n,r=!1){let i=n.map(a=>Re(a)).filter(a=>typeof a=="string").find(a=>e.some(c=>c.id===a));if(r&&i!==void 0)return i;let s=e.find(a=>a.roles.includes(t));return s!==void 0?s.id:i??e[0]?.id}function GC(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function BC(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function sl(e){let t=nt(e),n=t.statuses.map((E,T)=>ol(E,T)).filter(E=>E!==null),{aliasToId:r,byId:o}=GC(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:l,terminalStatuses:d}=BC(n),u=t.workflow,f=Re(u.open_status)??uo(n,"default_open",["open","in_progress",Xn[0]]),p=Re(u.in_progress_status)??uo(n,"active",["in_progress","in-progress",f],!0),_=Re(u.blocked_status)??uo(n,"blocked",["blocked"]),y=Re(u.close_status)??uo(n,"default_close",["closed","done","complete"]),b=Re(u.canceled_status)??uo(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:d,terminal_done_statuses:l,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:p,blocked_status:_,close_status:y,canceled_status:b}}function ts(e,t){let n=Ie(e);if(n)return t.alias_to_id.get(n)}function al(e){let t=nt(e),n=new Map,r=t.fields.map(c=>m_(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,l)=>c.key.localeCompare(l.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 l of c.cli_aliases)s.set(l,c);for(let l of c.commands){let d=a.get(l)??[];d.push(c),a.set(l,d)}}for(let[c,l]of a.entries())l.sort((d,u)=>d.key.localeCompare(u.key)),a.set(c,l);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function y_(e){return TC(e.key)}function HC(e,t){let n=ts(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]="91a3969e-59b3-506e-9349-ca08e73a1228")}catch{}})();var WC=16;function cl(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 KC(e){return[...new Set([y_(e),cl(e.key),cl(e.cli_flag),...e.cli_aliases.map(t=>cl(t))])]}function ns(e,t){for(let n of KC(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function w_(e){return Array.isArray(e)?e.flatMap(t=>w_(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 h_(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 h(`${t} must be one of true|false|1|0|yes|no`,g.USAGE)}function b_(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 h(`${t} must be a number`,g.USAGE);return r}function YC(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 h(`${t} must be valid JSON ${n}`,g.USAGE)}function XC(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function JC(e,t,n){if(t.const!==void 0&&B(e)!==B(t.const))return`${n} must equal ${B(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>B(r)===B(e)))return`${n} must be one of ${t.enum.map(r=>B(r)).join("|")}`;if(!XC(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!np(e))return`${n} must be an RFC 3339 date-time`}}function QC(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=rs(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function ZC(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=rs(s,a,`${n}.${i}`,r+1);if(c)return c}}function rs(e,t,n,r=0){if(r>WC)return`${n} value schema exceeds maximum depth`;let o=JC(e,t,n);if(o)return o;let i=QC(e,t,n,r);if(i)return i;let s=ZC(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(rs(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function yn(e,t,n){if(!e.value_schema||t===void 0)return t;let r=rs(t,e.value_schema,n);if(r)throw new h(r,g.USAGE);return t}function hn(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:yn(e,YC(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=w_(t);return e.type==="number"?yn(e,i.map(s=>b_(s,r)),r):e.type==="boolean"?yn(e,i.map(s=>h_(s,r)),r):yn(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?yn(e,b_(o,r),r):e.type==="boolean"?yn(e,h_(o,r),r):yn(e,typeof o=="string"?o:String(o),r)}function eO(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 tO(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=ns(e,i);if(s===void 0){eO(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=hn(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function nO(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=ns(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=hn(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 ir=1,E_=1;function hB(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=ir?t:ir}function v_(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=ir))return e}function rO(e,t=E_){return e<t?"outdated":e>t?"ahead":"current"}function bB(e,t=E_){let n=[],r=[];for(let o of e){let i=rO(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 oO={"in-progress":"in_progress",cancelled:"canceled"};function bn(e,t){if(t){let o=ts(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=oO[n]??n;if(Xn.includes(r))return r}function T_(e,t){return bn(e,t)??e}function iO(e,t){return t.terminal_statuses.has(T_(e,t))}import{encode as lO}from"@toon-format/toon";import{isDeepStrictEqual as k_}from"node:util";import{decode as sO}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 ll(e){return{value:sO(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 aO=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function cO(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(aO);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function os(e){return cO(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]="051655a4-8ba7-5118-9758-d9ca377fa7e4")}catch{}})();var pl=new Set(["schema","tracker","auto"]),x_=new Set(["source","isolated","snapshot"]),dO=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),uO=new Set(["passed","failed","stopped","canceled"]),fO=new Set(Ai);function cr(e){return e.replaceAll("\\","/")}function C_(e){for(let t of e)if(t!==0)return t;return 0}function ss(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var O_=["id","title","description","created_at","updated_at"],pO=new Set(Me);function I_(e){if(e?.schema)return{statusRegistry:sl(e.schema),fieldRegistry:al(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function mO(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Ut(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new h(`Invalid item metadata: ${e}`,g.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 _o(e,t){throw new h(t,g.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 R_(e){let t=new Set(pO);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function C(e,t){e||Ut(t)}function go(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Ut(t),e}function dl(e,t){let n=e[t];C(typeof n=="string",`${t} must be a string`),C(_t(n),`${t} must be a valid ISO timestamp`)}function A_(e,t,n){let r=e[t];r!==void 0&&C(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function ml(e,t,n){let r=e[t];r!==void 0&&(C(typeof r=="string",`${n} must be a string`),C(_t(r),`${n} must be a valid ISO timestamp`))}function _O(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){C(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();C(Ur.includes(n),`event.recurrence.by_weekday entries must be one of: ${Ur.join(", ")}`)}}}function gO(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)C(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function yO(e){if(e!==void 0){C(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)C(typeof t=="string","event.recurrence.exdates entries must be strings"),C(_t(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function hO(e){let t=go(e,"event.recurrence must be an object");C(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();C(ki.includes(n),`event.recurrence.freq must be one of: ${ki.join(", ")}`),A_(t,"interval","event.recurrence.interval"),A_(t,"count","event.recurrence.count"),ml(t,"until","event.recurrence.until"),_O(t.by_weekday),gO(t.by_month_day),yO(t.exdates)}function bO(e){for(let r of O_)C(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;C(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&C(typeof n=="number"&&Number.isInteger(n)&&n>=ir,`pm_format_version must be an integer >= ${ir}`),t}function wO(e,t){let n=e.status;C(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=bn(n,r),i=r?r.definitions.map(s=>s.id):[...Xn];C(o!==void 0,`status must be one of: ${i.join(", ")}`)}function EO(e){let t=e.priority;C(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;C(Array.isArray(n),"tags must be an array");for(let r of n)C(typeof r=="string","tags entries must be strings")}function vO(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){C(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"||Ti.includes(n);C(r,`confidence string value must be one of: ${[...Ti,"med"].join(", ")}`);return}C(!1,"confidence must be a number or string")}}function TO(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Ut("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||vi.includes(n);C(r,`severity value must be one of: ${[...vi,"med"].join(", ")}`)}function kO(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Ut("regression must be a boolean")}function AO(e){let t=e.reminders;if(t!==void 0){C(Array.isArray(t),"reminders must be an array");for(let n of t){let r=go(n,"reminders entries must be objects");C(typeof r.at=="string","reminder.at must be a string"),C(_t(r.at),"reminder.at must be a valid ISO timestamp"),C(typeof r.text=="string","reminder.text must be a string"),C(r.text.trim().length>0,"reminder.text must not be empty")}}}function SO(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(C(typeof e[t]=="string",`event.${t} must be a string`),C(e[t].trim().length>0,`event.${t} must not be empty`))}function xO(e){e.recurrence!==void 0&&(hO(e.recurrence),e.recurrence.until!==void 0&&C(de(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function CO(e){let t=go(e,"events entries must be objects");C(typeof t.start_at=="string","event.start_at must be a string"),C(_t(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(C(typeof t.end_at=="string","event.end_at must be a string"),C(_t(t.end_at),"event.end_at must be a valid ISO timestamp"),C(de(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),SO(t),t.all_day!==void 0&&C(typeof t.all_day=="boolean","event.all_day must be a boolean"),xO(t)}function OO(e){let t=e.events;if(t!==void 0){C(Array.isArray(t),"events must be an array");for(let n of t)CO(n)}}function IO(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&C(typeof n=="string",`${t} must be a string`)}}function RO(e){let t=e.type_options;if(t===void 0)return;let n=go(t,"type_options must be an object");for(let[r,o]of Object.entries(n))C(r.trim().length>0,"type_options keys must be non-empty"),C(typeof o=="string","type_options values must be strings"),C(o.trim().length>0,"type_options values must be non-empty strings")}function NO(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){mO(r,t)&&Ut(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=hn(r,o,`metadata field "${r.metadata_key}"`)}catch(i){Ut(String(i?.message).replace(/^Invalid\s+/u,""))}}}function DO(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=R_(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Ut(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function _l(e,t){let n=go(e,"item metadata must be an object"),r=bO(n);wO(n,t),EO(n),vO(n),TO(n),kO(n),dl(n,"created_at"),dl(n,"updated_at"),n.deadline!==void 0&&dl(n,"deadline"),AO(n),OO(n),ml(n,"closed_at","closed_at"),ml(n,"completed_at","completed_at"),IO(n),RO(n),NO(n,r,t),DO(n,t)}function PO(e){if(!(!e||e.length===0))return[...e].map(t=>({id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=de(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 ul(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=de(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 LO(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=de(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function MO(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!ki.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Ur.includes(s)))).sort((s,a)=>lc(s)-lc(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=>_t(s)))).sort((s,a)=>de(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 FO(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map($O).sort(jO)}function $O(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:MO(e.recurrence)};return ss(t),t}function jO(e,t){return C_([de(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 UO(e){if(!(!e||e.length===0))return e.map(t=>({path:cr(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function zO(e){if(!e||e.length===0)return;let t=e.map(BO).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)=>C_([de(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 sr(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function qO(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function fl(e){return typeof e=="string"?e:""}function VO(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 is(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function GO(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:is(n.requested_pm_context_mode,pl),pm_context_mode:is(n.pm_context_mode,pl),workspace_context_mode:is(n.workspace_context_mode,x_),trust_reason:is(n.trust_reason,dO)}));return t.length>0?t:void 0}function BO(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=uO.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:fl(e.started_at),finished_at:fl(e.finished_at),recorded_at:fl(e.recorded_at),attempt:qO(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:sr(e.passed)??0,failed:sr(e.failed)??0,skipped:sr(e.skipped)??0,items:sr(e.items),linked_tests:sr(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:VO(e.measurements),executions:GO(e.executions)};return ss(o),o}function HO(e){if(!(!Array.isArray(e)||e.length===0))return e.map(JO)}function po(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 yl(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function hl(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function S_(e){if(!yl(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!hl(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function WO(e){if(!yl(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!hl(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function KO(e){let t=e?.trim().toLowerCase();if(!(!t||!pl.has(t)))return t}function YO(e){let t=e?.trim().toLowerCase();if(!(!t||!x_.has(t)))return t}function XO(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!yl(e))return{provenance_invalid:!0};let n=S(e.author),r=S(e.created_at),o=e.source_kind;return!n||!r||!_t(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:S(e.source_ref)}}}function JO(e){let t={command:e.command?.trim()||void 0,path:e.path?cr(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:KO(e.pm_context_mode),workspace_context_mode:YO(e.workspace_context_mode),...XO(e.provenance,e.provenance_invalid),env_set:S_(e.env_set),env_clear:po(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:po(e.assert_stdout_contains),assert_stdout_regex:po(e.assert_stdout_regex),assert_stderr_contains:po(e.assert_stderr_contains),assert_stderr_regex:po(e.assert_stderr_regex),assert_stdout_min_lines:sr(e.assert_stdout_min_lines),assert_json_field_equals:S_(e.assert_json_field_equals),assert_json_field_gte:WO(e.assert_json_field_gte),note:e.note?.trim()||void 0};return ss(t),t}function QO(e){if(!(!e||e.length===0))return[...e].map(t=>({path:cr(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 S(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function ZO(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.id),i=S(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=S(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 eI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:cr(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function tI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.command),i=S(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=cr(i));let a=S(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function nI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.path);if(!o)continue;let i={path:cr(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=S(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function rI(e){if(e===null||typeof e!="object")return;let t=e,n=S(t.id),r=S(t.title),o=S(t.status),i=o&&fO.has(o)?o:void 0,s=gi(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 l={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return oI(l,t),l}function oI(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=S(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",ZO],["files","files",eI],["tests","tests",tI],["docs","docs",nI]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function iI(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=rI(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function sI(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=S(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=S(r.rationale);c&&(a.rationale=c);let l=S(r.evidence);l&&(a.evidence=l);let d=S(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function aI(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=S(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=S(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function cI(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=S(r.text);if(!o)continue;let i={text:o},s=S(r.command);s&&(i.command=s);let a=S(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function lI(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 ar(e){let t=0;for(;t<e.length&&e[t]===`
14
+ `;)t+=1;return e.slice(t).trimEnd()}function dI(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ti.includes(t))return t}function uI(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(vi.includes(t))return t}function mo(e){return e||void 0}function fI(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))hl(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function pI(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]=hn(r,o,`metadata field "${r.metadata_key}"`))}}function mI(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=R_(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&Ut(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function yo(e,t={}){let n=I_(t),r=bn(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:v_(e.pm_format_version),source_type:S(e.source_type),type_options:lI(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:PO(e.dependencies),comments:ul(e.comments),notes:ul(e.notes),learnings:ul(e.learnings),files:UO(e.files),tests:HO(e.tests),test_runs:zO(e.test_runs),docs:QO(e.docs),deadline:mo(e.deadline),reminders:LO(e.reminders),events:FO(e.events),closed_at:mo(e.closed_at),completed_at:mo(e.completed_at),assignee:S(e.assignee),claim_principal:S(e.claim_principal),source_owner:S(e.source_owner),author:mo(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:S(e.definition_of_ready),order:e.order,goal:S(e.goal),objective:S(e.objective),value:S(e.value),impact:S(e.impact),outcome:S(e.outcome),why_now:S(e.why_now),parent:S(e.parent),reviewer:S(e.reviewer),risk:e.risk??void 0,confidence:dI(e.confidence),sprint:S(e.sprint),release:S(e.release),blocked_by:S(e.blocked_by),blocked_reason:S(e.blocked_reason),unblock_note:S(e.unblock_note),reporter:S(e.reporter),severity:uI(e.severity),environment:S(e.environment),repro_steps:S(e.repro_steps),resolution:S(e.resolution),expected_result:S(e.expected_result),actual_result:S(e.actual_result),affected_version:S(e.affected_version),fixed_version:S(e.fixed_version),component:S(e.component),regression:e.regression,customer_impact:S(e.customer_impact),close_reason:mo(e.close_reason),plan_mode:S(e.plan_mode),plan_scope:S(e.plan_scope),plan_harness:S(e.plan_harness),plan_resume_context:S(e.plan_resume_context),plan_steps:iI(e.plan_steps),plan_decisions:sI(e.plan_decisions),plan_discoveries:aI(e.plan_discoveries),plan_validation:cI(e.plan_validation)};return fI(i,e),pI(i,n),mI(i,n),ss(i),i}function N_(e){return I(e,Me)}function _I(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 gI(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=_I(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 yI(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(`
15
+ `,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 gl(e,t){return yo(e,{...t,onWarning:void 0})}function hI(e,t,n={}){let r=yI(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=gI(r.content);o||(e.trimStart().startsWith("{")&&_o("json_markdown","JSON front matter is not valid JSON"),_o("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{_o("json_markdown","JSON front matter is not valid JSON")}return _l(s,t),{metadata:gl(s,n),body:ar(i)}}function bI(e,t,n={}){let r;try{r=ll(e).value}catch{_o("toon","TOON item document is not valid TOON")}C(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!O_.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&_o("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return _l(o.front_matter,t),C(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:gl(o.front_matter,n),body:ar(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return C(i===void 0||typeof i=="string","TOON item document body must be a string"),_l(s,t),{metadata:gl(s,n),body:ar(typeof i=="string"?i:"")}}function wI(e,t={}){let n=yo(e.metadata,t),r=N_(n),o=JSON.stringify(r,null,2),i=ar(e.body??"");return i?`${o}
16
16
 
17
17
  ${i}
18
18
  `:`${o}
19
- `}function bI(e,t={}){let n=yo(e.metadata,t),r=N_(n),o=ar(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=aO(s),c;try{c=dl(a).value}catch(l){throw new h("Refusing to persist a TOON item document that the configured decoder cannot read back.",g.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:l instanceof Error?l.message:String(l)})}if(!k_(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!k_(s[u],l[u]))??"document";throw new h(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${d}".`,g.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:d,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}
20
- `}function bn(e,t={}){let n=os(e);if(n)throw new h(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.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=I_(t);return r==="toon"?yI(e,o,t):gI(e,o,t)}function ho(e,t={}){return(t.format??"toon")==="toon"?bI(e,t):hI(e,t)}function je(e,t={}){return{metadata:yo(e.metadata,t),body:ar(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 wl(e){return e}import{AsyncLocalStorage as wI}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 El=new wI,D_=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function as(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Ft(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=as(n.id,128),o=as(n.parent_id,128);if(r===void 0||!D_.test(r)||o!==void 0&&!D_.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=as(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function lr(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=as(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function EI(e,t,n){let r=El.getStore(),o=lr({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Ft(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={...lr(r?.provenance),...o,...lr(e?.provenance)},a=Ft(e?.episode,!1)??Ft(n,!1)??i??Ft(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 cs(e,t){return EI(e.session_context,t,e.client_info?.episode)??{}}function vI(e,t){let n=El.getStore(),r=Ft(e.episode,!0),o=Ft(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...lr(n?.provenance),...lr(e.provenance)};return El.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function TI(e){let t=lr(e.provenance),n=Ft(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{createHash as P_}from"node:crypto";import{existsSync as vl,promises as L_,readFileSync as kI}from"node:fs";import et 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]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var AI="session.json";function Tl(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function M_(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Tl(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Tl(c,128)),a=t.focused_item_id===void 0||Tl(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function SI(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=M_(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function kl(e){return et.join(_c(e),AI)}async function ls(e){try{let t=await L_.readFile(kl(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=SI(r.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function Al(e,t){let n=kl(e);await L_.mkdir(et.dirname(n),{recursive:!0}),await P(n,JSON.stringify(t))}function Sl(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${P_("sha256").update(e).digest("hex").slice(0,24)}`}function xl(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Cl(e){let t=[...new Set(e)].sort((o,i)=>o.localeCompare(i));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${P_("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Ol(e,t,n){let r=await ls(e),o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i;let s={...r};Object.keys(o).length===0?delete s.semantic_attribution:s.semantic_attribution=o,await Al(e,s)}async function KB(e){let t=Sl(e.principal);await Ol(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??Cl(r),confidence:o?"high":"medium",rule_version:"v2",evidence:xl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function YB(e){let t=Sl(e.principal);await Ol(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??Cl(r),confidence:o?"high":"medium",evidence:xl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function XB(e){let t=Sl(e.principal);await Ol(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??Cl(r),confidence:o?"high":"medium",rule_version:"v2",evidence:xl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function xI(e,t){let n=t.PM_PATH?.trim();if(n){let o=et.resolve(e,n);if(vl(et.join(o,"settings.json")))return o;let i=et.join(o,".agents","pm");if(vl(et.join(i,"settings.json")))return i}let r=et.resolve(e);for(let o=0;o<32;o+=1){let i=et.join(r,".agents","pm");if(vl(et.join(i,"settings.json")))return i;let s=et.dirname(r);if(s===r)break;r=s}}function F_(e){if(!e.key)return;let t=xI(e.cwd,e.env);if(t)try{let n=JSON.parse(kI(kl(t),"utf8"));return M_(n.semantic_attribution?.[e.key])}catch{return}}async function CI(e){return(await ls(e)).focused_item}async function OI(e,t){let n=await ls(e);await Al(e,{...n,focused_item:t})}async function II(e){let n={...await ls(e)};delete n.focused_item,await Al(e,n)}import{AsyncLocalStorage as Pl}from"node:async_hooks";import{createHash as RI}from"node:crypto";import tt from"node:fs";import z_ from"node:os";import us 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]="cf550961-0040-5e04-9d8d-16e316027e43")}catch{}})();var Ll=["model","effort","role","topic","version"],ps=new Pl,q_=new Pl,ms=new Pl,Ml=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],V_=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),NI=Object.freeze({...V_,max_bytes:4194304}),Il=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function DI(e){let t=jt(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?NI:V_,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var Fl=Object.freeze(Ml.filter(e=>e.harness!=="ci").map(DI).sort((e,t)=>e.harness.localeCompare(t.harness))),En=new Map,dr=new Map;function Q(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function $t(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function jt(e){let t=e.harness.trim().toLowerCase();if(!Il.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:$t(e.environment_keys),model_environment_keys:$t(e.model_environment_keys),session_environment_keys:$t(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),$t(r)]).filter(([n])=>Il.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"&&Il.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:$t(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:$t(e.argv_markers).map(n=>n.toLowerCase()),client_names:$t(e.client_names).map(n=>n.toLowerCase())}}var G_=Ml.map(jt);function PI(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fs(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function $l(e=[]){let t=new Map(Ml.filter(o=>o.harness!=="ci").map(o=>[o.harness,jt(o)]));for(let{adapter:o}of En.values())t.set(o.harness,jt(o.descriptor));let n=[...t.values(),...G_.filter(o=>o.harness==="ci"),...[...dr.values()].map(o=>o.descriptor),...ms.getStore()?.descriptors??[],...e.map(jt)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function jl(e,t){for(let n of t??[]){let r=Q(e[n]);if(r)return r.slice(0,256)}}function LI(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function B_(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 Q(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return Q(i.slice(s.length+1))?.slice(0,256)}}var MI=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function wn(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return MI.has(n)?n:void 0}function Rl(e,t){return Q(e?.[t])?.slice(0,256)}var FI=1048576,Dl=4194304,ds=new Map,$_=Object.freeze({}),Nl=new Map,j_=Object.freeze({});function U_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function $I(e){let t;try{t=JSON.parse(e)}catch{return j_}let n=U_(t);if(!n)return j_;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=Q(a.value.model)?.slice(0,256),s??=Q(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=U_(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function jI(e,t,n){let r=Q(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=us.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=us.join(t.home_dir??z_.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=tt.openSync(s,"r");try{let c=tt.fstatSync(a),l=`${s}\0${c.size}\0${c.mtimeMs}`,d=Nl.get(l);if(d)return d[e];let u=Math.min(c.size,FI),f=Math.min(u,Math.ceil(u/2)),p=Math.min(u-f,c.size-f),_=Buffer.alloc(f);tt.readSync(a,_,0,f,0);let y=Buffer.alloc(p);p>0&&tt.readSync(a,y,0,p,c.size-p);let b={},E=c.size<=u?Buffer.concat([_,y]).toString("utf8").split(`
19
+ `}function EI(e,t={}){let n=yo(e.metadata,t),r=N_(n),o=ar(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=lO(s),c;try{c=ll(a).value}catch(l){throw new h("Refusing to persist a TOON item document that the configured decoder cannot read back.",g.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:l instanceof Error?l.message:String(l)})}if(!k_(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!k_(s[u],l[u]))??"document";throw new h(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${d}".`,g.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:d,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}
20
+ `}function wn(e,t={}){let n=os(e);if(n)throw new h(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.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=I_(t);return r==="toon"?bI(e,o,t):hI(e,o,t)}function ho(e,t={}){return(t.format??"toon")==="toon"?EI(e,t):wI(e,t)}function je(e,t={}){return{metadata:yo(e.metadata,t),body:ar(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 bl(e){return e}import{AsyncLocalStorage as vI}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 wl=new vI,D_=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function as(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function zt(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=as(n.id,128),o=as(n.parent_id,128);if(r===void 0||!D_.test(r)||o!==void 0&&!D_.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=as(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function lr(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=as(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function TI(e,t,n){let r=wl.getStore(),o=lr({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=zt(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={...lr(r?.provenance),...o,...lr(e?.provenance)},a=zt(e?.episode,!1)??zt(n,!1)??i??zt(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 cs(e,t){return TI(e.session_context,t,e.client_info?.episode)??{}}function kI(e,t){let n=wl.getStore(),r=zt(e.episode,!0),o=zt(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...lr(n?.provenance),...lr(e.provenance)};return wl.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function AI(e){let t=lr(e.provenance),n=zt(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{createHash as P_}from"node:crypto";import{existsSync as El,promises as L_,readFileSync as SI}from"node:fs";import rt 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]="424b9eb3-6b34-5ab0-a3f5-db61fbca12cf")}catch{}})();var xI="session.json";function vl(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function M_(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=vl(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>vl(c,128)),a=t.focused_item_id===void 0||vl(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function CI(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=M_(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Tl(e){return rt.join(mc(e),xI)}async function ls(e){try{let t=await L_.readFile(Tl(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=CI(r.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function kl(e,t){let n=Tl(e);await L_.mkdir(rt.dirname(n),{recursive:!0}),await L(n,JSON.stringify(t))}function Al(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${P_("sha256").update(e).digest("hex").slice(0,24)}`}function Sl(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function xl(e){let t=[...new Set(e)].sort((o,i)=>o.localeCompare(i));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${P_("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Cl(e,t,n){let r=await ls(e),o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i;let s={...r};Object.keys(o).length===0?delete s.semantic_attribution:s.semantic_attribution=o,await kl(e,s)}async function XB(e){let t=Al(e.principal);await Cl(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??xl(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Sl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function JB(e){let t=Al(e.principal);await Cl(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??xl(r),confidence:o?"high":"medium",evidence:Sl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function QB(e){let t=Al(e.principal);await Cl(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??xl(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Sl([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function OI(e,t){let n=t.PM_PATH?.trim();if(n){let o=rt.resolve(e,n);if(El(rt.join(o,"settings.json")))return o;let i=rt.join(o,".agents","pm");if(El(rt.join(i,"settings.json")))return i}let r=rt.resolve(e);for(let o=0;o<32;o+=1){let i=rt.join(r,".agents","pm");if(El(rt.join(i,"settings.json")))return i;let s=rt.dirname(r);if(s===r)break;r=s}}function F_(e){if(!e.key)return;let t=OI(e.cwd,e.env);if(t)try{let n=JSON.parse(SI(Tl(t),"utf8"));return M_(n.semantic_attribution?.[e.key])}catch{return}}async function II(e){return(await ls(e)).focused_item}async function RI(e,t){let n=await ls(e);await kl(e,{...n,focused_item:t})}async function NI(e){let n={...await ls(e)};delete n.focused_item,await kl(e,n)}import{AsyncLocalStorage as Dl}from"node:async_hooks";import{createHash as DI}from"node:crypto";import ot from"node:fs";import z_ from"node:os";import us 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]="cf550961-0040-5e04-9d8d-16e316027e43")}catch{}})();var Pl=["model","effort","role","topic","version"],ps=new Dl,q_=new Dl,ms=new Dl,Ll=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],V_=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),PI=Object.freeze({...V_,max_bytes:4194304}),Ol=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function LI(e){let t=Vt(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?PI:V_,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var Ml=Object.freeze(Ll.filter(e=>e.harness!=="ci").map(LI).sort((e,t)=>e.harness.localeCompare(t.harness))),vn=new Map,dr=new Map;function Q(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function qt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function Vt(e){let t=e.harness.trim().toLowerCase();if(!Ol.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:qt(e.environment_keys),model_environment_keys:qt(e.model_environment_keys),session_environment_keys:qt(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),qt(r)]).filter(([n])=>Ol.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"&&Ol.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:qt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:qt(e.argv_markers).map(n=>n.toLowerCase()),client_names:qt(e.client_names).map(n=>n.toLowerCase())}}var G_=Ll.map(Vt);function MI(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fs(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function Fl(e=[]){let t=new Map(Ll.filter(o=>o.harness!=="ci").map(o=>[o.harness,Vt(o)]));for(let{adapter:o}of vn.values())t.set(o.harness,Vt(o.descriptor));let n=[...t.values(),...G_.filter(o=>o.harness==="ci"),...[...dr.values()].map(o=>o.descriptor),...ms.getStore()?.descriptors??[],...e.map(Vt)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function $l(e,t){for(let n of t??[]){let r=Q(e[n]);if(r)return r.slice(0,256)}}function FI(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function B_(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 Q(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return Q(i.slice(s.length+1))?.slice(0,256)}}var $I=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function En(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return $I.has(n)?n:void 0}function Il(e,t){return Q(e?.[t])?.slice(0,256)}var jI=1048576,Nl=4194304,ds=new Map,$_=Object.freeze({}),Rl=new Map,j_=Object.freeze({});function U_(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function UI(e){let t;try{t=JSON.parse(e)}catch{return j_}let n=U_(t);if(!n)return j_;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=Q(a.value.model)?.slice(0,256),s??=Q(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=U_(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function zI(e,t,n){let r=Q(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=us.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=us.join(t.home_dir??z_.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=ot.openSync(s,"r");try{let c=ot.fstatSync(a),l=`${s}\0${c.size}\0${c.mtimeMs}`,d=Rl.get(l);if(d)return d[e];let u=Math.min(c.size,jI),f=Math.min(u,Math.ceil(u/2)),p=Math.min(u-f,c.size-f),_=Buffer.alloc(f);ot.readSync(a,_,0,f,0);let y=Buffer.alloc(p);p>0&&ot.readSync(a,y,0,p,c.size-p);let b={},E=c.size<=u?Buffer.concat([_,y]).toString("utf8").split(`
21
21
  `):[..._.toString("utf8").split(`
22
22
  `).slice(0,4096),...y.toString("utf8").split(`
23
- `).slice(-4096)];for(let O of E){if(O.length===0||O.length>262144)continue;let M=$I(O);if(b.model??=M.model,b.version??=M.version,b.model&&b.version)break}let T=Object.freeze(b);return Nl.clear(),Nl.set(l,T),T[e]}finally{tt.closeSync(a)}}catch{return}}function UI(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=tt.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=us.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let l=r(c,i+1);if(l)return l}}};return r(e,0)}function zI(e){if(e<=Dl)return[{offset:0,length:e}];let t=Math.floor(Dl/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function qI(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=Q(o?.model)?.slice(0,256),e.effort??=Q(o?.effort)?.slice(0,256)}function VI(e,t){let n={},r=4096;for(let o of zI(t)){let i=Buffer.alloc(o.length);tt.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
24
- `).reverse().slice(0,r);r-=s.length;for(let a of s)if(qI(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function GI(e,t,n){let r=Q(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=us.join(t.home_dir??z_.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=ds.get(i);if(s)return s[e];let a=UI(o,r);if(!a){ds.set(i,$_);return}try{let c=tt.openSync(a,"r");try{let l=tt.fstatSync(c).size,d=VI(c,l);return ds.set(i,d),d[e]}finally{tt.closeSync(c)}}catch{ds.set(i,$_);return}}function BI(e,t,n,r){let o=ms.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(Q(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return jI(e,t,n);if(s==="codex_session_file")return GI(e,t,n);if(s==="ai_agent_version"){let a=Q(n.AI_AGENT);return!a||!r||!fs(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function HI(e,t,n){if(e==="ai_agent_version"){let r=Q(n.AI_AGENT);return r!==void 0&&fs(r,t.harness)}return e==="codex_session_file"?Q(n.CODEX_THREAD_ID)!==void 0:Q(n.CLAUDE_CODE_SESSION_ID)!==void 0}function Ul(e){return e||(q_.getStore()??{env:process.env,argv:process.argv})}function WI(e,t,n,r){let o=e.environment_keys.some(a=>Q(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return fs(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||fs(r,a));return o||i||s}function KI(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function YI(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function XI(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Ll,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=wn(e,Q(n[s])?.slice(0,256)),d=wn(e,B_(t.argv??[],e)),l=wn(e,LI(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},p=Rl(o?.provenance,e),_=wn(e,jl(n,u[e])),y=wn(e,Rl(f,e)),b=wn(e,Rl(t.provenance,e)),E=BI(e,t,n,r);return YI([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[y,"mcp_client"],[b,"host"],[E,"probe"]])??KI(e,i)??(l?{value:l,source:"argv"}:void 0)}function JI(e,t){if(!(!e||!t))return RI("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function QI(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Ll,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let l=XI(c,e,t,n,r,o);l?a[c]=l:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function i5(e){let t=e.map(jt),n=new Map(G_.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=dr.get(i.harness);if(s&&!PI(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=dr.get(i.harness);dr.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=dr.get(i.harness);!s||s.registrations<=1?dr.delete(i.harness):s.registrations-=1}}}}function ZI(e){let t=jt(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=Q(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>Dl||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze($t(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function eR(){let e=new Map(Fl.map(t=>[t.harness,t]));for(let{adapter:t}of En.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function tR(e){let t=e.map(ZI),n=new Map(Fl.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=En.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=En.get(i.harness);En.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=En.get(i.harness);!s||s.registrations<=1?En.delete(i.harness):s.registrations-=1}}}}function nR(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function rR(e,t){return q_.run(e,t)}function oR(e,t,n={}){let r=e.map(jt);return $l(r),ms.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function bo(e){let t=Ul(e),n=t.env??{},r=$l(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(_=>WI(_,n,o,i)),a=cs(t,n),c=[jl(n,s?.session_environment_keys),Q(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=JI(s?.harness,c),d=F_({cwd:t.cwd??process.cwd(),env:n,key:l}),u=QI(t,n,s,a,d),f=u.model,p=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",l],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(p.filter(_=>_[1]!==void 0))}function iR(e,t,n,r,o,i){let s=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...s?{resolver:s}:{},rule_version:"v1"};if(i)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(s){let a=HI(s,n,r);return{status:a&&o?"failed":"unavailable",reason:a?o?"resolver_failed":"probes_disabled":"harness_unavailable",resolver:s,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function zl(e){let t=Ul(e),n=bo(t),r=$l(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&ms.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(Q(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=cs(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,jl(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,B_(t.argv??[],"role")].some(l=>{let d=Q(l)?.slice(0,256);return d!==void 0&&wn("role",d)===void 0}),c=Object.fromEntries(Ll.map(l=>[l,iR(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function ql(){return process.env.PM_AUTHOR}function sR(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function s5(e){return bo(e).harness}function aR(e,t,n){let r=Ul(n),o=bo(r);if(e!==void 0){let s=Q(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=Q(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=Q(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function H_(e){let t=ps.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function W_(e){let t=ps.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 Vl(e){let t=ps.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function wo(e,t){let n=aR(e,t);return ps.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 Ke(e,t){let n=await Y(e);if(n===null)return[];if(await He({path:e,scope:"project"}),n.trim()==="")return[];let r=os(n);if(r)throw new h(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.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 h(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,g.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]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();var _s="changed_fields",cR="changed_field_count",Gl="rows",lR=new Set(["apply","rollback"]),X_=new Set(["deleted","would_delete"]),K_=256;function Y_(e){return typeof e!="string"||e.length<=K_?e:`${e.slice(0,K_-1)}\u2026`}function dR(e){if(!ht(e))return null;let t={...e};return t.reason=Y_(t.reason),ht(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Y_(r)]))),t}function ht(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function J_(e){let t=e[_s];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==_s&&(n[r]=o);return n[cR]=t.length,n}function uR(e){return"item"in e&&Array.isArray(e[_s])}function fR(e){return typeof e.mode=="string"&&lR.has(e.mode)&&Array.isArray(e[Gl])}function pR(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Gl]=t,n}function mR(e){if(!ht(e))return null;let t=ht(e.item)?e.item:ht(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"&&X_.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 _R(e){if(!ht(e)||!ht(e.item)||typeof e.item.id!="string")return null;let t=e[_s];if(!Array.isArray(t))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&X_.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;r!==void 0&&(n.close_reason=r);let o=dR(e.recurrence);return o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings),n}function gR(e){let t=fR(e)?e[Gl]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!ht(o))return o;let i=J_(o);return i?(n=!0,i):o});return n?{projected:pR(e,r),changed:!0}:{projected:e,changed:!1}}function gs(e,t={}){if(t.idOnly===!0){let a=mR(e);if(a!==null)return a}if(t.compactEnvelope===!0){let a=_R(e);if(a!==null)return a}if((t.changedFields??"full")==="full"||!ht(e))return e;let r=!1,o=e,i=uR(e)?J_(e):null;i!==null&&(o=i,r=!0);let s=gR(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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var yR=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},hR=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?yR(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Bl=(e,t=process.platform)=>{let n=e.map(r=>hR(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"},bR=new Set(["--literal","--regex","--replacement"]);function _5(e){if(!e.includes("history-redact"))return[...e];let t=[],n=!1;for(let r of e){if(n&&!r.startsWith("-")){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!bR.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!0}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();var tg=new WeakMap;function b5(e,t){tg.set(e,new Set(t))}var Q_='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',wR={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:["activity_digest","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"}},ER=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function w5(e,t,n){if(e&&t)throw new h(`${n} cannot be combined with --full`,g.USAGE)}function nt(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 E5(e,t){let n=ER.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return nt([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return nt(r)}var vR=[{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 Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var TR=new Set([void 0,"tabular_when_uniform"]),kR=new Set(["collection","none"]),AR=new Set(["supported","unsupported"]);function Z_(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function SR(e){return Ue(e)&&typeof e.command=="string"&&e.command.trim().length>0&&kR.has(e.row_kind)&&Z_(e.row_keys,!0)&&(e.continuation_row_keys===void 0||Z_(e.continuation_row_keys,!1))&&AR.has(e.fields)&&TR.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var xR={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"]},CR={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:["activity_digest","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 OR(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=xR[s];if(a===void 0)return;let c=a.filter(l=>Array.isArray(t[l])||Ue(t[l]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:Q_}:{},toon_encoding:"tabular_when_uniform"}}let o=wR[r],i=CR[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((l,d)=>Ue(l)?l[d]:void 0,t);return Array.isArray(c)||Ue(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:Q_}:{},toon_encoding:"tabular_when_uniform"}})()}function IR(e){if(!Ue(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=>Ue(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 nt(r,new Set(o))}function RR(e){if(Array.isArray(e.sections_included))return nt(vR,new Set(e.sections_included.filter(t=>typeof t=="string")))}function NR(e){if(!Ue(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=tg.get(e),i=a=>n.includes(a)||a==="body"?t:e,s=["body",...n,...r.slice(1)].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:`--fields ${a}`}));return nt(s,new Set(s.flatMap(({name:a})=>Object.hasOwn(i(a),a)?[a]:[])))}function eg(e){if(Ue(e.projection))return nt([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function DR(e){if(!Ue(e.projection))return nt([]);if(typeof e.projection.mode=="string")return nt([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function PR(e){if(!(!Ue(e.selected)||typeof e.selected.summary!="boolean"))return nt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function LR(e,t){let n=IR(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return RR(t);if(r==="get")return NR(t);if(r==="list"||r.startsWith("list-"))return eg(t);if(r==="search")return eg(t)??nt([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return DR(t);if(r==="contracts")return PR(t)}function ng(e,t){if(e===void 0||!Ue(t))return t;let n=LR(e,t),r=t.row_contract,o=SR(r)?r:OR(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return Ue(i.omission_receipt)||n===void 0?i:{...i,omission_receipt:n}}import{createHash as MR}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]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var Hl=1,og=4096,FR=/^[A-Za-z0-9_-]+$/;function rg(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function x5(e,t){let n=new Set;for(let r of t)if(r.cursor_semantics==="presentation"){n.add(rg(r.flag));for(let o of r.aliases??[])n.add(rg(o))}return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function C5(e,t){return MR("sha256").update(e).update("\0").update(K(t)).digest("hex").slice(0,24)}function Eo(e,t,n,r){return Buffer.from(JSON.stringify({version:Hl,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function vn(e){return new h(e,g.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]})}function $R(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Hl&&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 Wl(e){if(typeof e!="string")throw vn("Query cursor is malformed.");let t=e.trim();if(t.length===0||t.length>og||!FR.test(t))throw vn("Query cursor is malformed.");let n;try{n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw vn("Query cursor is malformed.")}if(!$R(n))throw vn("Query cursor version or payload is unsupported.");return n}function Kl(e,t){let n=Wl(e);if(n.fingerprint!==t)throw vn(`Query cursor does not match the current filters, sort, or query (${n.fingerprint} != ${t}).`);return{after_id:n.after_id,...n.after_index===void 0?{}:{after_index:n.after_index},...n.snapshot===void 0?{}:{snapshot:n.snapshot}}}function O5(e,t){return Kl(e,t).after_id}function jR(e,t,n,r){if(t===void 0)return 0;let o=Kl(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 vn(`Query cursor item ${o.after_id} is no longer present in this result set.`)}return i+1}function I5(e,t){if(t.cursor!==void 0&&Kl(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw vn("Query cursor does not match the requested snapshot.");let n=jR(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:Eo(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var R5=Object.freeze({version:Hl,max_length:og});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="810d42b5-98f4-57a7-bdd9-2dfa1b2b1c03")}catch{}})();var UR=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function ur(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!ur(n))return;n=n[r]}return n}function Yl(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[s];if(Array.isArray(i)){let l=Number(a),d=[...i];return d[l]=o(i[l],s+1),d}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function sg(e,t,n){let r=pr(e).find(i=>i.path===t);if(!r)return e;let o=Array.isArray(r.value)?r.value.slice(n):Object.fromEntries(Object.entries(r.value).slice(n));return Yl(e,t,o)}function ys(e){let t=e.row_contract;return ur(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function zR(e){let t=e.row_contract;return ur(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):ys(e)}function fr(e){return ys(e).flatMap(t=>{let n=ig(e,t);return Array.isArray(n)||ur(n)?[{path:t,value:n}]:[]})}function pr(e){return zR(e).flatMap(t=>{let n=ig(e,t);return Array.isArray(n)||ur(n)?[{path:t,value:n}]:[]})}function hs(e){let t=fr(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(ur(o))for(let[s,a]of Object.entries(o))i.length===0&&UR.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function bs(e){return fr(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function vo(e,t){let n=e;for(let r of fr(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=Yl(n,r.path,o)}return n}function ag(e,t){let n=e,r=!1;for(let o of fr(n)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;r=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));n=Yl(n,o.path,s)}return{result:n,truncated: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]="02a0bd0c-6ab0-5193-807b-00394a4712b7")}catch{}})();var qR=8,VR=64,GR=5,BR=4,cg=100;function Jl(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*GR/BR),i=Math.ceil(o/cg)*cg;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function Ql(e){return Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4)}function HR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Xl(e,t){return typeof e=="string"?e.length<=240?e:(t.compacted=!0,`${e.slice(0,240)}\u2026`):Array.isArray(e)?e.map(n=>Xl(n,t)):HR(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Xl(r,t)])):e}function Tn(e,t){let n=t.estimated_tokens;for(let r=0;r<qR;r+=1){t.estimated_tokens=n;let o=Ql(e);if(o===n)return;n=o}t.estimated_tokens=n}function WR(e,t,n,r){for(let o=0;o<VR;o+=1){if(Tn(e,t),t.estimated_tokens<=n)return;let i=hs(e).filter(a=>(Array.isArray(a.value)?a.value.length:Object.keys(a.value).length)>Math.max(1,r.get(a.path)??0)).map(a=>({collection:a,length:Array.isArray(a.value)?a.value.length:Object.keys(a.value).length})).sort((a,c)=>c.length-a.length||a.collection.path.localeCompare(c.collection.path))[0]?.collection;if(!i)return;let s=Math.max(1,r.get(i.path)??0);if(Array.isArray(i.value))i.value.splice(-Math.min(i.value.length-s,Math.max(1,Math.ceil(i.value.length/2))));else{let a=Object.keys(i.value);for(let c of a.slice(-Math.min(a.length-s,Math.max(1,Math.ceil(a.length/2)))))delete i.value[c]}t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],i.path])].sort((a,c)=>a.localeCompare(c)),e.has_more=!0,e.truncated=!0,typeof e.count=="number"&&(e.count=bs(e))}}function lg(e,t,n,r=new Map){let o={compacted:!1},i=Xl(e,o);return t.strings_compacted=o.compacted,i.read_output=t,WR(i,t,n,r),Tn(i,t),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]="3c9694bd-3635-5298-abeb-6899c94317ab")}catch{}})();var To=[...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],KR=Object.fromEntries(To.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function Zl(e){let t=e.trim().toLowerCase();return To.find(n=>n.alias===t)}function YR(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6315a62f-6f55-5200-a5ea-ec892ff39f58")}catch{}})();var dg=[...Qe],ug=[...Gn],fg=[...ci],XR=[...li],JR=[...di],pg=[...ui],ko=["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","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],j5=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],QR=["install","reconcile","report","driver"],mg=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],_g=["upgrade"],gg=["reopen"],ed={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Ye=Object.freeze(ko.flatMap(e=>e in ed?[]:e==="extension"||e==="package"?[...mg.map(t=>`${e}-${t}`),...e==="package"?_g.map(t=>`package-${t}`):[],e]:e==="item"?gg.map(t=>`item-${t}`):[e])),yg=Object.freeze(To.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Ye.includes(e.alias)).map(e=>e.alias)),ZR=Object.freeze(Ye.filter(e=>!yg.includes(e)));function eN(e=ko,t=Ye,n=ed){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function tN(e){return Ye.includes(e)}function nN(e){return dg.includes(e)}function rN(e){return ug.includes(e)}function oN(e){return fg.includes(e)}function iN(e){return pg.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]="1d338971-5a60-5b4e-b4c8-0705c8e8c98c")}catch{}})();var hg=["full","compact","brief","summary","counts"],sN=["mutation","read","discovery","governance"],td=["error","warning","validation_summary","recovery_bundle"],bg=["full","omit_explanation","limit_collections","compact_recovery","action_only"],aN=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"]),cN=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),lN=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),dN={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},uN=3,fN=2,pN=192,mN={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},wg=td.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:mN[e],minimum_max_estimated_tokens:pN,degradation_ladder:bg,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),_N=new Map(wg.map(e=>[e.diagnostic_class,e]));function Eg(e){let[t=""]=e.trim().split(/\s+/u);return aN.has(t)?"mutation":cN.has(t)?"discovery":lN.has(t)?"governance":"read"}function nd(e,t=Eg(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=dN[t];return vg({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*uN/fN)},degradation_ladder:hg,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function vg(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 Tg=ko.map(e=>nd(e)),gN=new Map(Tg.map(e=>[e.command,e]));function rd(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=n.split(" "),o=gN.get(r);return o?{...o,command:n}:t.generateFallback?nd(n):null}function zt(e){return Math.ceil(Math.max(0,e)/4)}function od(e){let t=_N.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${td.join(", ")}`);return t}function Ut(e){return zt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function yN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function id(e){if(!yN(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function hN(e,t){return typeof e!="string"||e.length<=t?e:`${e.slice(0,Math.max(1,t-3))}...`}function mr(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function kg(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var bN=new Set(["limit_collections","compact_recovery","action_only"]),wN=new Set(["compact_recovery","action_only"]);function EN(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:hN(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=id(e.recovery);return n!==void 0?t.recovery=n:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function vN(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),bN.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(wN.has(t)){let r=id(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?kg(n):EN(n)}function _r(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=Ut(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function TN(e,t,n){let r=_r(e,t);for(let i of["recovery","exit_code"])Ut(r)<=n||e[i]===void 0||(delete e[i],r=_r(e,t));let o=40;for(;Ut(r)>n&&o>4;)o-=4,e.code=mr(String(e.code),o),e.required=mr(String(e.required),o),r=_r(e,t);return r}function kN(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>mr(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=id(e.recovery),c=a&&Ut(a)<=48?a:void 0,l={code:mr(String(e.code),320),required:mr(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},d=_r(l,s);for(;Ut(d)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,d=_r(l,s);return d=TN(l,s,t),d}function AN(e,t={}){let n=e,r=t.diagnosticClass??"error",o=od(r),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=Ut(n),c=Object.keys(n);if(a<=s)return kg(structuredClone(n));let l;for(let[d,u]of o.degradation_ladder.entries()){let f=vN(n,u),p=c.filter(y=>!Object.hasOwn(f,y)),_=_r(f,{diagnostic_class:r,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:d>0,degradation_steps:o.degradation_ladder.slice(0,d+1),omitted_fields:p});if(l=_,Ut(_)<=s)break}return Ut(l)>s&&(l=kN(l,s)),l}function SN(e,t,n={}){let r=n.diagnosticClass??"error",o=od(r),i=n.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=zt(Buffer.byteLength(e,"utf8")),c=a>s,l=`What is required:
23
+ `).slice(-4096)];for(let O of E){if(O.length===0||O.length>262144)continue;let P=UI(O);if(b.model??=P.model,b.version??=P.version,b.model&&b.version)break}let T=Object.freeze(b);return Rl.clear(),Rl.set(l,T),T[e]}finally{ot.closeSync(a)}}catch{return}}function qI(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=ot.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=us.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let l=r(c,i+1);if(l)return l}}};return r(e,0)}function VI(e){if(e<=Nl)return[{offset:0,length:e}];let t=Math.floor(Nl/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function GI(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=Q(o?.model)?.slice(0,256),e.effort??=Q(o?.effort)?.slice(0,256)}function BI(e,t){let n={},r=4096;for(let o of VI(t)){let i=Buffer.alloc(o.length);ot.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
24
+ `).reverse().slice(0,r);r-=s.length;for(let a of s)if(GI(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function HI(e,t,n){let r=Q(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=us.join(t.home_dir??z_.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=ds.get(i);if(s)return s[e];let a=qI(o,r);if(!a){ds.set(i,$_);return}try{let c=ot.openSync(a,"r");try{let l=ot.fstatSync(c).size,d=BI(c,l);return ds.set(i,d),d[e]}finally{ot.closeSync(c)}}catch{ds.set(i,$_);return}}function WI(e,t,n,r){let o=ms.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(Q(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return zI(e,t,n);if(s==="codex_session_file")return HI(e,t,n);if(s==="ai_agent_version"){let a=Q(n.AI_AGENT);return!a||!r||!fs(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function KI(e,t,n){if(e==="ai_agent_version"){let r=Q(n.AI_AGENT);return r!==void 0&&fs(r,t.harness)}return e==="codex_session_file"?Q(n.CODEX_THREAD_ID)!==void 0:Q(n.CLAUDE_CODE_SESSION_ID)!==void 0}function jl(e){return e||(q_.getStore()??{env:process.env,argv:process.argv})}function YI(e,t,n,r){let o=e.environment_keys.some(a=>Q(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return fs(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||fs(r,a));return o||i||s}function XI(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function JI(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function QI(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...Pl,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=En(e,Q(n[s])?.slice(0,256)),d=En(e,B_(t.argv??[],e)),l=En(e,FI(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},p=Il(o?.provenance,e),_=En(e,$l(n,u[e])),y=En(e,Il(f,e)),b=En(e,Il(t.provenance,e)),E=WI(e,t,n,r);return JI([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[y,"mcp_client"],[b,"host"],[E,"probe"]])??XI(e,i)??(l?{value:l,source:"argv"}:void 0)}function ZI(e,t){if(!(!e||!t))return DI("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function eR(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...Pl,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let l=QI(c,e,t,n,r,o);l?a[c]=l:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function a5(e){let t=e.map(Vt),n=new Map(G_.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=dr.get(i.harness);if(s&&!MI(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=dr.get(i.harness);dr.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=dr.get(i.harness);!s||s.registrations<=1?dr.delete(i.harness):s.registrations-=1}}}}function tR(e){let t=Vt(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=Q(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>Nl||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(qt(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function nR(){let e=new Map(Ml.map(t=>[t.harness,t]));for(let{adapter:t}of vn.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function rR(e){let t=e.map(tR),n=new Map(Ml.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=vn.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=vn.get(i.harness);vn.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=vn.get(i.harness);!s||s.registrations<=1?vn.delete(i.harness):s.registrations-=1}}}}function oR(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function iR(e,t){return q_.run(e,t)}function sR(e,t,n={}){let r=e.map(Vt);return Fl(r),ms.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function bo(e){let t=jl(e),n=t.env??{},r=Fl(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(_=>YI(_,n,o,i)),a=cs(t,n),c=[$l(n,s?.session_environment_keys),Q(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=ZI(s?.harness,c),d=F_({cwd:t.cwd??process.cwd(),env:n,key:l}),u=eR(t,n,s,a,d),f=u.model,p=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",l],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(p.filter(_=>_[1]!==void 0))}function aR(e,t,n,r,o,i){let s=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...s?{resolver:s}:{},rule_version:"v1"};if(i)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(s){let a=KI(s,n,r);return{status:a&&o?"failed":"unavailable",reason:a?o?"resolver_failed":"probes_disabled":"harness_unavailable",resolver:s,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function Ul(e){let t=jl(e),n=bo(t),r=Fl(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&ms.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(Q(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=cs(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,$l(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,B_(t.argv??[],"role")].some(l=>{let d=Q(l)?.slice(0,256);return d!==void 0&&En("role",d)===void 0}),c=Object.fromEntries(Pl.map(l=>[l,aR(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function zl(){return process.env.PM_AUTHOR}function cR(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function c5(e){return bo(e).harness}function lR(e,t,n){let r=jl(n),o=bo(r);if(e!==void 0){let s=Q(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=Q(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=Q(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function H_(e){let t=ps.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function W_(e){let t=ps.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 ql(e){let t=ps.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function wo(e,t){let n=lR(e,t);return ps.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 Xe(e,t){let n=await Y(e);if(n===null)return[];if(await Ke({path:e,scope:"project"}),n.trim()==="")return[];let r=os(n);if(r)throw new h(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,g.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 h(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,g.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]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();var _s="changed_fields",dR="changed_field_count",Vl="rows",uR=new Set(["apply","rollback"]),X_=new Set(["deleted","would_delete"]),K_=256;function Y_(e){return typeof e!="string"||e.length<=K_?e:`${e.slice(0,K_-1)}\u2026`}function fR(e){if(!Et(e))return null;let t={...e};return t.reason=Y_(t.reason),Et(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Y_(r)]))),t}function Et(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function J_(e){let t=e[_s];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==_s&&(n[r]=o);return n[dR]=t.length,n}function pR(e){return"item"in e&&Array.isArray(e[_s])}function mR(e){return typeof e.mode=="string"&&uR.has(e.mode)&&Array.isArray(e[Vl])}function _R(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[Vl]=t,n}function gR(e){if(!Et(e))return null;let t=Et(e.item)?e.item:Et(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"&&X_.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 yR(e){if(!Et(e)||!Et(e.item)||typeof e.item.id!="string")return null;let t=e[_s];if(!Array.isArray(t))return null;let n={id:e.item.id,...typeof e.outcome=="string"&&X_.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;r!==void 0&&(n.close_reason=r);let o=fR(e.recurrence);return o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings),n}function hR(e){let t=mR(e)?e[Vl]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!Et(o))return o;let i=J_(o);return i?(n=!0,i):o});return n?{projected:_R(e,r),changed:!0}:{projected:e,changed:!1}}function gs(e,t={}){if(t.idOnly===!0){let a=gR(e);if(a!==null)return a}if(t.compactEnvelope===!0){let a=yR(e);if(a!==null)return a}if((t.changedFields??"full")==="full"||!Et(e))return e;let r=!1,o=e,i=pR(e)?J_(e):null;i!==null&&(o=i,r=!0);let s=hR(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]="288a7da9-888b-527d-88fb-4711917cec5b")}catch{}})();var bR=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},wR=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?bR(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,Gl=(e,t=process.platform)=>{let n=e.map(r=>wR(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"},ER=new Set(["--literal","--regex","--replacement"]);function y5(e){if(!e.includes("history-redact"))return[...e];let t=[],n=!1;for(let r of e){if(n&&!r.startsWith("-")){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!ER.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!0}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();var tg=new WeakMap;function E5(e,t){tg.set(e,new Set(t))}var Q_='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',vR={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:["activity_digest","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"}},TR=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function v5(e,t,n){if(e&&t)throw new h(`${n} cannot be combined with --full`,g.USAGE)}function it(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 T5(e,t){let n=TR.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return it([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return it(r)}var kR=[{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 Ue(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var AR=new Set([void 0,"tabular_when_uniform"]),SR=new Set(["collection","none"]),xR=new Set(["supported","unsupported"]);function Z_(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function CR(e){return Ue(e)&&typeof e.command=="string"&&e.command.trim().length>0&&SR.has(e.row_kind)&&Z_(e.row_keys,!0)&&(e.continuation_row_keys===void 0||Z_(e.continuation_row_keys,!1))&&xR.has(e.fields)&&AR.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var OR={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"]},IR={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:["activity_digest","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 RR(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=OR[s];if(a===void 0)return;let c=a.filter(l=>Array.isArray(t[l])||Ue(t[l]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:Q_}:{},toon_encoding:"tabular_when_uniform"}}let o=vR[r],i=IR[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((l,d)=>Ue(l)?l[d]:void 0,t);return Array.isArray(c)||Ue(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:Q_}:{},toon_encoding:"tabular_when_uniform"}})()}function NR(e){if(!Ue(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=>Ue(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 it(r,new Set(o))}function DR(e){if(Array.isArray(e.sections_included))return it(kR,new Set(e.sections_included.filter(t=>typeof t=="string")))}function PR(e){if(!Ue(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=tg.get(e),i=a=>n.includes(a)||a==="body"?t:e,s=["body",...n,...r.slice(1)].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:`--fields ${a}`}));return it(s,new Set(s.flatMap(({name:a})=>Object.hasOwn(i(a),a)?[a]:[])))}function eg(e){if(Ue(e.projection))return it([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function LR(e){if(!Ue(e.projection))return it([]);if(typeof e.projection.mode=="string")return it([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function MR(e){if(!(!Ue(e.selected)||typeof e.selected.summary!="boolean"))return it([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function FR(e,t){let n=NR(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return DR(t);if(r==="get")return PR(t);if(r==="list"||r.startsWith("list-"))return eg(t);if(r==="search")return eg(t)??it([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return LR(t);if(r==="contracts")return MR(t)}function ng(e,t){if(e===void 0||!Ue(t))return t;let n=FR(e,t),r=t.row_contract,o=CR(r)?r:RR(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return Ue(i.omission_receipt)||n===void 0?i:{...i,omission_receipt:n}}import{createHash as $R}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]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var Bl=1,og=4096,jR=/^[A-Za-z0-9_-]+$/;function rg(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function O5(e,t){let n=new Set;for(let r of t)if(r.cursor_semantics==="presentation"){n.add(rg(r.flag));for(let o of r.aliases??[])n.add(rg(o))}return Object.fromEntries(Object.entries(e).filter(([r])=>!n.has(r)))}function I5(e,t){return $R("sha256").update(e).update("\0").update(B(t)).digest("hex").slice(0,24)}function Eo(e,t,n,r){return Buffer.from(JSON.stringify({version:Bl,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function Tn(e){return new h(e,g.USAGE,{code:"invalid_query_cursor",nextSteps:["Repeat the original query without --after to obtain a fresh cursor."]})}function UR(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Bl&&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 Hl(e){if(typeof e!="string")throw Tn("Query cursor is malformed.");let t=e.trim();if(t.length===0||t.length>og||!jR.test(t))throw Tn("Query cursor is malformed.");let n;try{n=JSON.parse(Buffer.from(t,"base64url").toString("utf8"))}catch{throw Tn("Query cursor is malformed.")}if(!UR(n))throw Tn("Query cursor version or payload is unsupported.");return n}function Wl(e,t){let n=Hl(e);if(n.fingerprint!==t)throw Tn(`Query cursor does not match the current filters, sort, or query (${n.fingerprint} != ${t}).`);return{after_id:n.after_id,...n.after_index===void 0?{}:{after_index:n.after_index},...n.snapshot===void 0?{}:{snapshot:n.snapshot}}}function R5(e,t){return Wl(e,t).after_id}function zR(e,t,n,r){if(t===void 0)return 0;let o=Wl(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 Tn(`Query cursor item ${o.after_id} is no longer present in this result set.`)}return i+1}function N5(e,t){if(t.cursor!==void 0&&Wl(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Tn("Query cursor does not match the requested snapshot.");let n=zR(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:Eo(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var D5=Object.freeze({version:Bl,max_length:og});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="810d42b5-98f4-57a7-bdd9-2dfa1b2b1c03")}catch{}})();var qR=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function ur(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ig(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!ur(n))return;n=n[r]}return n}function Kl(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[s];if(Array.isArray(i)){let l=Number(a),d=[...i];return d[l]=o(i[l],s+1),d}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function sg(e,t,n){let r=pr(e).find(i=>i.path===t);if(!r)return e;let o=Array.isArray(r.value)?r.value.slice(n):Object.fromEntries(Object.entries(r.value).slice(n));return Kl(e,t,o)}function ys(e){let t=e.row_contract;return ur(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function VR(e){let t=e.row_contract;return ur(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):ys(e)}function fr(e){return ys(e).flatMap(t=>{let n=ig(e,t);return Array.isArray(n)||ur(n)?[{path:t,value:n}]:[]})}function pr(e){return VR(e).flatMap(t=>{let n=ig(e,t);return Array.isArray(n)||ur(n)?[{path:t,value:n}]:[]})}function hs(e){let t=fr(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(ur(o))for(let[s,a]of Object.entries(o))i.length===0&&qR.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function bs(e){return fr(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function vo(e,t){let n=e;for(let r of fr(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=Kl(n,r.path,o)}return n}function ag(e,t){let n=e,r=!1;for(let o of fr(n)){let i=Array.isArray(o.value)?o.value:Object.entries(o.value);if(i.length<=t)continue;r=!0;let s=Array.isArray(o.value)?i.slice(0,t):Object.fromEntries(i.slice(0,t));n=Kl(n,o.path,s)}return{result:n,truncated: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]="02a0bd0c-6ab0-5193-807b-00394a4712b7")}catch{}})();var GR=8,BR=64,HR=5,WR=4,cg=100;function Xl(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*HR/WR),i=Math.ceil(o/cg)*cg;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function Jl(e){return Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4)}function KR(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Yl(e,t){return typeof e=="string"?e.length<=240?e:(t.compacted=!0,`${e.slice(0,240)}\u2026`):Array.isArray(e)?e.map(n=>Yl(n,t)):KR(e)?Object.fromEntries(Object.entries(e).map(([n,r])=>[n,Yl(r,t)])):e}function kn(e,t){let n=t.estimated_tokens;for(let r=0;r<GR;r+=1){t.estimated_tokens=n;let o=Jl(e);if(o===n)return;n=o}t.estimated_tokens=n}function YR(e,t,n,r){for(let o=0;o<BR;o+=1){if(kn(e,t),t.estimated_tokens<=n)return;let i=hs(e).filter(a=>(Array.isArray(a.value)?a.value.length:Object.keys(a.value).length)>Math.max(1,r.get(a.path)??0)).map(a=>({collection:a,length:Array.isArray(a.value)?a.value.length:Object.keys(a.value).length})).sort((a,c)=>c.length-a.length||a.collection.path.localeCompare(c.collection.path))[0]?.collection;if(!i)return;let s=Math.max(1,r.get(i.path)??0);if(Array.isArray(i.value))i.value.splice(-Math.min(i.value.length-s,Math.max(1,Math.ceil(i.value.length/2))));else{let a=Object.keys(i.value);for(let c of a.slice(-Math.min(a.length-s,Math.max(1,Math.ceil(a.length/2)))))delete i.value[c]}t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],i.path])].sort((a,c)=>a.localeCompare(c)),e.has_more=!0,e.truncated=!0,typeof e.count=="number"&&(e.count=bs(e))}}function lg(e,t,n,r=new Map){let o={compacted:!1},i=Yl(e,o);return t.strings_compacted=o.compacted,i.read_output=t,YR(i,t,n,r),kn(i,t),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]="3c9694bd-3635-5298-abeb-6899c94317ab")}catch{}})();var To=[...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","packages catalog"],["packages scaffold","packages init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],XR=Object.fromEntries(To.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function Ql(e){let t=e.trim().toLowerCase();return To.find(n=>n.alias===t)}function JR(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6315a62f-6f55-5200-a5ea-ec892ff39f58")}catch{}})();var dg=[...tt],ug=[...Gn],fg=[...ci],QR=[...li],ZR=[...di],pg=[...ui],ko=["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","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],z5=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],eN=["install","reconcile","report","driver"],mg=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],_g=["upgrade"],gg=["reopen"],Zl={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},Je=Object.freeze(ko.flatMap(e=>e in Zl?[]:e==="extension"||e==="package"?[...mg.map(t=>`${e}-${t}`),...e==="package"?_g.map(t=>`package-${t}`):[],e]:e==="item"?gg.map(t=>`item-${t}`):[e])),yg=Object.freeze(To.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&Je.includes(e.alias)).map(e=>e.alias)),tN=Object.freeze(Je.filter(e=>!yg.includes(e)));function nN(e=ko,t=Je,n=Zl){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function rN(e){return Je.includes(e)}function oN(e){return dg.includes(e)}function iN(e){return ug.includes(e)}function sN(e){return fg.includes(e)}function aN(e){return pg.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]="1d338971-5a60-5b4e-b4c8-0705c8e8c98c")}catch{}})();var hg=["full","compact","brief","summary","counts"],cN=["mutation","read","discovery","governance"],ed=["error","warning","validation_summary","recovery_bundle"],bg=["full","omit_explanation","limit_collections","compact_recovery","action_only"],lN=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"]),dN=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),uN=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),fN={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},pN=3,mN=2,_N=192,gN={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},wg=ed.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:gN[e],minimum_max_estimated_tokens:_N,degradation_ladder:bg,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),yN=new Map(wg.map(e=>[e.diagnostic_class,e]));function Eg(e){let[t=""]=e.trim().split(/\s+/u);return lN.has(t)?"mutation":dN.has(t)?"discovery":uN.has(t)?"governance":"read"}function td(e,t=Eg(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=fN[t];return vg({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*pN/mN)},degradation_ladder:hg,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function vg(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 Tg=ko.map(e=>td(e)),hN=new Map(Tg.map(e=>[e.command,e]));function nd(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=n.split(" "),o=hN.get(r);return o?{...o,command:n}:t.generateFallback?td(n):null}function Bt(e){return Math.ceil(Math.max(0,e)/4)}function rd(e){let t=yN.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${ed.join(", ")}`);return t}function Gt(e){return Bt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function bN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function od(e){if(!bN(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function wN(e,t){return typeof e!="string"||e.length<=t?e:`${e.slice(0,Math.max(1,t-3))}...`}function mr(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function kg(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var EN=new Set(["limit_collections","compact_recovery","action_only"]),vN=new Set(["compact_recovery","action_only"]);function TN(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:wN(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=od(e.recovery);return n!==void 0?t.recovery=n:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function kN(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),EN.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(vN.has(t)){let r=od(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?kg(n):TN(n)}function _r(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=Gt(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function AN(e,t,n){let r=_r(e,t);for(let i of["recovery","exit_code"])Gt(r)<=n||e[i]===void 0||(delete e[i],r=_r(e,t));let o=40;for(;Gt(r)>n&&o>4;)o-=4,e.code=mr(String(e.code),o),e.required=mr(String(e.required),o),r=_r(e,t);return r}function SN(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>mr(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=od(e.recovery),c=a&&Gt(a)<=48?a:void 0,l={code:mr(String(e.code),320),required:mr(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},d=_r(l,s);for(;Gt(d)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,d=_r(l,s);return d=AN(l,s,t),d}function xN(e,t={}){let n=e,r=t.diagnosticClass??"error",o=rd(r),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=Gt(n),c=Object.keys(n);if(a<=s)return kg(structuredClone(n));let l;for(let[d,u]of o.degradation_ladder.entries()){let f=kN(n,u),p=c.filter(y=>!Object.hasOwn(f,y)),_=_r(f,{diagnostic_class:r,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:d>0,degradation_steps:o.degradation_ladder.slice(0,d+1),omitted_fields:p});if(l=_,Gt(_)<=s)break}return Gt(l)>s&&(l=SN(l,s)),l}function CN(e,t,n={}){let r=n.diagnosticClass??"error",o=rd(r),i=n.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=Bt(Buffer.byteLength(e,"utf8")),c=a>s,l=`What is required:
25
25
  `,d=`
26
26
 
27
- Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,u=t.trim()||"Inspect the diagnostic code and retry with corrected input.",f=Math.max(1,s*4-Buffer.byteLength(`${l}${d}`,"utf8")),p=c?`${l}${mr(u,f)}${d}`:e;return{output:p,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,estimated_tokens:zt(Buffer.byteLength(p,"utf8")),truncated:c,degradation_steps:c?[...o.degradation_ladder]:["full"],omitted_fields:c?["explanation","collections"]:[]}}}import{createHash as a0}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]="642f6dec-c0b2-5377-a401-dfa4f8ef6a2a")}catch{}})();var sd=256,Ao=1e4,xN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,CN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,ON=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),IN=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&xN.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=sd,reason:`token_budget must be a safe integer of at least ${sd}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=Ao&&e.seen_item_ids.every(t=>typeof t=="string"&&CN.test(t)),reason:`seen_item_ids must contain at most ${Ao} portable item identifiers.`}];function Es(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ws(e){throw new h(`--output-session ${e}`,g.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function vs(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{ws("must be a valid JSON object.")}Es(t)||ws("must be a JSON object.");let n=Object.keys(t).filter(i=>!ON.has(i));n.length>0&&ws(`contains unknown field "${n.sort()[0]}".`);let r=IN.find(i=>!i.valid(t));r!==void 0&&ws(r.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function Ag(e){if(Es(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Es(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function RN(e){let t=new Set,n=0;for(let r of fr(e)){let o=Array.isArray(r.value)?r.value:Object.values(r.value);for(let i of o){if(!Es(i))continue;if(typeof i.context_ref=="string"){n+=1;continue}let s=Ag(i);s!==void 0&&t.add(s)}}return{deliveredIds:t,suppressedRepeatCount:n}}function Sg(e,t){let n=new Set(t.seen_item_ids);return vo(e,r=>{let o=Ag(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function ad(e,t){let{deliveredIds:n,suppressedRepeatCount:r}=RN(e),o=new Set(t.seen_item_ids),i=[...n].filter(_=>!o.has(_)).sort(),s=i.slice(0,Ao-t.seen_item_ids.length),a=[...t.seen_item_ids,...s].sort(),c=i.length-s.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:n.size,...c===0?{}:{seen_item_overflow_count:c},suppressed_repeat_count:r,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:a}},d={...e,read_session:l},u=_=>{l.spent_this_call_tokens=_,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,_),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<sd,l.next_state.spent_tokens=l.spent_total_tokens},f=0,p=0;for(let _=0;_<8;_+=1){u(f);let y=Math.ceil(Buffer.byteLength(JSON.stringify(d),"utf8")/4);if(y===f)return d;p=Math.max(p,y),f=y}return u(p),d}function xg(e){return Math.max(0,e.token_budget-e.spent_tokens)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2103a4dc-3037-5768-b2c7-5964de4ac86b")}catch{}})();var kn=["include","amount","cost","encoding"],Mg=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"],Fg=["canonical","legacy","intent","default"],xo={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},cd=Symbol.for("pm.readOutputInvocationProvenance"),$g=Object.freeze(kn.map(e=>xo[e])),jg=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Ug={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},zg=new Set(["--collapse","--fields","--section"]),ud=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function fd(e){return e.slice(2).replaceAll("-","_")}function NN(e,t){let n=ud[e];if(n!==void 0)return n;let r=t==="include"?zg.has(e)?"<csv>":fd(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${xo[t]} ${r}.`}function DN(e){let t=Ug[e],n=Object.freeze(Object.fromEntries(kn.map(r=>[r,Object.freeze({dimension:r,canonical_option:xo[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:ud[o]===void 0?"replacement":"behavior_preserving",migration_hint:NN(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Fg,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...pd(e).keys()])})}var PN=Object.freeze(Mg.map(DN)),LN=new Map(PN.map(e=>[e.command,e]));function rt(e,t={}){let n=e.trim().toLowerCase().replaceAll(/\s+/gu," "),o=n==="package catalog"||n==="packages catalog"||n==="package-catalog"||(n==="package"||n==="packages"||n==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":n==="package manage"||n==="package-manage"?"package-manage":n.split(" ")[0],i=o.startsWith("list-")?"list":o==="ctx"?"context":o;return Mg.includes(i)?i:void 0}var MN=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],FN={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function $N(e){return MN.some(t=>e[t]!==void 0)}var jN=[{keys:["outputInclude","output_include"],valid:e=>So(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||gr(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||gr(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputFormat","output_format"],valid:e=>e==="toon"||e==="json",message:"--output-format must be toon or json."},{keys:["outputSession","output_session"],valid:e=>(vs(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function tH(e,t){if(!$N(t))return;let n=rt(e,t);if(!n)throw new h(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,g.USAGE);if((FN[n]??[]).some(r=>t[r]!==void 0&&t[r]!==!1))throw new h(`Universal output controls cannot be combined with a ${n} mutation.`,g.USAGE);for(let r of jN){let o=r.keys.map(i=>t[i]).find(i=>i!==void 0);if(o!==void 0&&!r.valid(o))throw new h(r.message,g.USAGE)}}function pd(e){let t=rt(e);return t?new Map((Ug[t].include??[]).filter(n=>!zg.has(n)&&ud[n]===void 0).map(n=>[fd(n),qg(n)])):new Map}function UN(e,t,n){let r=So(t)??[],o=pd(e),i=[],s=[],a=n,c=a[cd],l=new Set(c?.canonical_include_modes??[]),d=new Set(c?.explicit_legacy_aliases??[]);for(let p of r){let _=o.get(p);if(_===void 0){i.push(p);continue}let y=`--${p.replaceAll("_","-")}`;Gg(Vg(n,y))&&d.add(y),n[_]=!0,s.push(p),l.add(p)}let u=rt(e)==="get"?i.filter(p=>p!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...So(n.fields)??[],...u])].join(","),l.add("fields")),(s.length>0||f)&&(a[cd]={canonical_include_modes:[...l],explicit_legacy_aliases:[...d],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function nH(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=UN(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function qg(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function Vg(e,t){let n=qg(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 Gg(e){return e!==void 0&&e!==!1&&e!==null}function So(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 gr(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 zN(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=Vg(t,o.flag),s={value:i,flag:o.flag};if(Gg(i)&&n(s))return s}}function Cg(e,t){let n=So(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:So(t.value)??[fd(t.flag)]}}function Og(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=gr(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=gr(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Ig(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=gr(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=gr(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Rg(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 qN(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function VN(e,t,n){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function GN(e,t){return kn.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[xo[n]]:[])}function Bg(e,t){let n=rt(e,t);if(!n)return;let r=LN.get(n),o=t[cd],i={include:T=>Cg(void 0,T),amount:T=>Og(void 0,T),cost:T=>Ig(void 0,T),encoding:T=>Rg(void 0,T)},s=Object.fromEntries(kn.map(T=>[T,zN(r.dimensions[T],t,O=>i[T](O)!==void 0,O=>qN(o,T,O))])),a=kn.flatMap(T=>{let O=s[T];return O?[O.flag]:[]}),c=kn.flatMap(T=>{let O=s[T];return O?[r.dimensions[T].legacy_aliases.find(W=>W.flag===O.flag).migration_hint]:[]}),l=Rg(t.outputFormat??t.output_format,s.encoding),d=Cg(t.outputInclude??t.output_include,s.include),u=Og(t.outputLimit??t.output_limit,s.amount),f=Ig(t.outputBudget??t.output_budget,s.cost),p=VN(e,s,o),_=rd(e,{generateFallback:!0}),y=l?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",b=f??(p?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:n,include:d,amount:u,cost:b,encoding:l,canonical_options_used:GN({include:d,amount:u,cost:b,encoding:l},o),legacy_aliases_used:a,migration_hints:c,precedence:Fg}}function Xe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var md=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),BN=["collection_counts","notes_count","tests_count"];function Hg(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function HN(e){let t=Xe(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...BN.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!md.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function WN(e,t){let n=HN(e),r=t.filter(u=>!n.valid.includes(u));if(r.length>0)throw new h(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,g.USAGE);let o=t.includes("item"),i=t.flatMap(u=>u.startsWith("item.")?[u.slice(5)]:n.itemFields.includes(u)?[u]:[]).filter((u,f,p)=>p.indexOf(u)===f);if(o&&i.length>0)throw new h("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",g.USAGE);let s=new Set(t.filter(u=>n.sections.includes(u))),a=Object.fromEntries(Object.entries(e).filter(([u])=>md.has(u)||s.has(u)));o?a.item=n.item:i.length>0&&(a.item=Hg(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(u=>!i.includes(u)).map(u=>({name:`item.${u}`,restore_with:`--output-include item.${u}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(u=>!s.has(u)).map(u=>({name:u,restore_with:`--output-include ${u}`}))],d=[...Xe(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function Ng(e){let t=0;return vo({...e},n=>(Xe(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function KN(e,t,n,r){if(Ng(t)===0||Ng(n)>0)return;let o=[...pd(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new h(`Unknown --output-include selector(s) for ${e}: ${r.join(", ")}. No selector matched any returned row field.${i}`,g.USAGE)}function YN(e,t,n){if(e==="get")return WN(t,n);let r=ys(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=vo(s,l=>Xe(l)?Hg(l,a):l);return KN(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||md.has(s)))}function XN(e,t){if(t==="unbounded")return e;let{result:n,truncated:r}=ag(e,t);return r&&(n.has_more=!0,n.truncated=!0,typeof n.count=="number"&&(n.count=bs(n)),n.applied_bound={kind:"output_limit",source:"explicit",value:t}),n}function JN(e){return kn.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(xo[t]))}function ks(e,t,n){let r=ad(e,t);for(let o=0;o<8;o+=1){let i=n.estimated_tokens,s=r.read_session.spent_this_call_tokens;Tn(r,n),r=ad(r,t);let a=r.read_session.spent_this_call_tokens;if(n.estimated_tokens===i&&a===s)return r}return r}function Wg(e,t){if(!Xe(e.read_output))return e;let n=e.read_output,r=vs(t.outputSession??t.output_session);return r===void 0?(Tn(e,n),e):ks(e,r,n)}function QN(e,t){if(e!=="validate")return t;let n=Xe(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(u=>Xe(u)&&u.name==="diagnostic_rows"))return t;let o=[...new Set(hs(t).map(({path:u})=>u).filter(u=>/^checks\.\d+\.details\./u.test(u)))],i=o.filter(u=>!o.some(f=>f!==u&&u.startsWith(`${f}.`)));if(i.length===0)return t;let s=Xe(t.row_contract)?t.row_contract:{},a=Array.isArray(s.row_keys)?s.row_keys.filter(u=>typeof u=="string"):[],c=Array.isArray(s.continuation_row_keys)?s.continuation_row_keys.filter(u=>typeof u=="string"):[],l=a.length>0?a:i,d=[...new Set(i)];return JSON.stringify(l)===JSON.stringify(a)&&JSON.stringify(d)===JSON.stringify(c)?t:{...t,row_contract:{...s,row_keys:l,continuation_row_keys:d,jq_selector:typeof s.jq_selector=="string"?s.jq_selector:".checks[].details"}}}function ZN(e,t,n,r){let o={...e};return t.include?.source==="canonical"&&(o=YN(t.command,o,t.include.value)),t.command==="assurance"&&(o=Pg(o)),o=Lg(o,t.command,r),t.amount?.source==="canonical"&&(o=XN(o,t.amount.value)),n===void 0?o:Sg(o,n)}function e0(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:xg(t)}]].sort((r,o)=>r.tokens-o.tokens)[0]}function Kg(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function t0(e,t,n,r,o){let i={contract_version:1,command:e.command,requested_dimensions:t,...r.source==="default"?{budget_source:r.source,budget_tokens:r.tokens}:{},precedence:e.precedence,...Kg(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:o}:{}},s={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:i},a=n===void 0?s:ks(s,n,i);if(n===void 0&&Tn(a,i),n!==void 0&&i.estimated_tokens>r.tokens)throw new h("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",g.USAGE);return a}function n0(e,t,n){if(t!==void 0)return!1;let r=e.canonical_options_used.length;return e.cost?.value==="unbounded"?r===(e.cost.source==="canonical"?1:0):e.cost?.source==="legacy"&&r===0?!0:r===0&&(e.cost===void 0||Ql(n)<=e.cost.value)}function r0(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(pr(e).map(f=>[f.path,Array.isArray(f.value)?f.value.length:Object.keys(f.value).length])),l=[...s.entries()].flatMap(([f,p])=>{let _=c.get(f);if(_>=p.rows)return[];let y=p.baseOffset+_;return[{path:f,cursor:ld({command:t.command,path:f,offset:y,total_rows:p.totalRows,fingerprint:p.fingerprint}),retained_rows:_,remaining_rows:p.totalRows-y,total_rows:p.totalRows}]}),d=l[0],u=Jl({effective_budget_tokens:r.tokens,measured_result_tokens:i});d&&typeof e.next_cursor!="string"&&(e.next_cursor=d.cursor),e.continuation_kind=o?"producer_cursor":d?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:l.length>0,recovery_budget_multiplier:d?1:u.recovery_budget_multiplier,continuations:l,restore_with:d?"Use recovery binding.":`Retry with --output-budget ${u.output_budget} because no declared row collection can be continued.`,recovery:d?{cursor:d.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${u.output_budget}`,sdk:{outputBudget:u.output_budget},mcp:{outputBudget:u.output_budget}}}}function o0(e,t,n,r){if(typeof n!="string"||!Array.isArray(e.items))return!1;let o=e.items.length;if(o===0||o>=t)return!1;let i;try{i=Wl(n)}catch{return!1}let s=i.after_index;if(s===void 0)return!1;let a=e.items.at(-1);if(Object.prototype.toString.call(a)!=="[object Object]")return!1;let c=Reflect.get(a,"id");if(typeof c!="string"||c.length===0)return!1;let l=r?s-(t-o):s+o;return l<0?!1:(e.next_cursor=Eo(i.fingerprint,c,l,i.snapshot),typeof e.applied_limit=="number"&&(e.applied_limit=o),!0)}function i0(e,t,n,r){let o=new Map(pr(e).map(s=>{let a=Array.isArray(s.value)?s.value.length:Object.keys(s.value).length,c=n?.path===s.path;return[s.path,{rows:a,totalRows:c?n.total_rows:a,baseOffset:c?n.offset:0,fingerprint:c?n.fingerprint:Ts(s.path,s.value,t)}]})),i=typeof e.next_cursor=="string";return{collectionsBeforeBudget:o,originalItemCount:Array.isArray(e.items)?e.items.length:0,cursorContinuesExistingPage:i,cursorSource:i?e.next_cursor:r.after}}function s0(e,t,n,r,o,i,s){let a=t.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(d=>Xe(d)&&d.verdict!=="pass").length:0,c=lg(e,n,r.tokens,a>0?new Map([["assertions",a]]):new Map),l=o0(c,i.originalItemCount,i.cursorSource,i.cursorContinuesExistingPage);return r0(c,t,n,r,l,s,i.collectionsBeforeBudget),o!==void 0&&(c=ks(c,o,n)),c}function Yg(e,t,n){let r=Bg(e,t);if(!r)return n;let o=vs(t.outputSession??t.output_session),i=t.outputCursor??t.output_cursor,s=typeof i=="string"?dd(i):void 0,a=JN(r);if(s===void 0&&n0(r,o,n))return n;let c=QN(r.command,n),l=e0(r,o),d=ZN(c,r,o,s),u=i0(d,r.command,s,t),f={contract_version:1,command:r.command,requested_dimensions:a,...l?.source==="default"?{budget_source:l.source,budget_tokens:l.tokens}:{},precedence:r.precedence,...Kg(r),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};if(d.read_output=f,d=o===void 0?d:ks(d,o,f),Tn(d,f),l!==void 0&&f.estimated_tokens>l.tokens){let p=f.estimated_tokens;d=s0(d,r,f,l,o,u,p)}return l!==void 0&&f.estimated_tokens>l.tokens?t0(r,a,o,l,f.estimated_tokens):d}function Xg(e){return Xe(e)&&Xe(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function Jg(e,t){let n=Bg(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var c0=4096,l0=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),Dg=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:l0}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Co(e){return Array.isArray(e)?e.map(Co):Oo(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Co(n)])):e}function Qg(e,t){if(!Oo(e))return Co(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Oo(i)?[o,Co(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Co(a)]))]))}function d0(e,t){return Array.isArray(e)?e.map(n=>Qg(n,t)):Qg(e,t)}function Ts(e,t,n){let r=n?Dg[n]:void 0,o=r?.paths.includes(e)===!0;return a0("sha256").update(K({path:e,value:o?d0(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function ld(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint}),"utf8").toString("base64url")}function dd(e){if(e.length>c0)throw new h("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!Oo(t)||t.v!==1||rt(String(t.c??""))!==t.c||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0)throw new h("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f}}function Pg(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Oo(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function Lg(e,t,n){if(!n)return e;if(n.command!==t)throw new h(`The read-output cursor belongs to ${n.command}, not ${t}.`,g.USAGE,{code:"read_output_cursor_command_mismatch"});let r=pr(e).find(i=>i.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0;if(!r||o!==n.total_rows||n.offset>o||Ts(n.path,r.value,t)!==n.fingerprint)throw new h("The read-output continuation no longer matches the declared row collection; restart the bounded read.",g.USAGE,{code:"read_output_cursor_stale"});return sg(e,n.path,n.offset)}import{AsyncLocalStorage as u0}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]="da15ca02-02cc-5886-8c82-610939b8581c")}catch{}})();var ey=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),ty=new u0;function f0(){return ty.getStore()??ey}function wH(e,t){return ty.run(m0(e.workspaceContracts,e.packageContracts),t)}function p0(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 m0(e=[],t=[]){let n=[{source:"core",contracts:ey,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=p0(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 ny(e,t,n=f0(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let p=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=p[0];p[0]=_;for(let b=1;b<=i.length;b+=1){let E=p[b];p[b]=Math.min(p[b]+1,p[b-1]+1,y+(f[_-1]===i[b-1]?0:1)),y=E}}return{candidate:f,distance:p[i.length]}}).sort((f,p)=>f.distance-p.distance||f.candidate.localeCompare(p.candidate))[0].candidate,l=[o,...r,"--for",i],d=[o,...r,"--for",c],u=Bl(d);throw new h(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,g.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:Bl(l),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:d}})}var ry={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=Ss(e.tokenBudget,t.token_budget),o=xs("context",t.intent,r,n),i=An(e.limit),s=String(i===void 0?o:Math.min(i,o));(e.limit===void 0||i!==void 0)&&(e.limit=s),e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let r=Ss(e.tokenBudget,t.token_budget),o=xs("list",t.intent,r,n),i=An(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let r=Ss(e.tokenBudget,t.token_budget),o=xs("search",t.intent,r,n),i=An(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))}};function EH(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==void 0&&(e==="get"||e==="list"||e==="search"))throw new h("--token-budget requires a declared context intent selected with --for",g.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let a={...t,tokenBudget:r};return delete a.token_budget,a}let o=ny(e,t.for,void 0,n),i=An(r)!==void 0,s={...t};return s.tokenBudget===void 0&&r!==void 0&&(s.tokenBudget=r),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),ry[e](s,o,i),s}var _0={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},As=256;function _d(e){return Array.isArray(e)?e.map(_d):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,_d(n)])):typeof e=="string"&&e.length>240?`${e.slice(0,240)}\u2026`:e}function An(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 Ss(e,t){let n=An(e);if(n===void 0)return t;if(n<As)throw new h(`Context intent token budget must be at least ${As}`,g.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${As}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${As} or omit the override.`]});return n}function xs(e,t,n,r){if(e==="get"||e==="next")return;let o=e==="context"&&t==="orient",i=e==="context"?o?1200:800:e==="list"?520:480,s=e==="context"?o?600:500:16,a=Math.max(e==="context"?1:2,Math.floor((n-i)/s));return r?a:Math.min(e==="context"?20:100,a)}function qt(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 Zg={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 oy(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 g0(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 y0(e,t,n){let r=!1;for(;;){if(qt(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 h0(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=oy(i);if(s===void 0)return!1;let a=r.length,c=[...r],l=!1;for(;;){if(l=y0(e,t,r)||l,!l)return!1;let d=g0(r.at(-1));if(d===void 0)return r.splice(0,r.length,...c),qt(e,t),!1;if(e.next_cursor=Eo(s.fingerprint,d,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),qt(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 b0(e,t,n,r){if(e==="list"||e==="search")return h0(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(qt(t,n),n.estimated_tokens<=n.token_budget)return o;let i=Zg[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,p)=>p.rows.length-f.rows.length||f.key.localeCompare(p.key))[0];if(i===void 0)return o;let s=Zg[e].reduce((f,p)=>f+(Array.isArray(t[p])?t[p].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"),l=Math.max(1,Math.ceil(c/i.rows.length)),d=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(d/l)));i.rows.splice(-u,u),o=!0}}function w0(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in ry))return n;let o=r,i=ny(o,t.for),s=Ss(t.tokenBudget??t.token_budget,i.token_budget),a={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:s,declared_token_budget:i.token_budget,token_budget_override:s-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:_0[o],declaration_feasible:!0,result_omitted:!1},c={...n},l=xs(o,i.intent,a.token_budget,An(t.tokenBudget??t.token_budget)!==void 0);if(l!==void 0){let u=An(t.limit),f=u!==void 0&&u<l;a.budget_derived_limit=l,a.binding_constraint=f?"explicit_limit":"token_budget",a.limit_reason=f?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",c.budget_derived_limit=l}let d={...c,context_intent:a};return qt(d,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",d={..._d(c),context_intent:a},qt(d,a)),a.estimated_tokens>a.token_budget&&b0(o,d,a,t)&&(a.degradation="budget_row_compaction",qt(d,a)),a.declaration_feasible=a.estimated_tokens<=a.declared_token_budget,a.estimated_tokens>a.token_budget&&(a.degradation="budget_receipt_only",a.result_omitted=!0,a.within_budget=!1,d={budget_exceeded:{omitted_result:!0,reason:a.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:v0(e,o,i.intent,a,c)},context_intent:a}),d}function E0(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=oy(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 gd(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function v0(e,t,n,r,o){let i=t==="get"&&gd(o.item)&&typeof o.item.id=="string"?o.item.id:t==="search"&&typeof o.query=="string"?o.query:void 0,s=i===void 0?"":` '${i.replaceAll("'",`'"'"'`)}'`,a=t==="get"?"":` --limit ${r.budget_derived_limit??1}`;return`pm ${e}${s} --for ${n} --token-budget ${Math.ceil(r.estimated_tokens/100)*100}${a}`}function yr(e,t){if(gd(e))return typeof e[t]=="number"?e[t]:void 0}function T0(e,t){let n=e;for(let r=0;r<8;r+=1){let o=yr(n.context_intent,"estimated_tokens"),i=yr(n.read_output,"estimated_tokens"),s=yr(n.read_session,"spent_this_call_tokens");if(gd(n.context_intent)&&qt(n,n.context_intent),n=Wg(n,t),yr(n.context_intent,"estimated_tokens")===o&&yr(n.read_output,"estimated_tokens")===i&&yr(n.read_session,"spent_this_call_tokens")===s)break}return n}function iy(e,t,n){let r=ng(e,n),o=typeof r=="object"&&r!==null&&!Array.isArray(r)?Yg(e??"",t,E0(t,w0(e??"",t,r))):r;return t.outputRowContract===!0||t.output_row_contract===!0||typeof o!="object"||o===null||Array.isArray(o)||!Object.hasOwn(o,"row_contract")?o:T0(Object.fromEntries(Object.entries(o).filter(([i])=>i!=="row_contract")),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]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();var hr=["result_rows","envelope","diagnostics","hints"],k0=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,A0=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,S0=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,x0=8;function yd(e){return Buffer.byteLength(e,"utf8")}function sy(e){return yd(JSON.stringify(e)??"null")}function C0(e,t){return A0.test(e)?"diagnostics":S0.test(e)?"hints":k0.test(e)||Array.isArray(t)?"result_rows":"envelope"}function O0(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"]=sy(e),t;for(let[n,r]of Object.entries(e))t[C0(n,r)]+=sy({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function I0(e,t){let n=hr.reduce((s,a)=>s+t[a],0),r=hr.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-hr.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))||hr.indexOf(a.section)-hr.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function ay(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function cy(e,t){let n=yd(t(e)),r=I0(n,O0(e)),o=Object.fromEntries(hr.map(a=>[a,{bytes:r[a],estimated_tokens:zt(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:zt(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=ay(e,i);for(let a=0;a<x0;a+=1){let c=yd(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:zt(c)},s=ay(e,i)}return s}import{encode as fy}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]="202cbb3e-71fe-5701-a1f5-eb515bf56561")}catch{}})();var R0=new Set(Object.values(g)),hd="__pm_native_output",ly=!1;function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function N0(e){return be(e)&&e[hd]===!0}function D0(e){if(!be(e)||e[hd]!==!0)return e;let{[hd]:t,...n}=e;return n}function bd(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function P0(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function L0(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function wd(e){if(e==="stdout"){P0();return}L0()}function dy(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function M0(){ly||(ly=!0,process.stdout.on("error",e=>{if(bd(e)){wd("stdout");return}dy(e)}),process.stderr.on("error",e=>{if(bd(e)){wd("stderr");return}dy(e)}))}function py(e,t){M0();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(bd(n))return wd(e),!1;throw n}}function bt(e){return py("stdout",e)}function Io(e){return py("stderr",e)}function Ed(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function F0(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function my(e){if(e.length===0||!e.every(be))return!1;let t=Object.keys(e[0]);return t.length>0&&e.every(n=>Object.keys(n).length===t.length&&t.every(r=>Object.hasOwn(n,r)&&F0(n[r])))}function _y(e,t){let n=" ".repeat(t);return e.split(`
27
+ Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,u=t.trim()||"Inspect the diagnostic code and retry with corrected input.",f=Math.max(1,s*4-Buffer.byteLength(`${l}${d}`,"utf8")),p=c?`${l}${mr(u,f)}${d}`:e;return{output:p,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,estimated_tokens:Bt(Buffer.byteLength(p,"utf8")),truncated:c,degradation_steps:c?[...o.degradation_ladder]:["full"],omitted_fields:c?["explanation","collections"]:[]}}}import{createHash as l0}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]="642f6dec-c0b2-5377-a401-dfa4f8ef6a2a")}catch{}})();var id=256,Ao=1e4,ON=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,IN=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,RN=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),NN=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&ON.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=id,reason:`token_budget must be a safe integer of at least ${id}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=Ao&&e.seen_item_ids.every(t=>typeof t=="string"&&IN.test(t)),reason:`seen_item_ids must contain at most ${Ao} portable item identifiers.`}];function Es(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function ws(e){throw new h(`--output-session ${e}`,g.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function vs(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{ws("must be a valid JSON object.")}Es(t)||ws("must be a JSON object.");let n=Object.keys(t).filter(i=>!RN.has(i));n.length>0&&ws(`contains unknown field "${n.sort()[0]}".`);let r=NN.find(i=>!i.valid(t));r!==void 0&&ws(r.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function Ag(e){if(Es(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Es(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function DN(e){let t=new Set,n=0;for(let r of fr(e)){let o=Array.isArray(r.value)?r.value:Object.values(r.value);for(let i of o){if(!Es(i))continue;if(typeof i.context_ref=="string"){n+=1;continue}let s=Ag(i);s!==void 0&&t.add(s)}}return{deliveredIds:t,suppressedRepeatCount:n}}function Sg(e,t){let n=new Set(t.seen_item_ids);return vo(e,r=>{let o=Ag(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function sd(e,t){let{deliveredIds:n,suppressedRepeatCount:r}=DN(e),o=new Set(t.seen_item_ids),i=[...n].filter(_=>!o.has(_)).sort(),s=i.slice(0,Ao-t.seen_item_ids.length),a=[...t.seen_item_ids,...s].sort(),c=i.length-s.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:n.size,...c===0?{}:{seen_item_overflow_count:c},suppressed_repeat_count:r,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:a}},d={...e,read_session:l},u=_=>{l.spent_this_call_tokens=_,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,_),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<id,l.next_state.spent_tokens=l.spent_total_tokens},f=0,p=0;for(let _=0;_<8;_+=1){u(f);let y=Math.ceil(Buffer.byteLength(JSON.stringify(d),"utf8")/4);if(y===f)return d;p=Math.max(p,y),f=y}return u(p),d}function xg(e){return Math.max(0,e.token_budget-e.spent_tokens)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2103a4dc-3037-5768-b2c7-5964de4ac86b")}catch{}})();var An=["include","amount","cost","encoding"],Mg=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"],Fg=["canonical","legacy","intent","default"],xo={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},ad=Symbol.for("pm.readOutputInvocationProvenance"),$g=Object.freeze(An.map(e=>xo[e])),jg=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Ug={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},zg=new Set(["--collapse","--fields","--section"]),dd=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function ud(e){return e.slice(2).replaceAll("-","_")}function PN(e,t){let n=dd[e];if(n!==void 0)return n;let r=t==="include"?zg.has(e)?"<csv>":ud(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${xo[t]} ${r}.`}function LN(e){let t=Ug[e],n=Object.freeze(Object.fromEntries(An.map(r=>[r,Object.freeze({dimension:r,canonical_option:xo[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:dd[o]===void 0?"replacement":"behavior_preserving",migration_hint:PN(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Fg,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...fd(e).keys()])})}var MN=Object.freeze(Mg.map(LN)),FN=new Map(MN.map(e=>[e.command,e]));function st(e,t={}){let n=e.trim().toLowerCase().replaceAll(/\s+/gu," "),o=n==="package catalog"||n==="packages catalog"||n==="package-catalog"||(n==="package"||n==="packages"||n==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":n==="package manage"||n==="package-manage"?"package-manage":n.split(" ")[0],i=o.startsWith("list-")?"list":o==="ctx"?"context":o;return Mg.includes(i)?i:void 0}var $N=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],jN={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function UN(e){return $N.some(t=>e[t]!==void 0)}var zN=[{keys:["outputInclude","output_include"],valid:e=>So(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||gr(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||gr(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputFormat","output_format"],valid:e=>e==="toon"||e==="json",message:"--output-format must be toon or json."},{keys:["outputSession","output_session"],valid:e=>(vs(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}];function rH(e,t){if(!UN(t))return;let n=st(e,t);if(!n)throw new h(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,g.USAGE);if((jN[n]??[]).some(r=>t[r]!==void 0&&t[r]!==!1))throw new h(`Universal output controls cannot be combined with a ${n} mutation.`,g.USAGE);for(let r of zN){let o=r.keys.map(i=>t[i]).find(i=>i!==void 0);if(o!==void 0&&!r.valid(o))throw new h(r.message,g.USAGE)}}function fd(e){let t=st(e);return t?new Map((Ug[t].include??[]).filter(n=>!zg.has(n)&&dd[n]===void 0).map(n=>[ud(n),qg(n)])):new Map}function qN(e,t,n){let r=So(t)??[],o=fd(e),i=[],s=[],a=n,c=a[ad],l=new Set(c?.canonical_include_modes??[]),d=new Set(c?.explicit_legacy_aliases??[]);for(let p of r){let _=o.get(p);if(_===void 0){i.push(p);continue}let y=`--${p.replaceAll("_","-")}`;Gg(Vg(n,y))&&d.add(y),n[_]=!0,s.push(p),l.add(p)}let u=st(e)==="get"?i.filter(p=>p!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...So(n.fields)??[],...u])].join(","),l.add("fields")),(s.length>0||f)&&(a[ad]={canonical_include_modes:[...l],explicit_legacy_aliases:[...d],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function oH(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=qN(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function qg(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function Vg(e,t){let n=qg(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 Gg(e){return e!==void 0&&e!==!1&&e!==null}function So(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 gr(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 VN(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=Vg(t,o.flag),s={value:i,flag:o.flag};if(Gg(i)&&n(s))return s}}function Cg(e,t){let n=So(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:So(t.value)??[ud(t.flag)]}}function Og(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=gr(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=gr(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Ig(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=gr(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=gr(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Rg(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 GN(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function BN(e,t,n){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function HN(e,t){return An.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[xo[n]]:[])}function Bg(e,t){let n=st(e,t);if(!n)return;let r=FN.get(n),o=t[ad],i={include:T=>Cg(void 0,T),amount:T=>Og(void 0,T),cost:T=>Ig(void 0,T),encoding:T=>Rg(void 0,T)},s=Object.fromEntries(An.map(T=>[T,VN(r.dimensions[T],t,O=>i[T](O)!==void 0,O=>GN(o,T,O))])),a=An.flatMap(T=>{let O=s[T];return O?[O.flag]:[]}),c=An.flatMap(T=>{let O=s[T];return O?[r.dimensions[T].legacy_aliases.find(F=>F.flag===O.flag).migration_hint]:[]}),l=Rg(t.outputFormat??t.output_format,s.encoding),d=Cg(t.outputInclude??t.output_include,s.include),u=Og(t.outputLimit??t.output_limit,s.amount),f=Ig(t.outputBudget??t.output_budget,s.cost),p=BN(e,s,o),_=nd(e,{generateFallback:!0}),y=l?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",b=f??(p?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:n,include:d,amount:u,cost:b,encoding:l,canonical_options_used:HN({include:d,amount:u,cost:b,encoding:l},o),legacy_aliases_used:a,migration_hints:c,precedence:Fg}}function Qe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var pd=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),WN=["collection_counts","notes_count","tests_count"];function Hg(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function KN(e){let t=Qe(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...WN.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!pd.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function YN(e,t){let n=KN(e),r=t.filter(u=>!n.valid.includes(u));if(r.length>0)throw new h(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,g.USAGE);let o=t.includes("item"),i=t.flatMap(u=>u.startsWith("item.")?[u.slice(5)]:n.itemFields.includes(u)?[u]:[]).filter((u,f,p)=>p.indexOf(u)===f);if(o&&i.length>0)throw new h("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",g.USAGE);let s=new Set(t.filter(u=>n.sections.includes(u))),a=Object.fromEntries(Object.entries(e).filter(([u])=>pd.has(u)||s.has(u)));o?a.item=n.item:i.length>0&&(a.item=Hg(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(u=>!i.includes(u)).map(u=>({name:`item.${u}`,restore_with:`--output-include item.${u}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(u=>!s.has(u)).map(u=>({name:u,restore_with:`--output-include ${u}`}))],d=[...Qe(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function Ng(e){let t=0;return vo({...e},n=>(Qe(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function XN(e,t,n,r){if(Ng(t)===0||Ng(n)>0)return;let o=[...fd(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new h(`Unknown --output-include selector(s) for ${e}: ${r.join(", ")}. No selector matched any returned row field.${i}`,g.USAGE)}function JN(e,t,n){if(e==="get")return YN(t,n);let r=ys(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=vo(s,l=>Qe(l)?Hg(l,a):l);return XN(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||pd.has(s)))}function QN(e,t){if(t==="unbounded")return e;let{result:n,truncated:r}=ag(e,t);return r&&(n.has_more=!0,n.truncated=!0,typeof n.count=="number"&&(n.count=bs(n)),n.applied_bound={kind:"output_limit",source:"explicit",value:t}),n}function ZN(e){return An.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(xo[t]))}function ks(e,t,n){let r=sd(e,t);for(let o=0;o<8;o+=1){let i=n.estimated_tokens,s=r.read_session.spent_this_call_tokens;kn(r,n),r=sd(r,t);let a=r.read_session.spent_this_call_tokens;if(n.estimated_tokens===i&&a===s)return r}return r}function Wg(e,t){if(!Qe(e.read_output))return e;let n=e.read_output,r=vs(t.outputSession??t.output_session);return r===void 0?(kn(e,n),e):ks(e,r,n)}function e0(e,t){if(e!=="validate")return t;let n=Qe(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(u=>Qe(u)&&u.name==="diagnostic_rows"))return t;let o=[...new Set(hs(t).map(({path:u})=>u).filter(u=>/^checks\.\d+\.details\./u.test(u)))],i=o.filter(u=>!o.some(f=>f!==u&&u.startsWith(`${f}.`)));if(i.length===0)return t;let s=Qe(t.row_contract)?t.row_contract:{},a=Array.isArray(s.row_keys)?s.row_keys.filter(u=>typeof u=="string"):[],c=Array.isArray(s.continuation_row_keys)?s.continuation_row_keys.filter(u=>typeof u=="string"):[],l=a.length>0?a:i,d=[...new Set(i)];return JSON.stringify(l)===JSON.stringify(a)&&JSON.stringify(d)===JSON.stringify(c)?t:{...t,row_contract:{...s,row_keys:l,continuation_row_keys:d,jq_selector:typeof s.jq_selector=="string"?s.jq_selector:".checks[].details"}}}function t0(e,t,n,r){let o={...e};return t.include?.source==="canonical"&&(o=JN(t.command,o,t.include.value)),t.command==="assurance"&&(o=Pg(o)),o=Lg(o,t.command,r),t.amount?.source==="canonical"&&(o=QN(o,t.amount.value)),n===void 0?o:Sg(o,n)}function n0(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:xg(t)}]].sort((r,o)=>r.tokens-o.tokens)[0]}function Kg(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function r0(e,t,n,r,o){let i={contract_version:1,command:e.command,requested_dimensions:t,...r.source==="default"?{budget_source:r.source,budget_tokens:r.tokens}:{},precedence:e.precedence,...Kg(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:o}:{}},s={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:i},a=n===void 0?s:ks(s,n,i);if(n===void 0&&kn(a,i),n!==void 0&&i.estimated_tokens>r.tokens)throw new h("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",g.USAGE);return a}function o0(e,t,n){if(t!==void 0)return!1;let r=e.canonical_options_used.length;return e.cost?.value==="unbounded"?r===(e.cost.source==="canonical"?1:0):e.cost?.source==="legacy"&&r===0?!0:r===0&&(e.cost===void 0||Jl(n)<=e.cost.value)}function i0(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(pr(e).map(f=>[f.path,Array.isArray(f.value)?f.value.length:Object.keys(f.value).length])),l=[...s.entries()].flatMap(([f,p])=>{let _=c.get(f);if(_>=p.rows)return[];let y=p.baseOffset+_;return[{path:f,cursor:cd({command:t.command,path:f,offset:y,total_rows:p.totalRows,fingerprint:p.fingerprint}),retained_rows:_,remaining_rows:p.totalRows-y,total_rows:p.totalRows}]}),d=l[0],u=Xl({effective_budget_tokens:r.tokens,measured_result_tokens:i});d&&typeof e.next_cursor!="string"&&(e.next_cursor=d.cursor),e.continuation_kind=o?"producer_cursor":d?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:l.length>0,recovery_budget_multiplier:d?1:u.recovery_budget_multiplier,continuations:l,restore_with:d?"Use recovery binding.":`Retry with --output-budget ${u.output_budget} because no declared row collection can be continued.`,recovery:d?{cursor:d.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${u.output_budget}`,sdk:{outputBudget:u.output_budget},mcp:{outputBudget:u.output_budget}}}}function s0(e,t,n,r){if(typeof n!="string"||!Array.isArray(e.items))return!1;let o=e.items.length;if(o===0||o>=t)return!1;let i;try{i=Hl(n)}catch{return!1}let s=i.after_index;if(s===void 0)return!1;let a=e.items.at(-1);if(Object.prototype.toString.call(a)!=="[object Object]")return!1;let c=Reflect.get(a,"id");if(typeof c!="string"||c.length===0)return!1;let l=r?s-(t-o):s+o;return l<0?!1:(e.next_cursor=Eo(i.fingerprint,c,l,i.snapshot),typeof e.applied_limit=="number"&&(e.applied_limit=o),!0)}function a0(e,t,n,r){let o=new Map(pr(e).map(s=>{let a=Array.isArray(s.value)?s.value.length:Object.keys(s.value).length,c=n?.path===s.path;return[s.path,{rows:a,totalRows:c?n.total_rows:a,baseOffset:c?n.offset:0,fingerprint:c?n.fingerprint:Ts(s.path,s.value,t)}]})),i=typeof e.next_cursor=="string";return{collectionsBeforeBudget:o,originalItemCount:Array.isArray(e.items)?e.items.length:0,cursorContinuesExistingPage:i,cursorSource:i?e.next_cursor:r.after}}function c0(e,t,n,r,o,i,s){let a=t.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(d=>Qe(d)&&d.verdict!=="pass").length:0,c=lg(e,n,r.tokens,a>0?new Map([["assertions",a]]):new Map),l=s0(c,i.originalItemCount,i.cursorSource,i.cursorContinuesExistingPage);return i0(c,t,n,r,l,s,i.collectionsBeforeBudget),o!==void 0&&(c=ks(c,o,n)),c}function Yg(e,t,n){let r=Bg(e,t);if(!r)return n;let o=vs(t.outputSession??t.output_session),i=t.outputCursor??t.output_cursor,s=typeof i=="string"?ld(i):void 0,a=ZN(r);if(s===void 0&&o0(r,o,n))return n;let c=e0(r.command,n),l=n0(r,o),d=t0(c,r,o,s),u=a0(d,r.command,s,t),f={contract_version:1,command:r.command,requested_dimensions:a,...l?.source==="default"?{budget_source:l.source,budget_tokens:l.tokens}:{},precedence:r.precedence,...Kg(r),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};if(d.read_output=f,d=o===void 0?d:ks(d,o,f),kn(d,f),l!==void 0&&f.estimated_tokens>l.tokens){let p=f.estimated_tokens;d=c0(d,r,f,l,o,u,p)}return l!==void 0&&f.estimated_tokens>l.tokens?r0(r,a,o,l,f.estimated_tokens):d}function Xg(e){return Qe(e)&&Qe(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function Jg(e,t){let n=Bg(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var d0=4096,u0=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),Dg=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:u0}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Oo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Co(e){return Array.isArray(e)?e.map(Co):Oo(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Co(n)])):e}function Qg(e,t){if(!Oo(e))return Co(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Oo(i)?[o,Co(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Co(a)]))]))}function f0(e,t){return Array.isArray(e)?e.map(n=>Qg(n,t)):Qg(e,t)}function Ts(e,t,n){let r=n?Dg[n]:void 0,o=r?.paths.includes(e)===!0;return l0("sha256").update(B({path:e,value:o?f0(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function cd(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint}),"utf8").toString("base64url")}function ld(e){if(e.length>d0)throw new h("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!Oo(t)||t.v!==1||st(String(t.c??""))!==t.c||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0)throw new h("The read-output continuation cursor is malformed or unsupported.",g.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f}}function Pg(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Oo(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function Lg(e,t,n){if(!n)return e;if(n.command!==t)throw new h(`The read-output cursor belongs to ${n.command}, not ${t}.`,g.USAGE,{code:"read_output_cursor_command_mismatch"});let r=pr(e).find(i=>i.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0;if(!r||o!==n.total_rows||n.offset>o||Ts(n.path,r.value,t)!==n.fingerprint)throw new h("The read-output continuation no longer matches the declared row collection; restart the bounded read.",g.USAGE,{code:"read_output_cursor_stale"});return sg(e,n.path,n.offset)}import{AsyncLocalStorage as p0}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]="da15ca02-02cc-5886-8c82-610939b8581c")}catch{}})();var ey=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),ty=new p0;function m0(){return ty.getStore()??ey}function vH(e,t){return ty.run(g0(e.workspaceContracts,e.packageContracts),t)}function _0(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 g0(e=[],t=[]){let n=[{source:"core",contracts:ey,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=_0(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 ny(e,t,n=m0(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let p=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=p[0];p[0]=_;for(let b=1;b<=i.length;b+=1){let E=p[b];p[b]=Math.min(p[b]+1,p[b-1]+1,y+(f[_-1]===i[b-1]?0:1)),y=E}}return{candidate:f,distance:p[i.length]}}).sort((f,p)=>f.distance-p.distance||f.candidate.localeCompare(p.candidate))[0].candidate,l=[o,...r,"--for",i],d=[o,...r,"--for",c],u=Gl(d);throw new h(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,g.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:Gl(l),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:d}})}var ry={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=Ss(e.tokenBudget,t.token_budget),o=xs("context",t.intent,r,n),i=Sn(e.limit),s=String(i===void 0?o:Math.min(i,o));(e.limit===void 0||i!==void 0)&&(e.limit=s),e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let r=Ss(e.tokenBudget,t.token_budget),o=xs("list",t.intent,r,n),i=Sn(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let r=Ss(e.tokenBudget,t.token_budget),o=xs("search",t.intent,r,n),i=Sn(e.limit);(e.limit===void 0||i!==void 0)&&(e.limit=String(i===void 0?o:Math.min(i,o)))}};function TH(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==void 0&&(e==="get"||e==="list"||e==="search"))throw new h("--token-budget requires a declared context intent selected with --for",g.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let a={...t,tokenBudget:r};return delete a.token_budget,a}let o=ny(e,t.for,void 0,n),i=Sn(r)!==void 0,s={...t};return s.tokenBudget===void 0&&r!==void 0&&(s.tokenBudget=r),delete s.token_budget,s.tokenBudget===void 0&&(s.tokenBudget=String(o.token_budget)),ry[e](s,o,i),s}var y0={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},As=256;function md(e){return Array.isArray(e)?e.map(md):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,md(n)])):typeof e=="string"&&e.length>240?`${e.slice(0,240)}\u2026`:e}function Sn(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 Ss(e,t){let n=Sn(e);if(n===void 0)return t;if(n<As)throw new h(`Context intent token budget must be at least ${As}`,g.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",required:`Use an integer token budget of at least ${As}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${As} or omit the override.`]});return n}function xs(e,t,n,r){if(e==="get"||e==="next")return;let o=e==="context"&&t==="orient",i=e==="context"?o?1200:800:e==="list"?520:480,s=e==="context"?o?600:500:16,a=Math.max(e==="context"?1:2,Math.floor((n-i)/s));return r?a:Math.min(e==="context"?20:100,a)}function Ht(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 Zg={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 oy(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 h0(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 b0(e,t,n){let r=!1;for(;;){if(Ht(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 w0(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=oy(i);if(s===void 0)return!1;let a=r.length,c=[...r],l=!1;for(;;){if(l=b0(e,t,r)||l,!l)return!1;let d=h0(r.at(-1));if(d===void 0)return r.splice(0,r.length,...c),Ht(e,t),!1;if(e.next_cursor=Eo(s.fingerprint,d,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),Ht(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 E0(e,t,n,r){if(e==="list"||e==="search")return w0(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Ht(t,n),n.estimated_tokens<=n.token_budget)return o;let i=Zg[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,p)=>p.rows.length-f.rows.length||f.key.localeCompare(p.key))[0];if(i===void 0)return o;let s=Zg[e].reduce((f,p)=>f+(Array.isArray(t[p])?t[p].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"),l=Math.max(1,Math.ceil(c/i.rows.length)),d=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(d/l)));i.rows.splice(-u,u),o=!0}}function v0(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in ry))return n;let o=r,i=ny(o,t.for),s=Ss(t.tokenBudget??t.token_budget,i.token_budget),a={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:s,declared_token_budget:i.token_budget,token_budget_override:s-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:y0[o],declaration_feasible:!0,result_omitted:!1},c={...n},l=xs(o,i.intent,a.token_budget,Sn(t.tokenBudget??t.token_budget)!==void 0);if(l!==void 0){let u=Sn(t.limit),f=u!==void 0&&u<l;a.budget_derived_limit=l,a.binding_constraint=f?"explicit_limit":"token_budget",a.limit_reason=f?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",c.budget_derived_limit=l}let d={...c,context_intent:a};return Ht(d,a),a.estimated_tokens>a.token_budget&&(a.degradation="recursive_budget_compaction",d={...md(c),context_intent:a},Ht(d,a)),a.estimated_tokens>a.token_budget&&E0(o,d,a,t)&&(a.degradation="budget_row_compaction",Ht(d,a)),a.declaration_feasible=a.estimated_tokens<=a.declared_token_budget,a.estimated_tokens>a.token_budget&&(a.degradation="budget_receipt_only",a.result_omitted=!0,a.within_budget=!1,d={budget_exceeded:{omitted_result:!0,reason:a.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:k0(e,o,i.intent,a,c)},context_intent:a}),d}function T0(e,t){if(typeof e.after!="string"||e.after.length===0)return t;let n=oy(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 _d(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function k0(e,t,n,r,o){let i=t==="get"&&_d(o.item)&&typeof o.item.id=="string"?o.item.id:t==="search"&&typeof o.query=="string"?o.query:void 0,s=i===void 0?"":` '${i.replaceAll("'",`'"'"'`)}'`,a=t==="get"?"":` --limit ${r.budget_derived_limit??1}`;return`pm ${e}${s} --for ${n} --token-budget ${Math.ceil(r.estimated_tokens/100)*100}${a}`}function yr(e,t){if(_d(e))return typeof e[t]=="number"?e[t]:void 0}function A0(e,t){let n=e;for(let r=0;r<8;r+=1){let o=yr(n.context_intent,"estimated_tokens"),i=yr(n.read_output,"estimated_tokens"),s=yr(n.read_session,"spent_this_call_tokens");if(_d(n.context_intent)&&Ht(n,n.context_intent),n=Wg(n,t),yr(n.context_intent,"estimated_tokens")===o&&yr(n.read_output,"estimated_tokens")===i&&yr(n.read_session,"spent_this_call_tokens")===s)break}return n}function iy(e,t,n){let r=ng(e,n),o=typeof r=="object"&&r!==null&&!Array.isArray(r)?Yg(e??"",t,T0(t,v0(e??"",t,r))):r;return t.outputRowContract===!0||t.output_row_contract===!0||typeof o!="object"||o===null||Array.isArray(o)||!Object.hasOwn(o,"row_contract")?o:A0(Object.fromEntries(Object.entries(o).filter(([i])=>i!=="row_contract")),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]="02baf966-46eb-5e19-b7eb-2f9fe05bb263")}catch{}})();var hr=["result_rows","envelope","diagnostics","hints"],S0=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,x0=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,C0=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,O0=8;function gd(e){return Buffer.byteLength(e,"utf8")}function sy(e){return gd(JSON.stringify(e)??"null")}function I0(e,t){return x0.test(e)?"diagnostics":C0.test(e)?"hints":S0.test(e)||Array.isArray(t)?"result_rows":"envelope"}function R0(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"]=sy(e),t;for(let[n,r]of Object.entries(e))t[I0(n,r)]+=sy({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function N0(e,t){let n=hr.reduce((s,a)=>s+t[a],0),r=hr.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-hr.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))||hr.indexOf(a.section)-hr.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function ay(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function cy(e,t){let n=gd(t(e)),r=N0(n,R0(e)),o=Object.fromEntries(hr.map(a=>[a,{bytes:r[a],estimated_tokens:Bt(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:Bt(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=ay(e,i);for(let a=0;a<O0;a+=1){let c=gd(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:Bt(c)},s=ay(e,i)}return s}import{encode as fy}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]="202cbb3e-71fe-5701-a1f5-eb515bf56561")}catch{}})();var D0=new Set(Object.values(g)),yd="__pm_native_output",ly=!1;function be(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function P0(e){return be(e)&&e[yd]===!0}function L0(e){if(!be(e)||e[yd]!==!0)return e;let{[yd]:t,...n}=e;return n}function hd(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function M0(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function F0(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function bd(e){if(e==="stdout"){M0();return}F0()}function dy(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function $0(){ly||(ly=!0,process.stdout.on("error",e=>{if(hd(e)){bd("stdout");return}dy(e)}),process.stderr.on("error",e=>{if(hd(e)){bd("stderr");return}dy(e)}))}function py(e,t){$0();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(hd(n))return bd(e),!1;throw n}}function vt(e){return py("stdout",e)}function Io(e){return py("stderr",e)}function wd(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function j0(e){return e===null||typeof e=="string"||typeof e=="number"||typeof e=="boolean"}function my(e){if(e.length===0||!e.every(be))return!1;let t=Object.keys(e[0]);return t.length>0&&e.every(n=>Object.keys(n).length===t.length&&t.every(r=>Object.hasOwn(n,r)&&j0(n[r])))}function _y(e,t){let n=" ".repeat(t);return e.split(`
28
28
  `).map(r=>`${n}${r}`).join(`
29
- `)}function $0(e,t,n){let r=" ".repeat(n);return!be(t)&&!Array.isArray(t)?`${r}${e}: ${Ed(t)}`:Array.isArray(t)&&t.length===0?`${r}${e}: []`:Array.isArray(t)&&my(t)?_y(fy({[e]:t}),n):be(t)&&Object.keys(t).length===0?`${r}${e}: {}`:`${r}${e}:
30
- ${vd(t,n+1)}`}function Cs(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>Cs(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(be(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=Cs(r);o!==void 0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}return e}}function vd(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":my(e)?_y(fy(e),t):e.map(r=>{if(!be(r)&&!Array.isArray(r))return`${n}- ${Ed(r)}`;let i=vd(r,t+1).split(`
29
+ `)}function U0(e,t,n){let r=" ".repeat(n);return!be(t)&&!Array.isArray(t)?`${r}${e}: ${wd(t)}`:Array.isArray(t)&&t.length===0?`${r}${e}: []`:Array.isArray(t)&&my(t)?_y(fy({[e]:t}),n):be(t)&&Object.keys(t).length===0?`${r}${e}: {}`:`${r}${e}:
30
+ ${Ed(t,n+1)}`}function Cs(e){if(e!=null){if(Array.isArray(e)){let t=e.map(n=>Cs(n)).filter(n=>n!==void 0);return t.length>0?t:void 0}if(be(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=Cs(r);o!==void 0&&(t[n]=o)}return Object.keys(t).length>0?t:void 0}return e}}function Ed(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":my(e)?_y(fy(e),t):e.map(r=>{if(!be(r)&&!Array.isArray(r))return`${n}- ${wd(r)}`;let i=Ed(r,t+1).split(`
31
31
  `),[s,...a]=i;return a.length===0?`${n}- ${s.trimStart()}`:`${n}- ${s.trimStart()}
32
32
  ${a.join(`
33
33
  `)}`}).join(`
34
- `);if(be(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>$0(o,i,t)).join(`
35
- `)}return`${n}${Ed(e)}`}function j0(e){if(!be(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=be(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(`
34
+ `);if(be(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>U0(o,i,t)).join(`
35
+ `)}return`${n}${wd(e)}`}function z0(e){if(!be(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=be(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(`
36
36
  `)}
37
37
  `;for(let r of e.events){if(!be(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(`
38
38
  `)}
39
- `}function U0(e){return e.json===!0||e.json===void 0&&e.defaultOutputFormat==="json"?"json":"toon"}var z0=new Set(["filters","now","projection","sorting"]);function q0(e){let t=Cs(e);if(!be(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!z0.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function V0(e,t){if(!be(e)||!Array.isArray(e.run_results)||!e.run_results.every(be))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:l,...d}=s;return o===void 0?s:!t||s.status!=="passed"?{...d,stdout:c,stderr:l}:d});return{...e,...o===void 0?{}:{execution_context:o},run_results:i}}function uy(e,t){if(t==="json")return`${JSON.stringify(e,null,2)}
39
+ `}function q0(e){return e.json===!0||e.json===void 0&&e.defaultOutputFormat==="json"?"json":"toon"}var V0=new Set(["filters","now","projection","sorting"]);function G0(e){let t=Cs(e);if(!be(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!V0.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function B0(e,t){if(!be(e)||!Array.isArray(e.run_results)||!e.run_results.every(be))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:l,...d}=s;return o===void 0?s:!t||s.status!=="passed"?{...d,stdout:c,stderr:l}:d});return{...e,...o===void 0?{}:{execution_context:o},run_results:i}}function uy(e,t){if(t==="json")return`${JSON.stringify(e,null,2)}
40
40
  `;let n=Cs(e);return n===void 0?`{}
41
- `:`${vd(n,0)}
42
- `}function G0(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:tl("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&&Io(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
41
+ `:`${Ed(n,0)}
42
+ `}function H0(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:el("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&&Io(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
43
43
  `),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
44
44
  `)?o.result:`${o.result}
45
- `}:{result:o.handled?o.result:e,rendered:null}}function B0(e,t,n){let r=Bm(),o=n.command??r?.command,i={...r?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(y=>y[1]!==void 0))},s=Jg(o??"",i)??U0(n),a={...i,resolvedOutputFormat:s},c={...n,command:o,commandOptions:a},l=G0(e,t,c,s);if(l.rendered!==null)return l.rendered;let d=l.result,u=o==="test"?V0(d,n.lean===!0):d,f=iy(o,a,u);Xg(f)&&(process.exitCode||=g.USAGE);let p=y=>{if(s==="toon"){let E=j0(y);if(E!==null)return E}let b=t?{rendered:null}:Wm(s,y);return b.rendered!==null?b.rendered.endsWith(`
45
+ `}:{result:o.handled?o.result:e,rendered:null}}function W0(e,t,n){let r=Bm(),o=n.command??r?.command,i={...r?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(y=>y[1]!==void 0))},s=Jg(o??"",i)??q0(n),a={...i,resolvedOutputFormat:s},c={...n,command:o,commandOptions:a},l=H0(e,t,c,s);if(l.rendered!==null)return l.rendered;let d=l.result,u=o==="test"?B0(d,n.lean===!0):d,f=iy(o,a,u);Xg(f)&&(process.exitCode||=g.USAGE);let p=y=>{if(s==="toon"){let E=z0(y);if(E!==null)return E}let b=t?{rendered:null}:Wm(s,y);return b.rendered!==null?b.rendered.endsWith(`
46
46
  `)?b.rendered:`${b.rendered}
47
- `:s==="json"?uy(n.lean===!0?q0(y):y,"json"):uy(y,"toon")},_=n.tokenAccounting===!0?cy(f,p):f;return p(_)}function H0(e,t){let n=Hm(e),r=hi(n.result)?n.result:null,o=N0(n.result),i=r?r.result:D0(n.result);return rr(i),r?"":B0(i,o,t)}function gy(e,t){be(e)&&Number.isInteger(e.exit_code)&&R0.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?gs(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?gs(e,{changedFields:"compact"}):gs(e,{compactEnvelope:!0}),r=H0(n,t);t.quiet||bt(r)}function Td(e){let t=tl("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Io(n.endsWith(`
47
+ `:s==="json"?uy(n.lean===!0?G0(y):y,"json"):uy(y,"toon")},_=n.tokenAccounting===!0?cy(f,p):f;return p(_)}function K0(e,t){let n=Hm(e),r=hi(n.result)?n.result:null,o=P0(n.result),i=r?r.result:L0(n.result);return rr(i),r?"":W0(i,o,t)}function gy(e,t){be(e)&&Number.isInteger(e.exit_code)&&D0.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?gs(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?gs(e,{changedFields:"compact"}):gs(e,{compactEnvelope:!0}),r=K0(n,t);t.quiet||vt(r)}function vd(e){let t=el("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Io(n.endsWith(`
48
48
  `)?n:`${n}
49
- `)}import xy from"fast-json-patch";import wt from"node:fs/promises";import Et from"node:path";import{randomUUID as W0}from"node:crypto";import{createRequire as K0}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]="a84b308f-7eef-535c-9531-b33b0775c651")}catch{}})();var Y0="history-event-index.sqlite",kd="2",X0=8,Sn=new Map;function Ns(e){return Et.join(e,"runtime",Y0)}async function yy(e){let t=Et.join(e,"history"),n=await wt.readdir(t,{withFileTypes:!0}).catch(s=>{if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return[];throw s}),r=Sn.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!Sn.has(e);for(let s of n.filter(a=>a.isFile()&&a.name.endsWith(".jsonl")).sort((a,c)=>a.name.localeCompare(c.name))){let a=s.name.slice(0,-6);o.add(a);let c=Et.join(t,s.name),l=await wt.stat(c,{bigint:!0}),d=[l.dev,l.ino,l.size,l.mtimeNs,l.ctimeNs].join(":");if(r.streams.get(a)?.signature===d)continue;let u=await Ke(c,a);r.streams.set(a,{signature:d,events:u.map((f,p)=>({stream_id:a,stream_offset:p,entry:f}))}),i=!0}for(let s of r.streams.keys())o.has(s)||(r.streams.delete(s),i=!0);if(i&&(r.ordered_events=[...r.streams.values()].flatMap(s=>s.events).sort(by)),Sn.delete(e),Sn.set(e,r),Sn.size>X0){let s=Sn.keys().next().value;Sn.delete(s)}return r.ordered_events}function J0(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function Q0(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?J0(t):null}var Os;function Ad(){return Os!==void 0||(Os=Q0(process.versions.node,K0(import.meta.url))),Os}function Z0(e){e.exec(`
49
+ `)}import xy from"fast-json-patch";import Tt from"node:fs/promises";import kt from"node:path";import{randomUUID as Y0}from"node:crypto";import{createRequire as X0}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]="a84b308f-7eef-535c-9531-b33b0775c651")}catch{}})();var J0="history-event-index.sqlite",Td="2",Q0=8,xn=new Map;function Ns(e){return kt.join(e,"runtime",J0)}async function yy(e){let t=kt.join(e,"history"),n=await Tt.readdir(t,{withFileTypes:!0}).catch(s=>{if(typeof s=="object"&&s!==null&&"code"in s&&s.code==="ENOENT")return[];throw s}),r=xn.get(e)??{streams:new Map,ordered_events:[]},o=new Set,i=!xn.has(e);for(let s of n.filter(a=>a.isFile()&&a.name.endsWith(".jsonl")).sort((a,c)=>a.name.localeCompare(c.name))){let a=s.name.slice(0,-6);o.add(a);let c=kt.join(t,s.name),l=await Tt.stat(c,{bigint:!0}),d=[l.dev,l.ino,l.size,l.mtimeNs,l.ctimeNs].join(":");if(r.streams.get(a)?.signature===d)continue;let u=await Xe(c,a);r.streams.set(a,{signature:d,events:u.map((f,p)=>({stream_id:a,stream_offset:p,entry:f}))}),i=!0}for(let s of r.streams.keys())o.has(s)||(r.streams.delete(s),i=!0);if(i&&(r.ordered_events=[...r.streams.values()].flatMap(s=>s.events).sort(by)),xn.delete(e),xn.set(e,r),xn.size>Q0){let s=xn.keys().next().value;xn.delete(s)}return r.ordered_events}function Z0(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function eD(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?Z0(t):null}var Os;function kd(){return Os!==void 0||(Os=eD(process.versions.node,X0(import.meta.url))),Os}function tD(e){e.exec(`
50
50
  PRAGMA journal_mode = OFF;
51
51
  PRAGMA synchronous = OFF;
52
52
  CREATE TABLE metadata (
@@ -74,26 +74,26 @@ ${a.join(`
74
74
  ON events(agent_harness, ts, stream_id, stream_offset);
75
75
  CREATE INDEX events_instance_order
76
76
  ON events(agent_instance, ts, stream_id, stream_offset);
77
- `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(kd)}function hy(e,t){e.prepare(`INSERT INTO events(
77
+ `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(Td)}function hy(e,t){e.prepare(`INSERT INTO events(
78
78
  stream_id, stream_offset, ts, author, agent_harness,
79
79
  agent_instance, op, entry_json
80
- ) 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 jH(e){let t=Ad();if(!t)return!1;let n=Ns(e);await wt.mkdir(Et.dirname(n),{recursive:!0});let r=`${n}.${W0()}.tmp`,o;try{o=new t(r),Z0(o),o.exec("BEGIN IMMEDIATE");for(let i of await yy(e))hy(o,i);return o.exec("COMMIT"),o.close(),o=void 0,await wt.rm(n,{force:!0}),await wt.rename(r,n),!0}catch(i){throw o?.close(),await wt.rm(r,{force:!0}),i}}function Is(e,t){return!t||t.length===0||t.includes(e)}function by(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function eD(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(by(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:t.after_ts}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<t.since_ts)return!1;return!0}function tD(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function nD(e,t){return!eD(e,t)||!Is(e.entry.op,t.ops)||!Is(e.entry.author,t.authors)||!Is(e.entry.agent_instance??"",t.agent_instances)||!Is(e.stream_id,t.stream_ids)||!tD(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function UH(e,t){let n=Math.max(0,Math.floor(t.limit)),r=(await yy(e)).filter(o=>nD(o,t)).slice(0,n+1);return{events:r.slice(0,t.limit),has_more:r.length>t.limit}}async function wy(e,t){let n=Et.dirname(Et.dirname(e)),r=Ns(n);try{await wt.access(r)}catch{return}let o=Ad();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==kd)throw new TypeError("Unsupported history event index version");let a=Et.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);hy(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await wt.rm(r,{force:!0})}}async function Ds(e){await wt.rm(Ns(Et.dirname(Et.dirname(e))),{force:!0})}function Rs(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function rD(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 zH(e,t){let n=Ad();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)),Rs(r,o,"op",t.ops),Rs(r,o,"author",t.authors),rD(r,o,t.harnesses,t.harness_alias_authors),Rs(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);Rs(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s;try{if(s=new n(Ns(e),{readOnly:!0}),s.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==kd)return s.close(),null;let c=s.prepare(`SELECT stream_id, stream_offset, entry_json
80
+ ) 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 zH(e){let t=kd();if(!t)return!1;let n=Ns(e);await Tt.mkdir(kt.dirname(n),{recursive:!0});let r=`${n}.${Y0()}.tmp`,o;try{o=new t(r),tD(o),o.exec("BEGIN IMMEDIATE");for(let i of await yy(e))hy(o,i);return o.exec("COMMIT"),o.close(),o=void 0,await Tt.rm(n,{force:!0}),await Tt.rename(r,n),!0}catch(i){throw o?.close(),await Tt.rm(r,{force:!0}),i}}function Is(e,t){return!t||t.length===0||t.includes(e)}function by(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function nD(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(by(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:t.after_ts}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<t.since_ts)return!1;return!0}function rD(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function oD(e,t){return!nD(e,t)||!Is(e.entry.op,t.ops)||!Is(e.entry.author,t.authors)||!Is(e.entry.agent_instance??"",t.agent_instances)||!Is(e.stream_id,t.stream_ids)||!rD(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function qH(e,t){let n=Math.max(0,Math.floor(t.limit)),r=(await yy(e)).filter(o=>oD(o,t)).slice(0,n+1);return{events:r.slice(0,t.limit),has_more:r.length>t.limit}}async function wy(e,t){let n=kt.dirname(kt.dirname(e)),r=Ns(n);try{await Tt.access(r)}catch{return}let o=kd();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Td)throw new TypeError("Unsupported history event index version");let a=kt.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);hy(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await Tt.rm(r,{force:!0})}}async function Ds(e){await Tt.rm(Ns(kt.dirname(kt.dirname(e))),{force:!0})}function Rs(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function iD(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 VH(e,t){let n=kd();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)),Rs(r,o,"op",t.ops),Rs(r,o,"author",t.authors),iD(r,o,t.harnesses,t.harness_alias_authors),Rs(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);Rs(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s;try{if(s=new n(Ns(e),{readOnly:!0}),s.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Td)return s.close(),null;let c=s.prepare(`SELECT stream_id, stream_offset, entry_json
81
81
  FROM events${i}
82
82
  ORDER BY ts, stream_id, stream_offset
83
- LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),l=c.length>t.limit,d=c.slice(0,t.limit).map(u=>({stream_id:String(u.stream_id),stream_offset:Number(u.stream_offset),entry:JSON.parse(String(u.entry_json))}));return s.close(),{events:d,has_more:l}}catch{return s?.close(),null}}import Sd from"node:fs/promises";import br 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]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var oD=br.join("runtime","history-drift-cache.json"),Ey={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 vy(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function iD(e){let t=br.join(e,oD),n=!1,r="invalid_cache_path";try{n=(await Sd.stat(await Sd.realpath(e))).isDirectory()}catch(o){let i=vy(o);r=i===void 0?"unknown":Ey[i]??"filesystem_error"}if(!n){Io(`[pm] warning: history_drift_cache_invalidation_failed:${r}
84
- `);return}try{await Sd.rm(t,{force:!0})}catch(o){let i=vy(o);if(de(o))return;let s=i===void 0?"unknown":Ey[i]??"filesystem_error";Io(`[pm] warning: history_drift_cache_invalidation_failed:${s}
85
- `)}}async function Ro(e){let t=br.dirname(br.resolve(e));br.basename(t)==="history"&&await iD(br.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]="8581413f-e74e-5db3-86bf-5e39290de741")}catch{}})();var sD={front_matter:{},body:""},Gt=3,wr=[1,2,3];function Ps(e,t){return(e??"").localeCompare(t??"")}function Ty(e,t){return(e??0)-(t??0)}function Vt(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function aD(e,t){return[e.scope.localeCompare(t.scope),Ps(e.path,t.path),Ps(e.command,t.command),Ty(e.timeout_seconds,t.timeout_seconds),Ps(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,Vt(e.env_clear,t.env_clear,[]),Vt(e.env_set,t.env_set,{}),Vt(e.assert_stdout_contains,t.assert_stdout_contains,[]),Vt(e.assert_stdout_regex,t.assert_stdout_regex,[]),Vt(e.assert_stderr_contains,t.assert_stderr_contains,[]),Vt(e.assert_stderr_regex,t.assert_stderr_regex,[]),Ty(e.assert_stdout_min_lines,t.assert_stdout_min_lines),Vt(e.assert_json_field_equals,t.assert_json_field_equals,{}),Vt(e.assert_json_field_gte,t.assert_json_field_gte,{}),Ps(e.note,t.note)].find(r=>r!==0)??0}function cD(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function lD(e,t){let n=cD(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 dD(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!lD(r,o.path)?{...o,op:"add"}:o;n.push(i),r=xy.applyPatch(r,[i],!0,!0).newDocument}return n}function xd(e,t){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=je(e),o=t===1&&r.metadata.tests?{...r.metadata,tests:[...r.metadata.tests].sort(aD)}:r.metadata;return{front_matter:I(o,Me),body:r.body}}function ky(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=je(e);return{metadata:I(n.metadata,Me),body:n.body}}function uD(e){return Ms(e,Gt)}function Ms(e,t){if(!wr.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return an(K(xd(e,t)))}function fD(){return an(K(sD))}function vt(e){let t=xd(e.before,Gt),n=xd(e.after,Gt),r=ky(e.before),o=ky(e.after),i=xy.compare(r,o),s=dD(r,i),a=W_(e.author),c=a.harness?Object.fromEntries(Object.entries(zl().provenance_outcomes).filter(([,d])=>d.resolver!==void 0&&d.status!=="resolved")):void 0,l=c===void 0||Object.keys(c).length===0?e.context:{...e.context,agent_provenance_outcomes:c};return{ts:e.nowIso,author:e.author,author_source:e.authorSource??H_(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:an(K(t)),after_hash:an(K(n)),item_hash_version:Gt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function Ay(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pD(e){let t=e.ts.trim();return t.length>0?t:oe()}function Sy(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function Ls(e,t){let n=pD(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(Ay(r))return JSON.stringify(Sy(r,n))}catch{}return e}return Ay(e)?JSON.stringify(Sy(e,n)):JSON.stringify(e)}async function Tt(e,t){let n=await $e("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Ct(e,Ls(n.result,t)),await Ro(e),await Ds(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 Ct(o,Ls(r.line,t)),await Ro(o),await Ds(o);return}await Ct(o,Ls(r.entry??t,t)),await Ro(o),await Ds(o);return}}await Ct(e,Ls(t,t)),await Ro(e),await wy(e,t)}import Cd 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]="c823af51-0cfd-536b-8f85-1f3e72db1c86")}catch{}})();var mD={metadata:{},body:""};function Er(){return structuredClone(mD)}function Fs(e,t=Gt){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Ms(No(e),t)}catch{}return an(K({replay_fallback:!0,metadata:e.metadata,body:e.body}))}function No(e){return{metadata:e.metadata,body:e.body}}function _D(e,t={}){return je(No(e),t)}function gD(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=je(e);return{metadata:I(t.metadata,Me),body:t.body}}function Cy(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function yD(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Od(e){return Array.isArray(e)?e.filter(yD).map(t=>({...t,path:Cy(t.path),from:typeof t.from=="string"?Cy(t.from):void 0})):[]}function hD(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 xn(e,t){try{let n=Od(t),r=Cd.applyPatch(structuredClone(e),n,!0,!1).newDocument;return hD(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 bD(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&wr.includes(t)))]}function Iy(e){return e!==void 0&&!wr.includes(e)}function wD(e,t){return e!==void 0?[e]:t===void 0?[...wr]:[t]}function Id(e){let t=Er(),n,r,o=[];for(let i=0;i<e.length;i+=1){let s=e[i],a=s.item_hash_version;if(Iy(a)){o.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${i+1}`);let f=xn(t,s.patch);if(!f.ok)return{ok:!1,errors:[...o,`verify_failed:patch_apply_failed:entry_${i+1}`]};t=f.document,n=void 0,r=void 0;continue}let c=xn(t,s.patch);if(!c.ok)return{ok:!1,errors:[...o,`verify_failed:patch_apply_failed:entry_${i+1}`]};let d=wD(a,r).filter(f=>Fs(t,f)===s.before_hash);if(d.length===0)return{ok:!1,errors:[...o,`verify_failed:before_hash_mismatch:entry_${i+1}`]};let u=d.find(f=>Fs(c.document,f)===s.after_hash);if(u===void 0)return{ok:!1,errors:[...o,`verify_failed:after_hash_mismatch:entry_${i+1}`]};t=c.document,n=u,r=a??r}return o.length>0?{ok:!1,errors:o,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Cn(e){let t=Id(e);return{ok:t.ok,errors:t.errors}}function Oy(e,t){try{return{ok:!0,document:Cd.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function ED(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Od(t)){let c=Oy(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=Oy(n,{...a,op:"add"});if(l.ok){n=l.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 vD(e){let t=bD(e);if(t.length===1)return t[0];let n=Id(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Gt}function fW(e,t=vD(e)){let n=e.findIndex(u=>Iy(u.item_hash_version));if(n>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[n]?.item_hash_version)}:entry_${n+1}`);let r=Er(),o=[],i=[],s=0,a=0,c=0,l=0,d=t!==1||e.some(u=>u.item_hash_version!==void 0);for(let u=0;u<e.length;u+=1){let f=e[u],p=Fs(r,t),_=xn(r,f.patch),y,b,E=!1,T=0,O=0;if(_.ok)y=_.document,b=f.patch;else{let le=ED(r,f.patch);y=le.document,b=Cd.compare(r,y),E=!0,T=le.convertedReplaceToAdd,O=le.skippedOps,c+=T,l+=O,a+=1}let M=Fs(y,t),W=p!==f.before_hash||M!==f.after_hash;W&&(s+=1);let Ee={...f,patch:b,before_hash:p,after_hash:M};d?Ee.item_hash_version=t:delete Ee.item_hash_version,o.push(Ee),i.push({index:u+1,rehashed:W,patch_repaired:E,converted_replace_to_add:T,skipped_ops:O}),r=y}return{entries:o,finalDocument:r,entriesRehashed:s,entriesPatchRepaired:a,convertedReplaceToAdd:c,skippedOps:l,details:i,itemHashVersion:t,explicitItemHashVersion:d}}function pW(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
83
+ LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),l=c.length>t.limit,d=c.slice(0,t.limit).map(u=>({stream_id:String(u.stream_id),stream_offset:Number(u.stream_offset),entry:JSON.parse(String(u.entry_json))}));return s.close(),{events:d,has_more:l}}catch{return s?.close(),null}}import Ad from"node:fs/promises";import br 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]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var sD=br.join("runtime","history-drift-cache.json"),Ey={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 vy(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function aD(e){let t=br.join(e,sD),n=!1,r="invalid_cache_path";try{n=(await Ad.stat(await Ad.realpath(e))).isDirectory()}catch(o){let i=vy(o);r=i===void 0?"unknown":Ey[i]??"filesystem_error"}if(!n){Io(`[pm] warning: history_drift_cache_invalidation_failed:${r}
84
+ `);return}try{await Ad.rm(t,{force:!0})}catch(o){let i=vy(o);if(le(o))return;let s=i===void 0?"unknown":Ey[i]??"filesystem_error";Io(`[pm] warning: history_drift_cache_invalidation_failed:${s}
85
+ `)}}async function Ro(e){let t=br.dirname(br.resolve(e));br.basename(t)==="history"&&await aD(br.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]="60d6ec0e-a8ed-5a5d-b5bd-d29da8532a79")}catch{}})();var cD={front_matter:{},body:""},Kt=3,wr=[1,2,3];function Ps(e,t){return(e??"").localeCompare(t??"")}function Ty(e,t){return(e??0)-(t??0)}function Wt(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function lD(e,t){return[e.scope.localeCompare(t.scope),Ps(e.path,t.path),Ps(e.command,t.command),Ty(e.timeout_seconds,t.timeout_seconds),Ps(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,Wt(e.env_clear,t.env_clear,[]),Wt(e.env_set,t.env_set,{}),Wt(e.assert_stdout_contains,t.assert_stdout_contains,[]),Wt(e.assert_stdout_regex,t.assert_stdout_regex,[]),Wt(e.assert_stderr_contains,t.assert_stderr_contains,[]),Wt(e.assert_stderr_regex,t.assert_stderr_regex,[]),Ty(e.assert_stdout_min_lines,t.assert_stdout_min_lines),Wt(e.assert_json_field_equals,t.assert_json_field_equals,{}),Wt(e.assert_json_field_gte,t.assert_json_field_gte,{}),Ps(e.note,t.note)].find(r=>r!==0)??0}function dD(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function uD(e,t){let n=dD(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 fD(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!uD(r,o.path)?{...o,op:"add"}:o;n.push(i),r=xy.applyPatch(r,[i],!0,!0).newDocument}return n}function Ms(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let o=je(e),s=t===1||t===2&&n?{...o.metadata,...o.metadata.dependencies===void 0?{}:{dependencies:o.metadata.dependencies.map(l=>({...l,id:l.id.toLowerCase()}))},...o.metadata.tests===void 0?{}:{tests:o.metadata.tests.map(({workspace_context_mode:l,provenance:d,provenance_invalid:u,...f})=>f)},...o.metadata.test_runs===void 0?{}:{test_runs:o.metadata.test_runs.map(({executions:l,...d})=>d)}}:o.metadata,a=t===1&&s.tests?{...s,tests:[...s.tests].sort(lD)}:s;return{front_matter:I(a,Me),body:o.body}}function ky(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=je(e);return{metadata:I(n.metadata,Me),body:n.body}}function pD(e){return Sd(e,Kt)}function Sd(e,t){if(!wr.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Lt(B(Ms(e,t)))}function Cy(e,t){let n=Sd(e,t);return t===2?[n,Lt(B(Ms(e,t,!0)))]:[n]}function mD(){return Lt(B(cD))}function At(e){let t=Ms(e.before,Kt),n=Ms(e.after,Kt),r=ky(e.before),o=ky(e.after),i=xy.compare(r,o),s=fD(r,i),a=W_(e.author),c=a.harness?Object.fromEntries(Object.entries(Ul().provenance_outcomes).filter(([,d])=>d.resolver!==void 0&&d.status!=="resolved")):void 0,l=c===void 0||Object.keys(c).length===0?e.context:{...e.context,agent_provenance_outcomes:c};return{ts:e.nowIso,author:e.author,author_source:e.authorSource??H_(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:Lt(B(t)),after_hash:Lt(B(n)),item_hash_version:Kt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function Ay(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _D(e){let t=e.ts.trim();return t.length>0?t:oe()}function Sy(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function Ls(e,t){let n=_D(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(Ay(r))return JSON.stringify(Sy(r,n))}catch{}return e}return Ay(e)?JSON.stringify(Sy(e,n)):JSON.stringify(e)}async function St(e,t){let n=await $e("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Rt(e,Ls(n.result,t)),await Ro(e),await Ds(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 Rt(o,Ls(r.line,t)),await Ro(o),await Ds(o);return}await Rt(o,Ls(r.entry??t,t)),await Ro(o),await Ds(o);return}}await Rt(e,Ls(t,t)),await Ro(e),await wy(e,t)}import Cd 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]="c9488ed4-8228-5e7c-9717-69dd7a3275c4")}catch{}})();var gD={metadata:{},body:""};function Er(){return structuredClone(gD)}function mW(e,t=Kt){return xd(e,t)[0]}function xd(e,t){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Cy(No(e),t)}catch{}let n=Lt(B({replay_fallback:!0,metadata:e.metadata,body:e.body}));return t===2?[n,n]:[n]}function Ry(e,t,n,r){let o=xd(e,n),i=xd(t,n);return{beforeHashes:o,afterHashes:i,pairIndex:o.findIndex((s,a)=>s===r.before_hash&&i[a]===r.after_hash),beforeIndex:o.indexOf(r.before_hash),afterIndex:i.indexOf(r.after_hash)}}function No(e){return{metadata:e.metadata,body:e.body}}function yD(e,t={}){return je(No(e),t)}function hD(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=je(e);return{metadata:I(t.metadata,Me),body:t.body}}function Oy(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function bD(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Od(e){return Array.isArray(e)?e.filter(bD).map(t=>({...t,path:Oy(t.path),from:typeof t.from=="string"?Oy(t.from):void 0})):[]}function wD(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 vr(e,t){try{let n=Od(t),r=Cd.applyPatch(structuredClone(e),n,!0,!1).newDocument;return wD(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 ED(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&wr.includes(t)))]}function Ny(e){return e!==void 0&&!wr.includes(e)}function vD(e,t){return e!==void 0?[e]:t===void 0?[...wr]:[t]}function Id(e){let t=Er(),n,r,o=[];for(let i=0;i<e.length;i+=1){let s=e[i],a=s.item_hash_version,c=Ny(a);c&&o.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${i+1}`);let l=vr(t,s.patch);if(!l.ok)return{ok:!1,errors:[...o,`verify_failed:patch_apply_failed:entry_${i+1}`]};if(c){t=l.document,n=void 0,r=void 0;continue}let u=vD(a,r).map(_=>({version:_,match:Ry(t,l.document,_,s)})),f=u.find(({match:_})=>_.pairIndex>=0);if(f===void 0){let _=u.some(({match:y})=>y.beforeIndex>=0);return{ok:!1,errors:[...o,`verify_failed:${_?"after":"before"}_hash_mismatch:entry_${i+1}`]}}let p=f.version;t=l.document,n=p,r=a??r}return o.length>0?{ok:!1,errors:o,...n===void 0?{}:{item_hash_version:n}}:{ok:!0,errors:[],...n===void 0?{}:{item_hash_version:n}}}function Cn(e){let t=Id(e);return{ok:t.ok,errors:t.errors}}function Iy(e,t){try{return{ok:!0,document:Cd.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function TD(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Od(t)){let c=Iy(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=Iy(n,{...a,op:"add"});if(l.ok){n=l.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 kD(e){let t=ED(e);if(t.length===1)return t[0];let n=Id(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Kt}function _W(e,t=kD(e),n={}){let r=e.findIndex(p=>Ny(p.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=Er(),i=[],s=[],a=0,c=0,l=0,d=0,u,f=t!==1||e.some(p=>p.item_hash_version!==void 0);for(let p=0;p<e.length;p+=1){let _=e[p],y=vr(o,_.patch),b,E,T=!1,O=0,P=0;if(y.ok)b=y.document,E=_.patch;else{let He=TD(o,_.patch);b=He.document,E=Cd.compare(o,b),T=!0,O=He.convertedReplaceToAdd,P=He.skippedOps,l+=O,d+=P,c+=1}let F=Ry(o,b,t,_);u===void 0||n.continuousHashSurface!==!0?u=[F.pairIndex,F.beforeIndex,F.afterIndex,Math.min(u??0,F.beforeHashes.length-1)].find(He=>He>=0):u=Math.min(u,F.beforeHashes.length-1);let xe=F.beforeHashes[u],me=F.afterHashes[u],et=xe!==_.before_hash||me!==_.after_hash;et&&(a+=1);let Be={..._,patch:E,before_hash:xe,after_hash:me};f?Be.item_hash_version=t:delete Be.item_hash_version,i.push(Be),s.push({index:p+1,rehashed:et,patch_repaired:T,converted_replace_to_add:O,skipped_ops:P}),o=b}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:l,skippedOps:d,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function gW(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
86
86
  `)}
87
- `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function Ry(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Rd(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?Ry(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Ry(t):"root"}function $s(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function TD(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=Er(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,l=xn(o,a.patch),d;l.ok?(d=l.document,o=d):d=c;let u=new Set;for(let p of a.patch)u.add(Rd(p.path)),p.from!==void 0&&u.add(Rd(p.from));let f=[...u].sort((p,_)=>p.localeCompare(_));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let p={field:r,before:$s(c,r),after:$s(d,r)};i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:[r],changes:[p]})}else{let p=f.map(_=>({field:_,before:$s(c,_),after:$s(d,_)}));i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:f,changes:p})}}return i}import kD from"node:fs/promises";import AD 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 SD(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function xD(e,t){return new h(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,g.NOT_FOUND)}async function CD(e,t){return await si(AD.dirname(e)),await(await kD.open(e,"a")).close(),ye({path:e,scope:"project",op:`${t}:history:auto_create`})}async function js(e){return Ny({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Ny(e){let t=SD(e.itemIds),n=[],r=[];for(let o of t){let i=Zn(e.pmRoot,o);if(!await ee(i)){if(e.settings.history.missing_stream==="strict_error")throw xD(o,e.commandLabel);r.push(...await CD(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import kt from"node:fs/promises";import Nd from"node:path";import{randomUUID as OD}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]="a9ad8a9f-de6e-5bce-8685-844f1129d5fb")}catch{}})();function ID(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 My(e){try{let t=await kt.readFile(e,"utf8");return await He({path:e,scope:"project"}),ID(t)}catch(t){return de(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Dd(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Fy(e,t){await ye({path:e,scope:"project",op:t})}function RD(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:oe(),ttl_seconds:n}}async function ND(e,t,n,r){await kt.mkdir(Nd.dirname(e),{recursive:!0});let o=await kt.open(e,"wx");try{await o.writeFile(`${JSON.stringify(RD(t,n,r),null,2)}
88
- `,"utf8")}finally{await o.close()}await Fy(e,"lock:create")}async function $y(e,t){try{return await kt.unlink(e),await Fy(e,t),!0}catch{return!1}}function jy(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 DD(e){return e?.owner?` (owner ${e.owner})`:""}var PD=25,LD=200,MD=250,FD=3,$D=".stale-cleanup",Uy="owner.json",jD=1e4,UD=5*6e4;function Dy(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 zD(e){let t=process.env.PM_LOCK_WAIT_MS,n=Dy(t);if(n!==void 0)return n;let r=Dy(e);return r!==void 0?r:0}function qD(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function zy(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new h(`Item ${e} is locked${DD(t)}${r}`,g.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:MD}})}function VD(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 GD(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new h(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,g.CONFLICT)}}function BD(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 qy(e){try{return BD(await kt.readFile(Nd.join(e,Uy),"utf8"))}catch{return null}}function HD(e){try{return process.kill(e,0),!0}catch(t){return!Dd(t,"ESRCH")}}async function Pd(e){try{return await kt.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Py(e,t){let n=await qy(e);n===null||n.token!==t||await Pd(e)}async function Ly(e){try{await kt.mkdir(e)}catch(n){return Dd(n,"EEXIST"),null}let t={pid:process.pid,token:OD()};try{await kt.writeFile(Nd.join(e,Uy),`${JSON.stringify(t)}
89
- `,"utf8")}catch{return await Pd(e),null}return t}async function WD(e){let t;try{let r=await kt.stat(e);if(t=Date.now()-r.mtimeMs,t<=jD)return!1}catch(r){return de(r)}let n=await qy(e);return n!==null&&HD(n.pid)&&t<=UD?!1:Pd(e)}async function KD(e,t){let n=`${e}${$D}`,r=await Ly(n);if(r!==null)return async()=>Py(n,r.token);if(!await WD(n))return null;let o=await Ly(n);return o===null?null:async()=>Py(n,o.token)}async function YD(e){let t=await KD(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await My(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!jy(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(GD(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=FD)throw zy(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await $y(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function ke(e,t,n,r,o=!1,i=!0,s){let a=await $e("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let p=VD(a.result);if(p)return async()=>{await Promise.resolve(p()),await $e("lock_release",{pm_root:e,id:t,owner:r})}}let c=Ap(e,t),l=zD(s),d=Date.now(),u=0,f=PD;for(;;)try{return await ND(c,t,r,n),async()=>{await $y(c,"lock:release"),await $e("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!Dd(p,"EEXIST"))throw new h(`Failed to acquire lock for ${t}: ${z(p)}`,g.GENERIC_FAILURE);let _=await My(c);if(jy(_.info,n)){let b=await YD({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:u,waitBudgetMs:l,startedAtMs:d,fallbackLockInfo:_});if(_=b.lockInfo,b.staleRemovalCounted&&(u+=1),b.shouldRetryCreate)continue}let y=Date.now()-d;if(l===0||y>=l)throw zy(t,_.info,l===0?0:y);await qD(Math.min(f,l-y)),f=Math.min(f*2,LD)}}import Vy from"node:fs/promises";import vr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9027d972-ce29-5511-ba81-27e17d97446e")}catch{}})();var Bt="_workspace";function On(e){return vr.join(e,"history",`${Bt}.jsonl`)}function Ld(e,t){return{metadata:{id:Bt,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 Tr(e,t=e.length){let n=Er();for(let r of e.slice(0,t))n=xn(n,r.patch).document;return No(n)}function Do(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Po(e){throw new h(`Workspace history verification failed: ${e.join(", ")}`,g.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Md(e,t){let n=vr.resolve(t),r=vr.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||vr.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function XD(e){let t=await Ke(On(e),Bt),n=Cn(t);n.ok||Po(n.errors);let r=Do(t.length===0?Bn:Tr(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=Md(e,vr.resolve(e,c));if(l=await Y(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(K(u)===K(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Gy(e){let t=On(e.pmRoot),n=await Ke(t,Bt),r=Cn(n);r.ok||Po(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=new Date().toISOString(),s=n.length===0?Bn:Tr(n),a=Do(s),c=a[e.documentPath];if(c!==void 0&&K(c)!==K(e.before))throw new h(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,g.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 l=Ld({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),d=vt({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:l,message:e.message});return await Tt(t,d),{entry:d,historyPath:t}}async function JD(e){let t=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Gy(e)}finally{await t()}}async function QD(e){let t=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=On(e.pmRoot),r=await Ke(n,Bt),o=Cn(r);o.ok||Po(o.errors);let i=r.length===0?Bn:Tr(r),s=vt({nowIso:new Date().toISOString(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Tt(n,s),{entry:s,historyPath:n}}finally{await t()}}async function By(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await P(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Gy({pmRoot:e.pmRoot,documentPath:vr.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await Vy.rm(e.filePath,{force:!0}):await P(e.filePath,t),o}return!0}async function ZD(e){let t=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await Y(e.filePath),r=await e.mutate(n);return{changed:await By({...e,raw:r.raw},n),result:r.result}}finally{await t()}}async function Fd(e){let t=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await By(e,await Y(e.filePath))}finally{await t()}}async function eP(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Md(e.pmRoot,e.filePath),i=On(e.pmRoot),s=await Ke(i,Bt),a=Cn(s);a.ok||Po(a.errors);let c=Tr(s),l=Do(c);if(!Object.hasOwn(l,r))throw new TypeError(`Workspace history does not govern document ${r}`);let d=await Y(o);if(d===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(d);if(K(l[r])===K(u))return{changed:!1,historyPath:i};let f=new Date().toISOString(),p=vt({nowIso:f,author:e.author,op:e.op,before:c,after:Ld({...l,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Tt(i,p),{changed:!0,entry:p,historyPath:i}}finally{await n()}}async function tP(e){let t=await ke(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Md(e.pmRoot,e.filePath),o=await Ke(On(e.pmRoot),Bt),i=Cn(o);if(i.ok||Po(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=Do(Tr(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Y(r),c=`${JSON.stringify(s,null,2)}
90
- `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let l=Tr(o),d=new Date().toISOString(),u=vt({nowIso:d,author:e.author,op:e.op,before:l,after:Ld({...Do(l),[n]:s},l.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await P(r,c);try{await Tt(On(e.pmRoot),u)}catch(f){throw a===null?await Vy.rm(r,{force:!0}):await P(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}import{readFile as nP}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]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}catch{}})();var rP=e=>nP(e,"utf8");async function oP(e,t,n=rP){if(t!==void 0)throw new h("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",g.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});let r=e.trim();if(r.length===0)throw new h("--body-file requires a file path.",g.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});if(r==="-")return await or().resolveValue("-","--body-file");try{return await n(r)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new h(s?`--body-file "${r}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${r}"${a}. Check that the file exists and is readable.`,g.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${i?` (underlying error: ${i})`:""}.`,nextSteps:[`Verify the path: ls -l "${r}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}import iP from"node:crypto";import Hy 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]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function Ky(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function Us(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function In(e,t){let n=Ky(t),r=Us(e);return r.startsWith(n)?r:`${n}${r}`}function sP(e){let t=ep(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=iP.randomInt(0,36).toString(36);return n}async function aP(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[Hy.join(e,o,`${t}.md`),Hy.join(e,o,`${t}.toon`)]);return(await Promise.all(r.map(o=>ee(o)))).some(Boolean)}var Wy=4,Yy=12;function cP(e){return typeof e!="number"||!Number.isFinite(e)?Wy:Math.min(Yy,Math.max(Wy,Math.trunc(e)))}async function lP(e,t,n={}){let r=cP(n.tokenLength),o=Math.min(r+6,Yy),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${Ky(t)}${sP(r)}`;if(n.probeExisting===!1||!await aP(e,a,n.typeToFolder??_e))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]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();var dP=new Set(["none","null","undefined"]);function a6(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",g.USAGE)}function uP(e){if(typeof e!="string")throw new h("--parent must be a string. Use --unset parent to clear this field.",g.USAGE);let t=e.trim();if(t.length===0)throw new h("--parent must not be empty. Use --parent none to unset.",g.USAGE);if(Xy(t))throw new h(`--parent must not use placeholder token "${t}". Use --unset parent to clear this field.`,g.USAGE);return t}function Xy(e){return dP.has(e.trim().toLowerCase())}function fP(e,t){if(t==="strict_error")throw new h(`Parent item "${e}" was not found. Create it first or use --parent none.`,g.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function pP(e,t,n){let r=In(e,n),o=In(t,n);if(r!==o)return;let i=t!==o||e!==r?` (normalized from parent "${t}" and item "${e}")`:"";throw new h(`Parent item "${o}" cannot be the same as item "${r}"${i}. Use --unset parent to clear this field.`,g.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var $d={critical:0,high:1,medium:2,low:3,minimal:4},mP=Object.keys($d),_P=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${mP.join(", ")}), case-insensitive`;function zs(e){return new h(`Invalid priority "${e}". Accepted values: ${_P}.`,g.USAGE)}function gP(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw zs(String(e))}if(typeof e!="string")throw zs(String(e));let t=e.trim();if(t.length===0)throw zs(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call($d,n))return $d[n];if(/^[0-4]$/.test(t))return Number(t);throw zs(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]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();var yP=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,hP=64;function m6(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",g.USAGE)}function bP(e,t,n){let r=t.trim();if(r.length===0)throw new h(`--${e} must not be empty. Use --${e} none to unset.`,g.USAGE);if(r.length<=hP&&yP.test(r))return{value:r,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(n==="strict_error")throw new h(`Invalid --${e} value "${r}". ${i}`,g.USAGE);return{value:r,warnings:[`validation_warning:${e}_format:${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]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();var Jy={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},Qy="all";function w6(e){if(typeof e!="string")return!1;let t=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return t.length===1&&t[0]===Qy}function wP(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Jy[n];return r?t[r]:hn(e,t)}function EP(e){let t=new Set(Object.keys(Jy));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function vP(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of EP(t)){let s=Be(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function TP(e,t,n){if(typeof e!="string")return;let r=n?.strict===!0,o=n?.flagLabel??"--status",i=e.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return;if(i.filter(c=>c.trim().toLowerCase()===Qy).length>0){if(i.length===1)return;throw new h(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,g.USAGE)}let a=[];for(let c of i){let l=wP(c,t);if(l===void 0){if(r){let d=vP(c,t);throw new h(`Invalid ${o} value "${c}". Use open|closed|canceled or a configured status id${d?`. Did you mean "${d}"?`:"."}`,g.USAGE)}a.push(c);continue}a.push(l)}return[...new Set(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]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();var kP={bug:"Issue",bugfix:"Issue",defect:"Issue",incident:"Issue",enhancement:"Feature",story:"Feature",userstory:"Feature","user-story":"Feature","user story":"Feature",change:"Chore",ticket:"Task",todo:"Task"};function AP(e){if(e!==void 0)return kP[e.trim().toLowerCase()]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();function eh(e){let t=[],n=new Set;for(let r of e)for(let o of Object.keys(r))n.has(o)||(n.add(o),t.push(o));return t}function jd(e){return e==null?"":Array.isArray(e)?e.map(t=>jd(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function Zy(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function SP(e){if(e.length===0)return"";let t=eh(e),n=[t.map(r=>Zy(r)).join(",")];for(let r of e)n.push(t.map(o=>Zy(jd(r[o]))).join(","));return n.join(`
91
- `)}function xP(e){if(e.length===0)return"";let t=eh(e),n=e.map(s=>t.map(a=>jd(s[a]))),r=t.map((s,a)=>Math.max(s.length,...n.map(c=>c[a].length))),o=(s,a)=>s.padEnd(r[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(r.map(s=>"-".repeat(s)).join("-+-"));for(let s of n)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
92
- `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9581c92-5e8a-589d-9681-d4d014e6902b")}catch{}})();function CP(e,t="--limit"){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||n<0)throw new h(`${t} must be a non-negative number`,g.USAGE);return Math.floor(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]="989b570c-112e-5ee3-8731-ab34f215ba45")}catch{}})();var OP=new Map(Yn.map(e=>[e.toLowerCase(),e])),IP=/^[A-Za-z][A-Za-z0-9_-]*$/;function th(e,t){if(!IP.test(e))throw new Error(`${t} "${e}" is not a valid identifier. Use a single letter-led token of letters, digits, hyphen, or underscore with no spaces or punctuation (e.g. "Spike" or "code-review").`)}function Ud(e){return OP.get(e.trim().toLowerCase())}function oh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function RP(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function ih(e){let t=new Map;for(let n of e){let r=n.trim();if(r.length===0)continue;let o=r.toLowerCase();t.has(o)||t.set(o,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function O6(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");th(t,"Type name");let n=Ud(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${Yn.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?xi(i):void 0,a=ih(e.aliases??[]);for(let c of a){th(c,"Alias");let l=Ud(c);if(l)throw new Error(`Alias "${c}" collides with built-in item type "${l}". Built-in types are reserved: ${Yn.join(", ")}.`)}return{name:t,description:r&&r.length>0?r:void 0,defaultStatus:o&&o.length>0?o:void 0,folder:s,aliases:a}}function I6(e,t){let n=e.name.toLowerCase(),r=new Map;for(let i of t.definitions){if(typeof i.name!="string")continue;let s=i.name.trim();if(!(s.length===0||s.toLowerCase()===n)){r.set(s.toLowerCase(),s);for(let a of oh(i.aliases))a.trim().length>0&&r.set(a.trim().toLowerCase(),s)}}let o=r.get(n);if(o)throw new Error(`Type name "${e.name}" collides with an alias of existing item type "${o}".`);for(let i of e.aliases){let s=r.get(i.toLowerCase());if(s)throw new Error(`Alias "${i}" already maps to existing item type "${s}".`)}}function nh(e,t){return typeof t=="string"&&t.trim().length>0?xi(t).toLowerCase():qr(e).toLowerCase()}function R6(e,t,n){let r=e.name.toLowerCase(),o=nh(e.name,e.folder),i=a=>{throw new Error(`Item type "${e.name}" would store items in folder "${o}", which already belongs to existing item type "${a}". Pass a distinct --folder to keep their storage separate.`)};for(let a of t.definitions){if(typeof a.name!="string")continue;let c=a.name.trim();c.length===0||c.toLowerCase()===r||nh(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function N6(e){if(e==null||e.trim().length===0)return{definitions:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/types.json contains invalid JSON.")}return{definitions:NP(t)}}function NP(e){let t=DP(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.name!="string"||o.name.trim().length===0||n.push(o)}return n}function DP(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 D6(e,t){let n=t.name.toLowerCase(),r=e.definitions.slice(),o=r.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===n),i=o>=0?r[o]:void 0,s=ih([...oh(i?.aliases),...t.aliases]),a={...i,name:t.name};return t.folder!==void 0&&(a.folder=t.folder),s.length>0?a.aliases=s:a.aliases!==void 0&&delete a.aliases,rh(a,"description",t.description),rh(a,"default_status",t.defaultStatus),o>=0?r[o]=a:r.push(a),r.sort((c,l)=>c.name.localeCompare(l.name)),{file:{definitions:r},definition:a,replaced:o>=0,...i&&typeof i.name=="string"?{previousName:i.name}:{}}}function P6(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=Ud(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${Yn.join(", ")}.`);let o=n.toLowerCase(),i=e.definitions.slice(),s=i.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===o);if(s<0)return{file:{definitions:i},removed:!1};let[a]=i.splice(s,1);return{file:{definitions:i},removed:!0,definition:a}}function rh(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function L6(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
93
- `}function PP(e,t){let n=e.trim().length>0?e.trim():e,r=t?.trim()||".agents/pm/schema/types.json";return`To register a custom type, run: pm schema add-type "${RP(n)}" (writes ${r}).`}function LP(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${PP(e,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]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}catch{}})();function sh(e,t){return fe(e,t)}function MP(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=ns(e,o);i!==void 0&&(r[o.metadata_key]=yn(o,i))}return r}function FP(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(Array.isArray(r)){if(Array.isArray(o)){let i=o.map(a=>String(a));if(!r.map(a=>String(a)).every(a=>i.includes(a)))return!1;continue}if(!sh(o,r[r.length-1]))return!1;continue}if(!sh(o,r))return!1}return!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]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}catch{}})();function ah(e){return typeof e=="string"?e.trim().toLowerCase():""}function qs(e,t){let n=Ie(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function $P(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=ah(r?.type);if(o.length===0||!Array.isArray(r?.allowed_transitions))continue;let i=r.allowed_transitions,s=n.get(o)??{pairs:[],denyAll:!1};i.length===0&&(s.denyAll=!0);for(let a of i){if(!Array.isArray(a)||a.length!==2)continue;let c=Ie(a[0]),l=Ie(a[1]);c.length===0||l.length===0||s.pairs.some(d=>d[0]===c&&d[1]===l)||s.pairs.push([c,l])}n.set(o,s)}return[...n.entries()].filter(([,r])=>r.pairs.length>0||r.denyAll).map(([r,o])=>({type:r,allowed_transitions:o.pairs})).sort((r,o)=>r.type.localeCompare(o.type))}function jP(e){let t=ah(e.typeName),n=e.typeWorkflows.find(s=>s.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=qs(e.fromStatus,e.statusRegistry),o=qs(e.toStatus,e.statusRegistry);return r.length>0&&r===o?{allowed:!0,hasRule:!0,allowedTransitions:n.allowed_transitions}:{allowed:n.allowed_transitions.some(s=>{let a=qs(s[0],e.statusRegistry),c=qs(s[1],e.statusRegistry);return a===r&&c===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function UP(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var ae={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ae,N=e=>typeof e=="boolean"?{ok:!0,value:e}:ae;function B(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?ae:{ok:!0,value:t}}function U(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ae}function A(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ae;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ae;r.push(i.value)}return{ok:!0,value:r}}}function qd(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}:ae}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Vs(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ae;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ae;n[r]=i.value}return{ok:!0,value:n}}}function R(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ae;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ae;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var zP=R({key:w,values:A(w),required:m(N),aliases:m(A(w)),description:m(w)}),qP=R({command:U("create","update"),option:w,required:m(N),visible:m(N),enabled:m(N)}),VP=R({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(A(w)),required_create_fields:m(A(w)),required_create_repeatables:m(A(w)),options:m(A(zP)),command_option_policies:m(A(qP))}),GP=R({id:w,aliases:m(A(w)),roles:m(A(U(...bi))),description:m(w),order:m(B())}),BP=R({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(A(w)),description:m(w),type:m(U(...Jn)),commands:m(A(U(...wi))),repeatable:m(N),required:m(N),required_on_create:m(N),required_types:m(A(w)),allow_unset:m(N)}),HP=e=>{if(!Array.isArray(e)||e.length!==2)return ae;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ae:{ok:!0,value:[t,n]}},WP=R({type:w,allowed_transitions:A(HP)}),KP=m(R({version:m(B({int:!0})),files:m(R({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(A(GP)),fields:m(A(BP)),workflow:m(R({draft_status:m(w),open_status:m(w),in_progress_status:m(w),blocked_status:m(w),close_status:m(w),canceled_status:m(w)})),type_workflows:m(A(WP)),unknown_field_policy:m(U(...Ei))})),YP=m(R({preset:m(U(...dp)),ownership_enforcement:m(U("none","warn","strict")),create_mode_default:m(U("progressive","strict")),close_validation_default:m(U("off","warn","strict")),require_close_reason:m(N),parent_reference:m(U("warn","strict_error")),metadata_profile:m(U("core","strict","custom")),force_required_for_stale_lock:m(N),create_default_type:m(w),workflow_enforcement:m(U("off","warn","strict")),duplicate_detection_mode:m(U("off","advisory","strict")),duplicate_detection_threshold:m(B({min:0,max:1})),duplicate_detection_limit:m(B({int:!0,min:0,max:20}))})),XP=R({name:w,disabled:m(N),require_trusted:m(N),require_provenance:m(N),sandbox_profile:m(U("none","restricted","strict")),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w))}),zd=U("block","warn"),JP=e=>typeof e=="string"?zd(e):R({global:m(zd),project:m(zd)})(e),QP=m(R({mode:m(U("off","warn","enforce")),trust_mode:m(U("off","warn","enforce")),pm_max_version_exceeded_mode:m(JP),require_provenance:m(N),trusted_extensions:m(A(w)),default_sandbox_profile:m(U("none","restricted","strict")),allowed_extensions:m(A(w)),blocked_extensions:m(A(w)),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w)),extension_overrides:m(A(XP))})),Rn=qd(128),ZP=R({harness:qd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(A(Rn,64)),model_environment_keys:m(A(Rn,64)),session_environment_keys:m(A(Rn,64)),provenance_environment_keys:m(Vs(A(Rn,64))),provenance_resolvers:m(Vs(U("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(A(Rn,64)),argv_markers:m(A(Rn,64)),client_names:m(A(Rn,64))}),eL=R({version:B({int:!0}),id_prefix:w,ids:m(R({token_length:m(B({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(R({probes_enabled:m(N),identity_vocabulary:m(R({version:B({int:!0,positive:!0}),aliases:Vs(qd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:A(ZP)})),mutation_guard:m(R({require_attributed_author:m(N),secret_guard:m(U("off","advise","block")),stale_in_progress_hours:m(B({int:!0,positive:!0}))})),item_format:m(U("toon","json_markdown")),locks:R({ttl_seconds:B({int:!0}),wait_ms:m(B({int:!0,min:0}))}),checkpoints:m(R({retention_days:m(B({int:!0,positive:!0}))})),output:R({default_format:U("toon","json")}),ux:m(R({deprecation_hints:m(N)})),history:m(R({missing_stream:U("auto_create","strict_error"),compact_policy:m(R({enabled:m(N),max_entries:m(B({int:!0,positive:!0})),trigger:m(U("health_warn","auto"))}))})),validation:m(R({sprint_release_format:U("warn","strict_error"),parent_reference:m(U("warn","strict_error")),metadata_profile:m(U("core","strict","custom")),metadata_required_fields:m(A(w)),lifecycle_stale_blocker_reason_patterns:m(A(w)),lifecycle_closure_like_blocked_reason_patterns:m(A(w)),lifecycle_closure_like_resolution_patterns:m(A(w)),lifecycle_closure_like_actual_result_patterns:m(A(w)),estimate_defaults_by_type:m(Vs(B({int:!0,positive:!0})))})),governance:YP,workflow:m(R({definition_of_done:A(w)})),testing:m(R({record_results_to_items:N,allow_untrusted_linked_tests:m(N)})),telemetry:m(R({enabled:N,first_run_prompt_completed:m(N),capture_level:m(U("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(B({int:!0,positive:!0}))})),agent_guidance:m(R({prompt_completed:m(N),declined:m(N),declined_at:m(w),template_version:m(B({int:!0,positive:!0})),last_checked_files:m(A(w))})),item_types:m(R({definitions:A(VP)})),schema:KP,context:m(R({default_depth:m(U("brief","standard","deep")),activity_limit:m(B({int:!0,positive:!0})),stale_threshold_days:m(B({int:!0,positive:!0})),sections:m(R({hierarchy:m(N),activity:m(N),progress:m(N),recently_created:m(N),unparented:m(N),blockers:m(N),files:m(N),workload:m(N),staleness:m(N),tests:m(N)}))})),extensions:R({enabled:A(w),disabled:A(w),policy:QP}),search:R({score_threshold:B(),hybrid_semantic_weight:m(B()),max_results:B({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(B()),embedding_batch_size:B({int:!0}),embedding_timeout_ms:m(B({int:!0})),scanner_max_batch_retries:B({int:!0}),provider:m(w),corpus_fields:m(A(w)),mutation_refresh_policy:m(U("cache_only","semantic_configured","semantic_auto")),query_expansion:m(R({enabled:m(N),provider:m(w)})),rerank:m(R({enabled:m(N),model:m(w),top_k:m(B({int:!0,positive:!0}))})),bm25:m(R({k1:m(B()),b:m(B())}))}),providers:R({openai:R({base_url:w,api_key:w,model:w}),ollama:R({base_url:w,model:w})}),vector_store:R({adapter:m(w),collection_name:m(w),qdrant:R({url:w,api_key:w}),lancedb:R({path:w})})});function ch(e){let t=eL(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 tL={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},lh=120;function Vd(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function uh(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var nL=uh(tL),dh=new WeakMap;function rL(e){let t=dh.get(e);if(t)return t;let n=uh(e);return dh.set(e,n),n}function B6(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return lh;if(t){let o=rL(t).get(n);if(Vd(o))return Math.floor(o)}let r=nL.get(n);return Vd(r)?Math.floor(r):lh}function Gd(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||!Vd(r)||(t[o]=Math.floor(r))}return t}import{stat as oL}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 Gs=new Map;function fh(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function iL(e){try{let t=await oL(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function Ht(e){let t=fh(e),n=await Promise.all(t.map(r=>iL(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Lo(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 ph(e){return Gs.get(e)}function Bs(e,t){let n=fh(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));Gs.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Wt(e){if(e){Gs.delete(e);return}Gs.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]="5b95183e-9fd3-55cf-9059-8736f692e96e")}catch{}})();var sL="settings:write",hh=Symbol("pm.settings.persist_source"),aL=128,cL=new Set(["off","advisory","strict"]);function mh(e){return structuredClone(tc[e])}function lL(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:x.governance.preset}function _h(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 dL(e){return e.preset==="custom"?_h({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):_h({preset:e.preset},e)}function uL(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),cL.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 Ws(e){let t=e.governance??{},n=lL(t.preset),r=uL(t);if(n==="custom"){let s=mh("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=mh(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function bh(){return structuredClone(x)}function wh(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:x.search.mutation_refresh_policy}function Eh(e){return typeof e=="boolean"?e:x.search.query_expansion.enabled}function vh(e){return typeof e!="string"?x.search.query_expansion.provider:e.trim()}function Th(e){return typeof e=="boolean"?e:x.search.rerank.enabled}function kh(e){return typeof e!="string"?x.search.rerank.model:e.trim()}function Ah(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:x.search.rerank.top_k}function Sh(e){if(typeof e!="string")return x.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,aL);return n.length>0?n:x.vector_store.collection_name}function Bd(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function fL(e,t){let n=e.schema,r=Bd(n?.statuses),o=Bd(n?.fields),i=Bd(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:kr(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:kr(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 Xd(e,t){Object.defineProperty(e,hh,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Jd(e){let t=e[hh];if(!(!t||typeof t!="object"))return t}function pL(e){let t=Jd(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,Xd(e,n)}}function Hs(e){let t=structuredClone(e.settings),n=Jd(e.settings);return n&&Xd(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function mL(e,t,n){let r=Ze(t);return[n,Te(e,r.files.types,he.types),Te(e,r.files.statuses,he.statuses),Te(e,r.files.fields,he.fields),Te(e,r.files.workflows,he.workflows)]}async function _L(e,t,n){let r=await Ht(t);Bs(e,{tracked_paths:t,signatures:r,value:Hs(n)})}async function gL(e,t,n){try{await _L(e,t,n)}catch{Wt(e)}}function gh(e,t){return e.find(n=>n.path===t)}function yL(e,t,n){for(let r of n){let o=gh(e,r),i=gh(t,r);if(!o||!i||!Lo([o],[i]))return!1}return!0}async function Hd(e,t,n,r,o){try{let i=await Ht(t);if(!yL(r,i,o)){Wt(e);return}Bs(e,{tracked_paths:t,signatures:i,value:Hs(n)})}catch{Wt(e)}}function hL(e,t){let n=Ze(e.schema),r=kr(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=fe(r,t.runtime_item_type_definitions),s=fe(n.statuses,t.runtime_schema_statuses),a=fe(n.fields,t.runtime_schema_fields),c=fe(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?kr(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 Mo(e){return{settings:bh(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function bL(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Kd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function xh(e){let t=x.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:Kd(e?.last_checked_files??t.last_checked_files)}}function Je(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function wL(e){return e==="off"||e==="warn"||e==="enforce"?e:x.extensions.policy.mode}function EL(e){return e==="off"||e==="warn"||e==="enforce"?e:x.extensions.policy.trust_mode}function Ch(e){return e==="none"||e==="restricted"||e==="strict"?e:x.extensions.policy.default_sandbox_profile}function vL(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=Ch(e.sandbox_profile));let r=Je(e.allowed_capabilities),o=Je(e.blocked_capabilities),i=Je(e.allowed_surfaces),s=Je(e.blocked_surfaces),a=Je(e.allowed_commands),c=Je(e.blocked_commands),l=Je(e.allowed_actions),d=Je(e.blocked_actions),u=Je(e.allowed_services),f=Je(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),l.length>0&&(n.allowed_actions=l),d.length>0&&(n.blocked_actions=d),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function TL(e){let t=new Map;for(let n of e??[]){let r=vL(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Wd(e){return e==="block"||e==="warn"?e:void 0}function kL(e){if(typeof e=="string")return Wd(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Wd(e.global),n=Wd(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function Ne(e,t){return Je(e?.[t]??x.extensions.policy[t])}function Oh(e){let t=kL(e?.pm_max_version_exceeded_mode);return{mode:wL(e?.mode),trust_mode:EL(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:Ne(e,"trusted_extensions"),default_sandbox_profile:Ch(e?.default_sandbox_profile),allowed_extensions:Ne(e,"allowed_extensions"),blocked_extensions:Ne(e,"blocked_extensions"),allowed_capabilities:Ne(e,"allowed_capabilities"),blocked_capabilities:Ne(e,"blocked_capabilities"),allowed_surfaces:Ne(e,"allowed_surfaces"),blocked_surfaces:Ne(e,"blocked_surfaces"),allowed_commands:Ne(e,"allowed_commands"),blocked_commands:Ne(e,"blocked_commands"),allowed_actions:Ne(e,"allowed_actions"),blocked_actions:Ne(e,"blocked_actions"),allowed_services:Ne(e,"allowed_services"),blocked_services:Ne(e,"blocked_services"),extension_overrides:TL(e?.extension_overrides??x.extensions.policy.extension_overrides)}}function Ih(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 Kt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function re(e,t){return e===void 0?t:e}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Yd(e){return Array.isArray(e)?e:[]}function AL(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Ih(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Kt(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Kt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Kt(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Kt(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Gd(e.validation?.estimate_defaults_by_type)}}function SL(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 xL(e,t){return{...t.search,...e.search,mutation_refresh_policy:wh(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Eh(e.search?.query_expansion?.enabled),provider:vh(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Th(e.search?.rerank?.enabled),model:kh(e.search?.rerank?.model),top_k:Ah(e.search?.rerank?.top_k)}}}function CL(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Sh(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function OL(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function IL(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 RL(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function kr(e){let t=(e??[]).map(r=>Si(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 Rh(e){let t=bh(),n=Ws({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:OL(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:AL(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,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:SL(e,t),agent_guidance:xh(e.agent_guidance??t.agent_guidance),item_types:{definitions:kr(e.item_types?.definitions)},schema:Ze(e.schema??t.schema),context:IL(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:Oh(e.extensions.policy??t.extensions.policy)},search:xL(e,t),providers:RL(e,t),vector_store:CL(e,t)}}function NL(e){e.agent_identity=I(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=I(De(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Yd(e.agent_identity.harness_signals).map(n=>I(De(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=I(e.locks,["ttl_seconds","wait_ms"]),e.ids=I(e.ids,["token_length"]),e.mutation_guard=I(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=I(e.checkpoints,["retention_days"]),e.output=I(e.output,["default_format"]),e.ux=I(e.ux,["deprecation_hints"]),e.history=I(e.history,["missing_stream","compact_policy"]),e.validation=I(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=I(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=I(e.workflow,["definition_of_done"]),e.testing=I(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=I(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=I(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=I(e.item_types,["definitions"]),e.schema=I(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=I(De(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=I(De(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=I(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=I(De(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=I(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=I(De(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=Yd(e.extensions.policy.extension_overrides).map(n=>I(De(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=I(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=I(De(e.search.query_expansion),["enabled","provider"]),e.search.rerank=I(De(e.search.rerank),["enabled","model","top_k"]),e.providers=I(e.providers,["openai","ollama"]),e.providers.openai=I(De(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=I(De(e.providers.ollama),["base_url","model"]),e.vector_store=I(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=I(De(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=I(De(e.vector_store.lancedb),["path"])}function DL(e){return{...e,locks:re(e.locks,x.locks),ids:re(e.ids,x.ids),agent_identity:re(e.agent_identity,x.agent_identity),mutation_guard:re(e.mutation_guard,x.mutation_guard),checkpoints:re(e.checkpoints,x.checkpoints),output:re(e.output,x.output),ux:re(e.ux,x.ux),history:re(e.history,x.history),validation:re(e.validation,x.validation),workflow:re(e.workflow,x.workflow),testing:re(e.testing,x.testing),telemetry:re(e.telemetry,x.telemetry),agent_guidance:re(e.agent_guidance,x.agent_guidance),item_types:re(e.item_types,x.item_types),schema:re(e.schema,x.schema),context:re(e.context,x.context),extensions:re(e.extensions,x.extensions),search:re(e.search,x.search),providers:re(e.providers,x.providers),vector_store:re(e.vector_store,x.vector_store)}}function PL(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:Ih(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Kt(e.validation?.lifecycle_stale_blocker_reason_patterns??x.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Kt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??x.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Kt(e.validation?.lifecycle_closure_like_resolution_patterns??x.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Kt(e.validation?.lifecycle_closure_like_actual_result_patterns??x.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Gd(e.validation?.estimate_defaults_by_type)}}function LL(e){return{...x.search,...e.search,mutation_refresh_policy:wh(e.search?.mutation_refresh_policy),query_expansion:{...x.search.query_expansion,...e.search?.query_expansion,enabled:Eh(e.search?.query_expansion?.enabled),provider:vh(e.search?.query_expansion?.provider)},rerank:{...x.search.rerank,...e.search?.rerank,enabled:Th(e.search?.rerank?.enabled),model:kh(e.search?.rerank?.model),top_k:Ah(e.search?.rerank?.top_k)}}}function ML(e){return{default_depth:e.context?.default_depth??x.context.default_depth,activity_limit:e.context?.activity_limit??x.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??x.context.stale_threshold_days,sections:{...x.context.sections,...e.context?.sections}}}function FL(e){return{...e.vector_store,adapter:e.vector_store?.adapter??x.vector_store.adapter,collection_name:Sh(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function $L(e,t,n,r){return{...e,item_format:"toon",validation:PL(e,t),governance:t,agent_guidance:xh(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:LL(e),context:ML(e),extensions:{enabled:Kd(e.extensions?.enabled),disabled:Kd(e.extensions?.disabled),policy:Oh(e.extensions?.policy)},vector_store:FL(e)}}function Nh(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(!fe(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:{};Nh(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Dh=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function yh(e,t){let n=DL(e),r=Ws(n),o=Ze(n.schema),i=hL(n,t),s=$L(n,r,o,i),a=I({...s,governance:dL(r)},Dh);return NL(a),a}function jL(e,t={}){let n=yh(e,t.persist_source);if(t.persist_source){let r=Rh(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=yh(r,t.persist_source),i=structuredClone(t.persist_source.source_settings);return Nh(i,o,n),`${JSON.stringify(I(i,Dh),null,2)}
87
+ `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function Dy(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Rd(e){if(e==="/body"||e.startsWith("/body/"))return"body";if(e==="/metadata"||e.startsWith("/metadata/")||e==="/front_matter"||e.startsWith("/front_matter/")){let n=e.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];return n?Dy(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?Dy(t):"root"}function Fs(e,t){return t==="body"?e.body:t==="metadata"?e.metadata:t==="root"?e:e.metadata[t]}function AD(e,t){let n=t?.windowStartIndex??0,r=t?.field;if(e.length===0||n>=e.length)return[];let o=Er(),i=[];for(let s=0;s<e.length;s+=1){let a=e[s],c=o,l=vr(o,a.patch),d;l.ok?(d=l.document,o=d):d=c;let u=new Set;for(let p of a.patch)u.add(Rd(p.path)),p.from!==void 0&&u.add(Rd(p.from));let f=[...u].sort((p,_)=>p.localeCompare(_));if(s>=n)if(r!==void 0){if(!u.has(r))continue;let p={field:r,before:Fs(c,r),after:Fs(d,r)};i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:[r],changes:[p]})}else{let p=f.map(_=>({field:_,before:Fs(c,_),after:Fs(d,_)}));i.push({index:s+1,ts:a.ts,op:a.op,author:a.author,patch_ops:a.patch.length,changed_fields:f,changes:p})}}return i}import SD from"node:fs/promises";import xD 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 CD(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function OD(e,t){return new h(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,g.NOT_FOUND)}async function ID(e,t){return await si(xD.dirname(e)),await(await SD.open(e,"a")).close(),ye({path:e,scope:"project",op:`${t}:history:auto_create`})}async function $s(e){return Py({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function Py(e){let t=CD(e.itemIds),n=[],r=[];for(let o of t){let i=Zn(e.pmRoot,o);if(!await ee(i)){if(e.settings.history.missing_stream==="strict_error")throw OD(o,e.commandLabel);r.push(...await ID(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings:r}}import xt from"node:fs/promises";import Nd from"node:path";import{randomUUID as RD}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]="a9ad8a9f-de6e-5bce-8685-844f1129d5fb")}catch{}})();function ND(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 $y(e){try{let t=await xt.readFile(e,"utf8");return await Ke({path:e,scope:"project"}),ND(t)}catch(t){return le(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Dd(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function jy(e,t){await ye({path:e,scope:"project",op:t})}function DD(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:oe(),ttl_seconds:n}}async function PD(e,t,n,r){await xt.mkdir(Nd.dirname(e),{recursive:!0});let o=await xt.open(e,"wx");try{await o.writeFile(`${JSON.stringify(DD(t,n,r),null,2)}
88
+ `,"utf8")}finally{await o.close()}await jy(e,"lock:create")}async function Uy(e,t){try{return await xt.unlink(e),await jy(e,t),!0}catch{return!1}}function zy(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 LD(e){return e?.owner?` (owner ${e.owner})`:""}var MD=25,FD=200,$D=250,jD=3,UD=".stale-cleanup",qy="owner.json",zD=1e4,qD=5*6e4;function Ly(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 VD(e){let t=process.env.PM_LOCK_WAIT_MS,n=Ly(t);if(n!==void 0)return n;let r=Ly(e);return r!==void 0?r:0}function GD(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function Vy(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new h(`Item ${e} is locked${LD(t)}${r}`,g.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:$D}})}function BD(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 HD(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new h(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,g.CONFLICT)}}function WD(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 Gy(e){try{return WD(await xt.readFile(Nd.join(e,qy),"utf8"))}catch{return null}}function KD(e){try{return process.kill(e,0),!0}catch(t){return!Dd(t,"ESRCH")}}async function Pd(e){try{return await xt.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function My(e,t){let n=await Gy(e);n===null||n.token!==t||await Pd(e)}async function Fy(e){try{await xt.mkdir(e)}catch(n){return Dd(n,"EEXIST"),null}let t={pid:process.pid,token:RD()};try{await xt.writeFile(Nd.join(e,qy),`${JSON.stringify(t)}
89
+ `,"utf8")}catch{return await Pd(e),null}return t}async function YD(e){let t;try{let r=await xt.stat(e);if(t=Date.now()-r.mtimeMs,t<=zD)return!1}catch(r){return le(r)}let n=await Gy(e);return n!==null&&KD(n.pid)&&t<=qD?!1:Pd(e)}async function XD(e,t){let n=`${e}${UD}`,r=await Fy(n);if(r!==null)return async()=>My(n,r.token);if(!await YD(n))return null;let o=await Fy(n);return o===null?null:async()=>My(n,o.token)}async function JD(e){let t=await XD(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await $y(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!zy(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(HD(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=jD)throw Vy(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await Uy(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function Te(e,t,n,r,o=!1,i=!0,s){let a=await $e("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i});if(a.handled){let p=BD(a.result);if(p)return async()=>{await Promise.resolve(p()),await $e("lock_release",{pm_root:e,id:t,owner:r})}}let c=Ap(e,t),l=VD(s),d=Date.now(),u=0,f=MD;for(;;)try{return await PD(c,t,r,n),async()=>{await Uy(c,"lock:release"),await $e("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!Dd(p,"EEXIST"))throw new h(`Failed to acquire lock for ${t}: ${q(p)}`,g.GENERIC_FAILURE);let _=await $y(c);if(zy(_.info,n)){let b=await JD({lockPath:c,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:u,waitBudgetMs:l,startedAtMs:d,fallbackLockInfo:_});if(_=b.lockInfo,b.staleRemovalCounted&&(u+=1),b.shouldRetryCreate)continue}let y=Date.now()-d;if(l===0||y>=l)throw Vy(t,_.info,l===0?0:y);await GD(Math.min(f,l-y)),f=Math.min(f*2,FD)}}import By from"node:fs/promises";import Tr 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]="9027d972-ce29-5511-ba81-27e17d97446e")}catch{}})();var Yt="_workspace";function On(e){return Tr.join(e,"history",`${Yt}.jsonl`)}function Ld(e,t){return{metadata:{id:Yt,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 kr(e,t=e.length){let n=Er();for(let r of e.slice(0,t))n=vr(n,r.patch).document;return No(n)}function Do(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Po(e){throw new h(`Workspace history verification failed: ${e.join(", ")}`,g.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Md(e,t){let n=Tr.resolve(t),r=Tr.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Tr.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function QD(e){let t=await Xe(On(e),Yt),n=Cn(t);n.ok||Po(n.errors);let r=Do(t.length===0?Bn:kr(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=Md(e,Tr.resolve(e,c));if(l=await Y(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(B(u)===B(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Hy(e){let t=On(e.pmRoot),n=await Xe(t,Yt),r=Cn(n);r.ok||Po(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=new Date().toISOString(),s=n.length===0?Bn:kr(n),a=Do(s),c=a[e.documentPath];if(c!==void 0&&B(c)!==B(e.before))throw new h(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,g.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 l=Ld({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),d=At({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:l,message:e.message});return await St(t,d),{entry:d,historyPath:t}}async function ZD(e){let t=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Hy(e)}finally{await t()}}async function eP(e){let t=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=On(e.pmRoot),r=await Xe(n,Yt),o=Cn(r);o.ok||Po(o.errors);let i=r.length===0?Bn:kr(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 St(n,s),{entry:s,historyPath:n}}finally{await t()}}async function Wy(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await L(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Hy({pmRoot:e.pmRoot,documentPath:Tr.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await By.rm(e.filePath,{force:!0}):await L(e.filePath,t),o}return!0}async function tP(e){let t=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=await Y(e.filePath),r=await e.mutate(n);return{changed:await Wy({...e,raw:r.raw},n),result:r.result}}finally{await t()}}async function Fd(e){let t=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Wy(e,await Y(e.filePath))}finally{await t()}}async function nP(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Md(e.pmRoot,e.filePath),i=On(e.pmRoot),s=await Xe(i,Yt),a=Cn(s);a.ok||Po(a.errors);let c=kr(s),l=Do(c);if(!Object.hasOwn(l,r))throw new TypeError(`Workspace history does not govern document ${r}`);let d=await Y(o);if(d===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(d);if(B(l[r])===B(u))return{changed:!1,historyPath:i};let f=new Date().toISOString(),p=At({nowIso:f,author:e.author,op:e.op,before:c,after:Ld({...l,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await St(i,p),{changed:!0,entry:p,historyPath:i}}finally{await n()}}async function rP(e){let t=await Te(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Md(e.pmRoot,e.filePath),o=await Xe(On(e.pmRoot),Yt),i=Cn(o);if(i.ok||Po(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=Do(kr(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Y(r),c=`${JSON.stringify(s,null,2)}
90
+ `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let l=kr(o),d=new Date().toISOString(),u=At({nowIso:d,author:e.author,op:e.op,before:l,after:Ld({...Do(l),[n]:s},l.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await L(r,c);try{await St(On(e.pmRoot),u)}catch(f){throw a===null?await By.rm(r,{force:!0}):await L(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}import{readFile as oP}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]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}catch{}})();var iP=e=>oP(e,"utf8");async function sP(e,t,n=iP){if(t!==void 0)throw new h("--body and --body-file are mutually exclusive; provide the body inline with --body or from a file with --body-file, not both.",g.USAGE,{code:"body_file_conflicts_with_body",required:"Choose exactly one body source.",why:"Both --body and --body-file set the item body; allowing both would make the effective body ambiguous.",nextSteps:["Re-run with only --body <text> or only --body-file <path>."]});let r=e.trim();if(r.length===0)throw new h("--body-file requires a file path.",g.USAGE,{code:"body_file_missing_path",required:"Pass a readable file path: --body-file <path>.",why:"An empty --body-file value has no file to read the body from."});if(r==="-")return await or().resolveValue("-","--body-file");try{return await n(r)}catch(o){let i=o?.code,s=i==="EISDIR",a=i?` (${i})`:"";throw new h(s?`--body-file "${r}" is a directory, not a file. Point it at a readable file.`:`--body-file could not read "${r}"${a}. Check that the file exists and is readable.`,g.NOT_FOUND,{code:"body_file_unreadable",required:"Point --body-file at an existing, readable file.",why:`The body content is loaded from the file at the supplied path, so an unreadable path cannot produce a body${i?` (underlying error: ${i})`:""}.`,nextSteps:[`Verify the path: ls -l "${r}"`,"Or pipe the body with --body-file -.","Or pass the body inline with --body <text>."]})}}import aP from"node:crypto";import Ky 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]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function Xy(e){let t=[],n=!1;for(let r of(e??"").toLowerCase()){let o=r.charCodeAt(0),i=o>=48&&o<=57,s=o>=97&&o<=122;if(!i&&!s){n=t.length>0;continue}n&&(t.push("-"),n=!1),t.push(r)}return t.length===0?"pm-":`${t.join("")}-`}function js(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function In(e,t){let n=Xy(t),r=js(e);return r.startsWith(n)?r:`${n}${r}`}function cP(e){let t=ep(e);if(t!==void 0)return t;let n="";for(let r=0;r<e;r+=1)n+=aP.randomInt(0,36).toString(36);return n}async function lP(e,t,n){let r=[...new Set(Object.values(n))].flatMap(o=>[Ky.join(e,o,`${t}.md`),Ky.join(e,o,`${t}.toon`)]);return(await Promise.all(r.map(o=>ee(o)))).some(Boolean)}var Yy=4,Jy=12;function dP(e){return typeof e!="number"||!Number.isFinite(e)?Yy:Math.min(Jy,Math.max(Yy,Math.trunc(e)))}async function uP(e,t,n={}){let r=dP(n.tokenLength),o=Math.min(r+6,Jy),i=0;for(;r<=o;){for(let s=0;s<32;s+=1){let a=`${Xy(t)}${cP(r)}`;if(n.probeExisting===!1||!await lP(e,a,n.typeToFolder??_e))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]="4a376062-2e23-5991-80a5-27183909caf3")}catch{}})();var fP=new Set(["none","null","undefined"]);function d6(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set parent-reference-policy requires --policy with one of: warn, strict_error (alias: strict)",g.USAGE)}function pP(e){if(typeof e!="string")throw new h("--parent must be a string. Use --unset parent to clear this field.",g.USAGE);let t=e.trim();if(t.length===0)throw new h("--parent must not be empty. Use --parent none to unset.",g.USAGE);if(Qy(t))throw new h(`--parent must not use placeholder token "${t}". Use --unset parent to clear this field.`,g.USAGE);return t}function Qy(e){return fP.has(e.trim().toLowerCase())}function mP(e,t){if(t==="strict_error")throw new h(`Parent item "${e}" was not found. Create it first or use --parent none.`,g.USAGE);return{warnings:[`validation_warning:parent_reference_missing:${e}`]}}function _P(e,t,n){let r=In(e,n),o=In(t,n);if(r!==o)return;let i=t!==o||e!==r?` (normalized from parent "${t}" and item "${e}")`:"";throw new h(`Parent item "${o}" cannot be the same as item "${r}"${i}. Use --unset parent to clear this field.`,g.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var $d={critical:0,high:1,medium:2,low:3,minimal:4},gP=Object.keys($d),yP=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${gP.join(", ")}), case-insensitive`;function Us(e){return new h(`Invalid priority "${e}". Accepted values: ${yP}.`,g.USAGE)}function hP(e){if(typeof e=="number"){if(Number.isInteger(e)&&e>=0&&e<=4)return e;throw Us(String(e))}if(typeof e!="string")throw Us(String(e));let t=e.trim();if(t.length===0)throw Us(e);let n=t.toLowerCase();if(Object.prototype.hasOwnProperty.call($d,n))return $d[n];if(/^[0-4]$/.test(t))return Number(t);throw Us(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]="bf76a01e-7292-59df-94ca-1e41aaff7365")}catch{}})();var bP=/^[A-Za-z0-9][A-Za-z0-9._/-]*$/,wP=64;function y6(e){let t=e?.trim().toLowerCase().replaceAll("-","_");if(t==="warn"||t==="strict_error")return t;if(t==="strict")return"strict_error";throw new h("Config set sprint-release-format-policy requires --policy with one of: warn, strict_error (alias: strict)",g.USAGE)}function EP(e,t,n){let r=t.trim();if(r.length===0)throw new h(`--${e} must not be empty. Use --${e} none to unset.`,g.USAGE);if(r.length<=wP&&bP.test(r))return{value:r,warnings:[]};let i="Expected 1-64 characters matching [A-Za-z0-9][A-Za-z0-9._/-]* (no spaces).";if(n==="strict_error")throw new h(`Invalid --${e} value "${r}". ${i}`,g.USAGE);return{value:r,warnings:[`validation_warning:${e}_format:${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]="d0e997bc-8bdb-5602-8606-73ecf77b2a35")}catch{}})();var Zy={open:"open_status",closed:"close_status",canceled:"canceled_status",cancelled:"canceled_status"},eh="all";function T6(e){if(typeof e!="string")return!1;let t=e.split(",").map(n=>n.trim().toLowerCase()).filter(n=>n.length>0);return t.length===1&&t[0]===eh}function vP(e,t){let n=e.trim().toLowerCase();if(n.length===0)return;let r=Zy[n];return r?t[r]:bn(e,t)}function TP(e){let t=new Set(Object.keys(Zy));for(let n of e.definitions){t.add(n.id);for(let r of n.aliases)t.add(r)}return[...t]}function kP(e,t){let n=e.trim().toLowerCase(),r,o=Number.POSITIVE_INFINITY;for(let i of TP(t)){let s=We(n,i.toLowerCase(),2);s!==null&&s<o&&(r=i,o=s)}return r}function AP(e,t,n){if(typeof e!="string")return;let r=n?.strict===!0,o=n?.flagLabel??"--status",i=e.split(",").map(c=>c.trim()).filter(c=>c.length>0);if(i.length===0)return;if(i.filter(c=>c.trim().toLowerCase()===eh).length>0){if(i.length===1)return;throw new h(`Invalid ${o} value "all". Use it by itself, or omit ${o} to search every status.`,g.USAGE)}let a=[];for(let c of i){let l=vP(c,t);if(l===void 0){if(r){let d=kP(c,t);throw new h(`Invalid ${o} value "${c}". Use open|closed|canceled or a configured status id${d?`. Did you mean "${d}"?`:"."}`,g.USAGE)}a.push(c);continue}a.push(l)}return[...new Set(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]="b7a167e0-3041-5056-a672-ea0a054ed8df")}catch{}})();var SP={bug:"Issue",bugfix:"Issue",defect:"Issue",incident:"Issue",enhancement:"Feature",story:"Feature",userstory:"Feature","user-story":"Feature","user story":"Feature",change:"Chore",ticket:"Task",todo:"Task"};function xP(e){if(e!==void 0)return SP[e.trim().toLowerCase()]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6d11dc0f-e313-5b39-965d-6bc84ad52966")}catch{}})();function nh(e){let t=[],n=new Set;for(let r of e)for(let o of Object.keys(r))n.has(o)||(n.add(o),t.push(o));return t}function jd(e){return e==null?"":Array.isArray(e)?e.map(t=>jd(t)).join(";"):typeof e=="object"?JSON.stringify(e):String(e)}function th(e){return/[",\r\n]/.test(e)?`"${e.replace(/"/g,'""')}"`:e}function CP(e){if(e.length===0)return"";let t=nh(e),n=[t.map(r=>th(r)).join(",")];for(let r of e)n.push(t.map(o=>th(jd(r[o]))).join(","));return n.join(`
91
+ `)}function OP(e){if(e.length===0)return"";let t=nh(e),n=e.map(s=>t.map(a=>jd(s[a]))),r=t.map((s,a)=>Math.max(s.length,...n.map(c=>c[a].length))),o=(s,a)=>s.padEnd(r[a]),i=[t.map((s,a)=>o(s,a)).join(" | ")];i.push(r.map(s=>"-".repeat(s)).join("-+-"));for(let s of n)i.push(s.map((a,c)=>o(a,c)).join(" | "));return i.join(`
92
+ `)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b9581c92-5e8a-589d-9681-d4d014e6902b")}catch{}})();function IP(e,t="--limit"){if(e===void 0)return;let n=Number(e);if(!Number.isFinite(n)||n<0)throw new h(`${t} must be a non-negative number`,g.USAGE);return Math.floor(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]="989b570c-112e-5ee3-8731-ab34f215ba45")}catch{}})();var RP=new Map(Yn.map(e=>[e.toLowerCase(),e])),NP=/^[A-Za-z][A-Za-z0-9_-]*$/;function rh(e,t){if(!NP.test(e))throw new Error(`${t} "${e}" is not a valid identifier. Use a single letter-led token of letters, digits, hyphen, or underscore with no spaces or punctuation (e.g. "Spike" or "code-review").`)}function Ud(e){return RP.get(e.trim().toLowerCase())}function sh(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function DP(e){return e.replace(/[\\"`$]/g,t=>`\\${t}`)}function ah(e){let t=new Map;for(let n of e){let r=n.trim();if(r.length===0)continue;let o=r.toLowerCase();t.has(o)||t.set(o,r)}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function N6(e){let t=(e.name??"").trim();if(t.length===0)throw new Error("Type name must not be empty.");rh(t,"Type name");let n=Ud(t);if(n)throw new Error(`Cannot redefine built-in item type "${n}". Built-in types are reserved: ${Yn.join(", ")}.`);let r=e.description?.trim(),o=e.defaultStatus?.trim(),i=e.folder?.trim(),s=i&&i.length>0?xi(i):void 0,a=ah(e.aliases??[]);for(let c of a){rh(c,"Alias");let l=Ud(c);if(l)throw new Error(`Alias "${c}" collides with built-in item type "${l}". Built-in types are reserved: ${Yn.join(", ")}.`)}return{name:t,description:r&&r.length>0?r:void 0,defaultStatus:o&&o.length>0?o:void 0,folder:s,aliases:a}}function D6(e,t){let n=e.name.toLowerCase(),r=new Map;for(let i of t.definitions){if(typeof i.name!="string")continue;let s=i.name.trim();if(!(s.length===0||s.toLowerCase()===n)){r.set(s.toLowerCase(),s);for(let a of sh(i.aliases))a.trim().length>0&&r.set(a.trim().toLowerCase(),s)}}let o=r.get(n);if(o)throw new Error(`Type name "${e.name}" collides with an alias of existing item type "${o}".`);for(let i of e.aliases){let s=r.get(i.toLowerCase());if(s)throw new Error(`Alias "${i}" already maps to existing item type "${s}".`)}}function oh(e,t){return typeof t=="string"&&t.trim().length>0?xi(t).toLowerCase():qr(e).toLowerCase()}function P6(e,t,n){let r=e.name.toLowerCase(),o=oh(e.name,e.folder),i=a=>{throw new Error(`Item type "${e.name}" would store items in folder "${o}", which already belongs to existing item type "${a}". Pass a distinct --folder to keep their storage separate.`)};for(let a of t.definitions){if(typeof a.name!="string")continue;let c=a.name.trim();c.length===0||c.toLowerCase()===r||oh(c,a.folder)===o&&i(c)}let s=n?.get(o);s!==void 0&&s.toLowerCase()!==r&&i(s)}function L6(e){if(e==null||e.trim().length===0)return{definitions:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/types.json contains invalid JSON.")}return{definitions:PP(t)}}function PP(e){let t=LP(e);if(!t)return[];let n=[];for(let r of t){if(typeof r!="object"||r===null||Array.isArray(r))continue;let o=r;typeof o.name!="string"||o.name.trim().length===0||n.push(o)}return n}function LP(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 M6(e,t){let n=t.name.toLowerCase(),r=e.definitions.slice(),o=r.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===n),i=o>=0?r[o]:void 0,s=ah([...sh(i?.aliases),...t.aliases]),a={...i,name:t.name};return t.folder!==void 0&&(a.folder=t.folder),s.length>0?a.aliases=s:a.aliases!==void 0&&delete a.aliases,ih(a,"description",t.description),ih(a,"default_status",t.defaultStatus),o>=0?r[o]=a:r.push(a),r.sort((c,l)=>c.name.localeCompare(l.name)),{file:{definitions:r},definition:a,replaced:o>=0,...i&&typeof i.name=="string"?{previousName:i.name}:{}}}function F6(e,t){let n=(t??"").trim();if(n.length===0)throw new Error("Type name must not be empty.");let r=Ud(n);if(r)throw new Error(`Cannot remove built-in item type "${r}". Built-in types are reserved: ${Yn.join(", ")}.`);let o=n.toLowerCase(),i=e.definitions.slice(),s=i.findIndex(c=>typeof c.name=="string"&&c.name.trim().toLowerCase()===o);if(s<0)return{file:{definitions:i},removed:!1};let[a]=i.splice(s,1);return{file:{definitions:i},removed:!0,definition:a}}function ih(e,t,n){let r=e;n!==void 0&&(r[t]=n)}function $6(e){return`${JSON.stringify({definitions:e.definitions},null,2)}
93
+ `}function MP(e,t){let n=e.trim().length>0?e.trim():e,r=t?.trim()||".agents/pm/schema/types.json";return`To register a custom type, run: pm schema add-type "${DP(n)}" (writes ${r}).`}function FP(e,t,n){return`Invalid type value "${e}". Allowed: ${t.join(", ")}. ${MP(e,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]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}catch{}})();function ch(e,t){return ue(e,t)}function $P(e,t,n){let r={};for(let o of t.command_to_fields.get(n)??[]){let i=ns(e,o);i!==void 0&&(r[o.metadata_key]=hn(o,i))}return r}function jP(e,t){for(let[n,r]of Object.entries(t)){let o=e[n];if(Array.isArray(r)){if(Array.isArray(o)){let i=o.map(a=>String(a));if(!r.map(a=>String(a)).every(a=>i.includes(a)))return!1;continue}if(!ch(o,r[r.length-1]))return!1;continue}if(!ch(o,r))return!1}return!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]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}catch{}})();function lh(e){return typeof e=="string"?e.trim().toLowerCase():""}function zs(e,t){let n=Ie(e);return n.length===0?"":t?.alias_to_id?.get(n)??n}function UP(e){let t=Array.isArray(e?.type_workflows)?e.type_workflows:[],n=new Map;for(let r of t){let o=lh(r?.type);if(o.length===0||!Array.isArray(r?.allowed_transitions))continue;let i=r.allowed_transitions,s=n.get(o)??{pairs:[],denyAll:!1};i.length===0&&(s.denyAll=!0);for(let a of i){if(!Array.isArray(a)||a.length!==2)continue;let c=Ie(a[0]),l=Ie(a[1]);c.length===0||l.length===0||s.pairs.some(d=>d[0]===c&&d[1]===l)||s.pairs.push([c,l])}n.set(o,s)}return[...n.entries()].filter(([,r])=>r.pairs.length>0||r.denyAll).map(([r,o])=>({type:r,allowed_transitions:o.pairs})).sort((r,o)=>r.type.localeCompare(o.type))}function zP(e){let t=lh(e.typeName),n=e.typeWorkflows.find(s=>s.type===t);if(!n)return{allowed:!0,hasRule:!1,allowedTransitions:[]};let r=zs(e.fromStatus,e.statusRegistry),o=zs(e.toStatus,e.statusRegistry);return r.length>0&&r===o?{allowed:!0,hasRule:!0,allowedTransitions:n.allowed_transitions}:{allowed:n.allowed_transitions.some(s=>{let a=zs(s[0],e.statusRegistry),c=zs(s[1],e.statusRegistry);return a===r&&c===o}),hasRule:!0,allowedTransitions:n.allowed_transitions}}function qP(e){return e.length===0?"(no transitions allowed)":e.map(t=>`${t[0]} -> ${t[1]}`).join(", ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var ae={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ae,N=e=>typeof e=="boolean"?{ok:!0,value:e}:ae;function W(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?ae:{ok:!0,value:t}}function z(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ae}function A(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ae;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ae;r.push(i.value)}return{ok:!0,value:r}}}function qd(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}:ae}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function qs(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ae;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ae;n[r]=i.value}return{ok:!0,value:n}}}function R(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ae;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ae;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var VP=R({key:w,values:A(w),required:m(N),aliases:m(A(w)),description:m(w)}),GP=R({command:z("create","update"),option:w,required:m(N),visible:m(N),enabled:m(N)}),BP=R({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(A(w)),required_create_fields:m(A(w)),required_create_repeatables:m(A(w)),options:m(A(VP)),command_option_policies:m(A(GP))}),HP=R({id:w,aliases:m(A(w)),roles:m(A(z(...bi))),description:m(w),order:m(W())}),WP=R({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(A(w)),description:m(w),type:m(z(...Jn)),commands:m(A(z(...wi))),repeatable:m(N),required:m(N),required_on_create:m(N),required_types:m(A(w)),allow_unset:m(N)}),KP=e=>{if(!Array.isArray(e)||e.length!==2)return ae;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ae:{ok:!0,value:[t,n]}},YP=R({type:w,allowed_transitions:A(KP)}),XP=m(R({version:m(W({int:!0})),files:m(R({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(A(HP)),fields:m(A(WP)),workflow:m(R({draft_status:m(w),open_status:m(w),in_progress_status:m(w),blocked_status:m(w),close_status:m(w),canceled_status:m(w)})),type_workflows:m(A(YP)),unknown_field_policy:m(z(...Ei))})),JP=m(R({preset:m(z(...dp)),ownership_enforcement:m(z("none","warn","strict")),create_mode_default:m(z("progressive","strict")),close_validation_default:m(z("off","warn","strict")),require_close_reason:m(N),parent_reference:m(z("warn","strict_error")),metadata_profile:m(z("core","strict","custom")),force_required_for_stale_lock:m(N),create_default_type:m(w),workflow_enforcement:m(z("off","warn","strict")),duplicate_detection_mode:m(z("off","advisory","strict")),duplicate_detection_threshold:m(W({min:0,max:1})),duplicate_detection_limit:m(W({int:!0,min:0,max:20}))})),QP=R({name:w,disabled:m(N),require_trusted:m(N),require_provenance:m(N),sandbox_profile:m(z("none","restricted","strict")),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w))}),zd=z("block","warn"),ZP=e=>typeof e=="string"?zd(e):R({global:m(zd),project:m(zd)})(e),eL=m(R({mode:m(z("off","warn","enforce")),trust_mode:m(z("off","warn","enforce")),pm_max_version_exceeded_mode:m(ZP),require_provenance:m(N),trusted_extensions:m(A(w)),default_sandbox_profile:m(z("none","restricted","strict")),allowed_extensions:m(A(w)),blocked_extensions:m(A(w)),allowed_capabilities:m(A(w)),blocked_capabilities:m(A(w)),allowed_surfaces:m(A(w)),blocked_surfaces:m(A(w)),allowed_commands:m(A(w)),blocked_commands:m(A(w)),allowed_actions:m(A(w)),blocked_actions:m(A(w)),allowed_services:m(A(w)),blocked_services:m(A(w)),extension_overrides:m(A(QP))})),Rn=qd(128),tL=R({harness:qd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(A(Rn,64)),model_environment_keys:m(A(Rn,64)),session_environment_keys:m(A(Rn,64)),provenance_environment_keys:m(qs(A(Rn,64))),provenance_resolvers:m(qs(z("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(A(Rn,64)),argv_markers:m(A(Rn,64)),client_names:m(A(Rn,64))}),nL=R({version:W({int:!0}),id_prefix:w,ids:m(R({token_length:m(W({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(R({probes_enabled:m(N),identity_vocabulary:m(R({version:W({int:!0,positive:!0}),aliases:qs(qd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:A(tL)})),mutation_guard:m(R({require_attributed_author:m(N),secret_guard:m(z("off","advise","block")),stale_in_progress_hours:m(W({int:!0,positive:!0}))})),item_format:m(z("toon","json_markdown")),locks:R({ttl_seconds:W({int:!0}),wait_ms:m(W({int:!0,min:0}))}),checkpoints:m(R({retention_days:m(W({int:!0,positive:!0}))})),output:R({default_format:z("toon","json")}),ux:m(R({deprecation_hints:m(N)})),history:m(R({missing_stream:z("auto_create","strict_error"),compact_policy:m(R({enabled:m(N),max_entries:m(W({int:!0,positive:!0})),trigger:m(z("health_warn","auto"))}))})),validation:m(R({sprint_release_format:z("warn","strict_error"),parent_reference:m(z("warn","strict_error")),metadata_profile:m(z("core","strict","custom")),metadata_required_fields:m(A(w)),lifecycle_stale_blocker_reason_patterns:m(A(w)),lifecycle_closure_like_blocked_reason_patterns:m(A(w)),lifecycle_closure_like_resolution_patterns:m(A(w)),lifecycle_closure_like_actual_result_patterns:m(A(w)),estimate_defaults_by_type:m(qs(W({int:!0,positive:!0})))})),governance:JP,workflow:m(R({definition_of_done:A(w)})),testing:m(R({record_results_to_items:N,allow_untrusted_linked_tests:m(N)})),telemetry:m(R({enabled:N,first_run_prompt_completed:m(N),capture_level:m(z("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(W({int:!0,positive:!0}))})),agent_guidance:m(R({prompt_completed:m(N),declined:m(N),declined_at:m(w),template_version:m(W({int:!0,positive:!0})),last_checked_files:m(A(w))})),item_types:m(R({definitions:A(BP)})),schema:XP,context:m(R({default_depth:m(z("brief","standard","deep")),activity_limit:m(W({int:!0,positive:!0})),stale_threshold_days:m(W({int:!0,positive:!0})),sections:m(R({hierarchy:m(N),activity:m(N),progress:m(N),recently_created:m(N),unparented:m(N),blockers:m(N),files:m(N),workload:m(N),staleness:m(N),tests:m(N)}))})),extensions:R({enabled:A(w),disabled:A(w),policy:eL}),search:R({score_threshold:W(),hybrid_semantic_weight:m(W()),max_results:W({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(W()),embedding_batch_size:W({int:!0}),embedding_timeout_ms:m(W({int:!0})),scanner_max_batch_retries:W({int:!0}),provider:m(w),corpus_fields:m(A(w)),mutation_refresh_policy:m(z("cache_only","semantic_configured","semantic_auto")),query_expansion:m(R({enabled:m(N),provider:m(w)})),rerank:m(R({enabled:m(N),model:m(w),top_k:m(W({int:!0,positive:!0}))})),bm25:m(R({k1:m(W()),b:m(W())}))}),providers:R({openai:R({base_url:w,api_key:w,model:w}),ollama:R({base_url:w,model:w})}),vector_store:R({adapter:m(w),collection_name:m(w),qdrant:R({url:w,api_key:w}),lancedb:R({path:w})})});function dh(e){let t=nL(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 rL={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},uh=120;function Vd(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function ph(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var oL=ph(rL),fh=new WeakMap;function iL(e){let t=fh.get(e);if(t)return t;let n=ph(e);return fh.set(e,n),n}function K6(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return uh;if(t){let o=iL(t).get(n);if(Vd(o))return Math.floor(o)}let r=oL.get(n);return Vd(r)?Math.floor(r):uh}function Gd(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||!Vd(r)||(t[o]=Math.floor(r))}return t}import{stat as sL}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 Vs=new Map;function mh(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function aL(e){try{let t=await sL(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function Xt(e){let t=mh(e),n=await Promise.all(t.map(r=>aL(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Lo(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 _h(e){return Vs.get(e)}function Gs(e,t){let n=mh(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));Vs.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Jt(e){if(e){Vs.delete(e);return}Vs.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]="5b95183e-9fd3-55cf-9059-8736f692e96e")}catch{}})();var cL="settings:write",wh=Symbol("pm.settings.persist_source"),lL=128,dL=new Set(["off","advisory","strict"]);function gh(e){return structuredClone(ec[e])}function uL(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:x.governance.preset}function yh(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 fL(e){return e.preset==="custom"?yh({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):yh({preset:e.preset},e)}function pL(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),dL.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 Hs(e){let t=e.governance??{},n=uL(t.preset),r=pL(t);if(n==="custom"){let s=gh("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=gh(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Eh(){return structuredClone(x)}function vh(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:x.search.mutation_refresh_policy}function Th(e){return typeof e=="boolean"?e:x.search.query_expansion.enabled}function kh(e){return typeof e!="string"?x.search.query_expansion.provider:e.trim()}function Ah(e){return typeof e=="boolean"?e:x.search.rerank.enabled}function Sh(e){return typeof e!="string"?x.search.rerank.model:e.trim()}function xh(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:x.search.rerank.top_k}function Ch(e){if(typeof e!="string")return x.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,lL);return n.length>0?n:x.vector_store.collection_name}function Bd(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function mL(e,t){let n=e.schema,r=Bd(n?.statuses),o=Bd(n?.fields),i=Bd(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Ar(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:Ar(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 Xd(e,t){Object.defineProperty(e,wh,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Jd(e){let t=e[wh];if(!(!t||typeof t!="object"))return t}function _L(e){let t=Jd(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,Xd(e,n)}}function Bs(e){let t=structuredClone(e.settings),n=Jd(e.settings);return n&&Xd(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function gL(e,t,n){let r=nt(t);return[n,ve(e,r.files.types,he.types),ve(e,r.files.statuses,he.statuses),ve(e,r.files.fields,he.fields),ve(e,r.files.workflows,he.workflows)]}async function yL(e,t,n){let r=await Xt(t);Gs(e,{tracked_paths:t,signatures:r,value:Bs(n)})}async function hL(e,t,n){try{await yL(e,t,n)}catch{Jt(e)}}function hh(e,t){return e.find(n=>n.path===t)}function bL(e,t,n){for(let r of n){let o=hh(e,r),i=hh(t,r);if(!o||!i||!Lo([o],[i]))return!1}return!0}async function Hd(e,t,n,r,o){try{let i=await Xt(t);if(!bL(r,i,o)){Jt(e);return}Gs(e,{tracked_paths:t,signatures:i,value:Bs(n)})}catch{Jt(e)}}function wL(e,t){let n=nt(e.schema),r=Ar(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=ue(r,t.runtime_item_type_definitions),s=ue(n.statuses,t.runtime_schema_statuses),a=ue(n.fields,t.runtime_schema_fields),c=ue(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Ar(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 Mo(e){return{settings:Eh(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function EL(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Kd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Oh(e){let t=x.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:Kd(e?.last_checked_files??t.last_checked_files)}}function Ze(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function vL(e){return e==="off"||e==="warn"||e==="enforce"?e:x.extensions.policy.mode}function TL(e){return e==="off"||e==="warn"||e==="enforce"?e:x.extensions.policy.trust_mode}function Ih(e){return e==="none"||e==="restricted"||e==="strict"?e:x.extensions.policy.default_sandbox_profile}function kL(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=Ih(e.sandbox_profile));let r=Ze(e.allowed_capabilities),o=Ze(e.blocked_capabilities),i=Ze(e.allowed_surfaces),s=Ze(e.blocked_surfaces),a=Ze(e.allowed_commands),c=Ze(e.blocked_commands),l=Ze(e.allowed_actions),d=Ze(e.blocked_actions),u=Ze(e.allowed_services),f=Ze(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),l.length>0&&(n.allowed_actions=l),d.length>0&&(n.blocked_actions=d),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function AL(e){let t=new Map;for(let n of e??[]){let r=kL(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Wd(e){return e==="block"||e==="warn"?e:void 0}function SL(e){if(typeof e=="string")return Wd(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Wd(e.global),n=Wd(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function Ne(e,t){return Ze(e?.[t]??x.extensions.policy[t])}function Rh(e){let t=SL(e?.pm_max_version_exceeded_mode);return{mode:vL(e?.mode),trust_mode:TL(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:Ne(e,"trusted_extensions"),default_sandbox_profile:Ih(e?.default_sandbox_profile),allowed_extensions:Ne(e,"allowed_extensions"),blocked_extensions:Ne(e,"blocked_extensions"),allowed_capabilities:Ne(e,"allowed_capabilities"),blocked_capabilities:Ne(e,"blocked_capabilities"),allowed_surfaces:Ne(e,"allowed_surfaces"),blocked_surfaces:Ne(e,"blocked_surfaces"),allowed_commands:Ne(e,"allowed_commands"),blocked_commands:Ne(e,"blocked_commands"),allowed_actions:Ne(e,"allowed_actions"),blocked_actions:Ne(e,"blocked_actions"),allowed_services:Ne(e,"allowed_services"),blocked_services:Ne(e,"blocked_services"),extension_overrides:AL(e?.extension_overrides??x.extensions.policy.extension_overrides)}}function Nh(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 Qt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function re(e,t){return e===void 0?t:e}function De(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Yd(e){return Array.isArray(e)?e:[]}function xL(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Nh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Qt(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Qt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Qt(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Qt(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Gd(e.validation?.estimate_defaults_by_type)}}function CL(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 OL(e,t){return{...t.search,...e.search,mutation_refresh_policy:vh(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Th(e.search?.query_expansion?.enabled),provider:kh(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Ah(e.search?.rerank?.enabled),model:Sh(e.search?.rerank?.model),top_k:xh(e.search?.rerank?.top_k)}}}function IL(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Ch(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function RL(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function NL(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 DL(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Ar(e){let t=(e??[]).map(r=>Si(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 Dh(e){let t=Eh(),n=Hs({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:RL(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:xL(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,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:CL(e,t),agent_guidance:Oh(e.agent_guidance??t.agent_guidance),item_types:{definitions:Ar(e.item_types?.definitions)},schema:nt(e.schema??t.schema),context:NL(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:Rh(e.extensions.policy??t.extensions.policy)},search:OL(e,t),providers:DL(e,t),vector_store:IL(e,t)}}function PL(e){e.agent_identity=I(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=I(De(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Yd(e.agent_identity.harness_signals).map(n=>I(De(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=I(e.locks,["ttl_seconds","wait_ms"]),e.ids=I(e.ids,["token_length"]),e.mutation_guard=I(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=I(e.checkpoints,["retention_days"]),e.output=I(e.output,["default_format"]),e.ux=I(e.ux,["deprecation_hints"]),e.history=I(e.history,["missing_stream","compact_policy"]),e.validation=I(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=I(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=I(e.workflow,["definition_of_done"]),e.testing=I(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=I(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=I(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=I(e.item_types,["definitions"]),e.schema=I(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=I(De(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=I(De(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=I(e.context,["default_depth","activity_limit","stale_threshold_days","sections"]),e.context.sections=I(De(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=I(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=I(De(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=Yd(e.extensions.policy.extension_overrides).map(n=>I(De(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=I(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=I(De(e.search.query_expansion),["enabled","provider"]),e.search.rerank=I(De(e.search.rerank),["enabled","model","top_k"]),e.providers=I(e.providers,["openai","ollama"]),e.providers.openai=I(De(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=I(De(e.providers.ollama),["base_url","model"]),e.vector_store=I(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=I(De(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=I(De(e.vector_store.lancedb),["path"])}function LL(e){return{...e,locks:re(e.locks,x.locks),ids:re(e.ids,x.ids),agent_identity:re(e.agent_identity,x.agent_identity),mutation_guard:re(e.mutation_guard,x.mutation_guard),checkpoints:re(e.checkpoints,x.checkpoints),output:re(e.output,x.output),ux:re(e.ux,x.ux),history:re(e.history,x.history),validation:re(e.validation,x.validation),workflow:re(e.workflow,x.workflow),testing:re(e.testing,x.testing),telemetry:re(e.telemetry,x.telemetry),agent_guidance:re(e.agent_guidance,x.agent_guidance),item_types:re(e.item_types,x.item_types),schema:re(e.schema,x.schema),context:re(e.context,x.context),extensions:re(e.extensions,x.extensions),search:re(e.search,x.search),providers:re(e.providers,x.providers),vector_store:re(e.vector_store,x.vector_store)}}function ML(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:Nh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:Qt(e.validation?.lifecycle_stale_blocker_reason_patterns??x.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:Qt(e.validation?.lifecycle_closure_like_blocked_reason_patterns??x.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:Qt(e.validation?.lifecycle_closure_like_resolution_patterns??x.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:Qt(e.validation?.lifecycle_closure_like_actual_result_patterns??x.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Gd(e.validation?.estimate_defaults_by_type)}}function FL(e){return{...x.search,...e.search,mutation_refresh_policy:vh(e.search?.mutation_refresh_policy),query_expansion:{...x.search.query_expansion,...e.search?.query_expansion,enabled:Th(e.search?.query_expansion?.enabled),provider:kh(e.search?.query_expansion?.provider)},rerank:{...x.search.rerank,...e.search?.rerank,enabled:Ah(e.search?.rerank?.enabled),model:Sh(e.search?.rerank?.model),top_k:xh(e.search?.rerank?.top_k)}}}function $L(e){return{default_depth:e.context?.default_depth??x.context.default_depth,activity_limit:e.context?.activity_limit??x.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??x.context.stale_threshold_days,sections:{...x.context.sections,...e.context?.sections}}}function jL(e){return{...e.vector_store,adapter:e.vector_store?.adapter??x.vector_store.adapter,collection_name:Ch(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function UL(e,t,n,r){return{...e,item_format:"toon",validation:ML(e,t),governance:t,agent_guidance:Oh(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:FL(e),context:$L(e),extensions:{enabled:Kd(e.extensions?.enabled),disabled:Kd(e.extensions?.disabled),policy:Rh(e.extensions?.policy)},vector_store:jL(e)}}function Ph(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(!ue(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:{};Ph(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var Lh=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function bh(e,t){let n=LL(e),r=Hs(n),o=nt(n.schema),i=wL(n,t),s=UL(n,r,o,i),a=I({...s,governance:fL(r)},Lh);return PL(a),a}function zL(e,t={}){let n=bh(e,t.persist_source);if(t.persist_source){let r=Dh(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=bh(r,t.persist_source),i=structuredClone(t.persist_source.source_settings);return Ph(i,o,n),`${JSON.stringify(I(i,Lh),null,2)}
94
94
  `}return`${JSON.stringify(n,null,2)}
95
- `}async function Yt(e){let t=ge(e),n=[t];await He({path:t,scope:"project"});let r=ph(e);if(r){let l=await Ht(r.tracked_paths);if(Lo(l,r.signatures))return Hs(r.value)}let o=await Ht([t]),i;try{i=await Y(t)}catch{return Mo("settings_read_fs_error")}if(i===null){let l=Mo();return await Hd(e,[t],l,o,[t]),l}let s=await Ht([t]);if(!Lo(o,s))return Wt(e),Yt(e);let a;try{a=JSON.parse(i)}catch{let l=Mo("settings_read_invalid_json");return await Hd(e,[t],l,s,[t]),l}let c=ch(a);if(!c.success){let l=Mo("settings_read_invalid_schema");return await Hd(e,[t],l,s,[t]),l}try{let l=Rh(c.data),d=mL(e,l.schema,t);n=d;let u=await Ht(d),f=await __(e,l.schema),p=await g_(e,l.schema),_=await Ht(d),y={...l,item_types:{definitions:kr([...l.item_types.definitions,...Yd(p.type_definitions_from_file)])},schema:p.schema};Xd(y,fL(c.data,y));let b={settings:y,metadata:{has_explicit_item_format:bL(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(E=>`runtime_schema_bootstrap_created:${E}`),...p.warnings]};return f.created_paths.length===0?Lo(u,_)?Bs(e,{tracked_paths:d,signatures:_,value:Hs(b)}):Wt(e):Wt(e),b}catch{let l=Mo("settings_read_merge_failed");return await gL(e,n,l),l}}async function ot(e){return(await Yt(e)).settings}async function Fo(e,t,n=sL){let r=ge(e),o=jL(t,{persist_source:Jd(t)});try{await Fd({pmRoot:e,filePath:r,raw:o,op:n,author:wo(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),await ye({path:r,scope:"project",op:n})}finally{Wt(e)}}import{spawnSync as Lh}from"node:child_process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}catch{}})();var UL="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",zL="PM_OLLAMA_MODEL",qL="http://localhost:11434",VL="qwen3-embedding:0.6b",GL=".agents/pm/search/lancedb/",BL=1500,HL=2500,WL=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,KL=/embed|embedding/i,it=F;function YL(){let e=it(process.env[UL]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Ph(e){return e.some(t=>it(t)!==null)}function XL(e){let t=it(e);return!!(t&&t.toLowerCase()!=="ollama")}function JL(e){let t=it(e);return!!(t&&t.toLowerCase()!=="lancedb")}function QL(e){return XL(e.search?.provider)||JL(e.vector_store?.adapter)||Ph([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Ph([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function ZL(){let e=Lh("ollama",["--version"],{encoding:"utf8",timeout:BL});return e.error?!1:e.status===0}function eM(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;let n=t.map(i=>i.split(/\s+/)[0]?.trim()).filter(i=>!!(i&&i.length>0)).filter(i=>i.toUpperCase()!=="NAME");if(n.length===0)return null;let r=n.find(i=>WL.test(i));return r||(n.find(i=>KL.test(i))??null)}function tM(e){let t=it(e.providers?.ollama?.model);if(t)return t;let n=it(process.env[zL]);if(n)return n;let r=Lh("ollama",["list"],{encoding:"utf8",timeout:HL});if(!r.error&&r.status===0){let o=eM(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function nM(e){return{baseUrl:it(e.providers?.ollama?.base_url)===null,model:it(e.providers?.ollama?.model)===null,lancedbPath:it(e.vector_store?.lancedb?.path)===null,embeddingModel:it(e.search?.embedding_model)===null}}function rM(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function oM(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=qL),t.model&&(o.model=n)}function iM(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=GL}function sM(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function Ar(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(YL()||QL(e))return t;let n=nM(e);if(!rM(n)||n.model&&!ZL())return t;let r=structuredClone(e),o=tM(r);return o?(oM(r,n,o),iM(r,n),sM(r,n,o),{settings:r,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${VL} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as aM}from"node:child_process";import{mkdirSync as Mh,rmSync as $h,statSync as cM}from"node:fs";import Ks 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]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}catch{}})();var jh="reindex",lM="search/pending-refresh.json",dM="search/pending-refresh.gate.lock",uM=3e4,fM="PM_SEARCH_REFRESH_INLINE",Uh="PM_SEARCH_REFRESH_CHILD",pM=3e4;function Fh(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Zd(){if(Fh(process.env[fM])||Fh(process.env[Uh]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}function zh(e){return Ks.join(e,lM)}function qh(e){return Ks.join(e,dM)}function mM(e){let t=qh(e);try{if(Date.now()-cM(t).mtimeMs<uM)return!1;$h(t,{recursive:!0,force:!0})}catch{}try{return Mh(Ks.dirname(t),{recursive:!0}),Mh(t),!0}catch{return!1}}function _M(e){try{$h(qh(e),{recursive:!0,force:!0})}catch{}}async function Vh(e,t,n){for(let r=0;r<50;r+=1){if(mM(e))try{return await t()}finally{_M(e)}await gM(20)}return n}function gM(e){return new Promise(t=>{setTimeout(t,e)})}async function eu(e){let t=await Y(zh(e));if(!t||t.trim().length===0)return[];try{let n=JSON.parse(t);return Array.isArray(n.ids)?n.ids.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}async function Gh(e,t){await P(zh(e),`${JSON.stringify({ids:t})}
96
- `)}async function Qd(e,t){let n=t.filter(i=>typeof i=="string"&&i.trim().length>0);if(n.length===0)return;let r=async()=>{let i=await eu(e),s=[...new Set([...i,...n])].sort((a,c)=>a.localeCompare(c));await Gh(e,s)};await Vh(e,async()=>(await r(),!0),!1)||await r()}async function yM(e){return Vh(e,async()=>{let t=await eu(e);return t.length>0&&await Gh(e,[]),t},[])}function hM(){return Ks.join(mt(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function tu(e){try{let t=aM(process.execPath,[hM()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[Uh]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function bM(e){setTimeout(()=>tu(e),pM)}async function Bh(e,t){await Qd(e,t),tu(e)}async function E8(e,t,n=bM){let r=[],o=[];if(!await ee(e))return{processed:o,rounds:0,warnings:r};let i;try{let u=await Yt(e),f=u.warnings.find(p=>p.startsWith("settings_read_"));if(f)return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${f}`]};i=Ar(u.settings).settings}catch(u){return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${z(u)}`]}}let s=null;try{s=await ke(e,jh,i.locks.ttl_seconds,wo(void 0,"pm-search-refresh"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch{}if(!s)return{processed:o,rounds:0,warnings:r};let a=0,c=!1,l=!1;try{for(;;){let u=await yM(e);if(u.length===0)break;a+=1;try{let f=await t(e,u);if(r.push(...f.warnings),f.warnings.some(p=>p.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await Qd(e,u),c=!0,l=!0;break}o.push(...f.refreshed)}catch(f){r.push(`search_background_refresh_failed:${z(f)}`),await Qd(e,u),c=!0;break}}}finally{await s?.()}return l&&n(e),(c?[]:await eu(e)).length>0&&tu(e),{processed:[...new Set(o)].sort((u,f)=>u.localeCompare(f)),rounds:a,warnings:r}}import Nn from"node:fs/promises";import Wh from"node:path";import{randomUUID as wM}from"node:crypto";import{createRequire as EM}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 vM="metadata-query-index.sqlite",$o="4";function TM(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Ys;function kM(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?TM(t):null}function jo(){return Ys!==void 0||(Ys=kM(process.versions.node,EM(import.meta.url))),Ys}function Hh(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function Sr(e){return Wh.join(e,"runtime",vM)}function AM(e){e.exec(`
95
+ `}async function Zt(e){let t=ge(e),n=[t];await Ke({path:t,scope:"project"});let r=_h(e);if(r){let l=await Xt(r.tracked_paths);if(Lo(l,r.signatures))return Bs(r.value)}let o=await Xt([t]),i;try{i=await Y(t)}catch{return Mo("settings_read_fs_error")}if(i===null){let l=Mo();return await Hd(e,[t],l,o,[t]),l}let s=await Xt([t]);if(!Lo(o,s))return Jt(e),Zt(e);let a;try{a=JSON.parse(i)}catch{let l=Mo("settings_read_invalid_json");return await Hd(e,[t],l,s,[t]),l}let c=dh(a);if(!c.success){let l=Mo("settings_read_invalid_schema");return await Hd(e,[t],l,s,[t]),l}try{let l=Dh(c.data),d=gL(e,l.schema,t);n=d;let u=await Xt(d),f=await __(e,l.schema),p=await g_(e,l.schema),_=await Xt(d),y={...l,item_types:{definitions:Ar([...l.item_types.definitions,...Yd(p.type_definitions_from_file)])},schema:p.schema};Xd(y,mL(c.data,y));let b={settings:y,metadata:{has_explicit_item_format:EL(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.created_paths.map(E=>`runtime_schema_bootstrap_created:${E}`),...p.warnings]};return f.created_paths.length===0?Lo(u,_)?Gs(e,{tracked_paths:d,signatures:_,value:Bs(b)}):Jt(e):Jt(e),b}catch{let l=Mo("settings_read_merge_failed");return await hL(e,n,l),l}}async function at(e){return(await Zt(e)).settings}async function Fo(e,t,n=cL){let r=ge(e),o=zL(t,{persist_source:Jd(t)});try{await Fd({pmRoot:e,filePath:r,raw:o,op:n,author:wo(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),await ye({path:r,scope:"project",op:n})}finally{Jt(e)}}import{spawnSync as Fh}from"node:child_process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}catch{}})();var qL="PM_DISABLE_OLLAMA_AUTO_DEFAULTS",VL="PM_OLLAMA_MODEL",GL="http://localhost:11434",BL="qwen3-embedding:0.6b",HL=".agents/pm/search/lancedb/",WL=1500,KL=2500,YL=/qwen.*(?:embed|embedding)|(?:embed|embedding).*qwen/i,XL=/embed|embedding/i,ct=$;function JL(){let e=ct(process.env[qL]);if(!e)return!1;let t=e.toLowerCase();return t==="1"||t==="true"||t==="yes"}function Mh(e){return e.some(t=>ct(t)!==null)}function QL(e){let t=ct(e);return!!(t&&t.toLowerCase()!=="ollama")}function ZL(e){let t=ct(e);return!!(t&&t.toLowerCase()!=="lancedb")}function eM(e){return QL(e.search?.provider)||ZL(e.vector_store?.adapter)||Mh([e.providers?.openai?.base_url,e.providers?.openai?.model,e.providers?.openai?.api_key])?!0:Mh([e.vector_store?.qdrant?.url,e.vector_store?.qdrant?.api_key])}function tM(){let e=Fh("ollama",["--version"],{encoding:"utf8",timeout:WL});return e.error?!1:e.status===0}function nM(e){let t=e.split(/\r?\n/).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0)return null;let n=t.map(i=>i.split(/\s+/)[0]?.trim()).filter(i=>!!(i&&i.length>0)).filter(i=>i.toUpperCase()!=="NAME");if(n.length===0)return null;let r=n.find(i=>YL.test(i));return r||(n.find(i=>XL.test(i))??null)}function rM(e){let t=ct(e.providers?.ollama?.model);if(t)return t;let n=ct(process.env[VL]);if(n)return n;let r=Fh("ollama",["list"],{encoding:"utf8",timeout:KL});if(!r.error&&r.status===0){let o=nM(typeof r.stdout=="string"?r.stdout:"");if(o)return o}return null}function oM(e){return{baseUrl:ct(e.providers?.ollama?.base_url)===null,model:ct(e.providers?.ollama?.model)===null,lancedbPath:ct(e.vector_store?.lancedb?.path)===null,embeddingModel:ct(e.search?.embedding_model)===null}}function iM(e){return e.baseUrl||e.model||e.lancedbPath||e.embeddingModel}function sM(e,t,n){if(!t.baseUrl&&!t.model)return;let r=e.providers??={},o=r.ollama??={};t.baseUrl&&(o.base_url=GL),t.model&&(o.model=n)}function aM(e,t){if(!t.lancedbPath)return;let n=e.vector_store??={},r=n.lancedb??={};r.path=HL}function cM(e,t,n){if(!t.embeddingModel)return;let r=e.search??={};r.embedding_model=n}function Sr(e){let t={settings:e,auto_ollama_defaults_applied:!1};if(JL()||eM(e))return t;let n=oM(e);if(!iM(n)||n.model&&!tM())return t;let r=structuredClone(e),o=rM(r);return o?(sM(r,n,o),aM(r,n),cM(r,n,o),{settings:r,auto_ollama_defaults_applied:!0}):{...t,auto_ollama_defaults_skipped_reason:"no_installed_embedding_model",auto_ollama_defaults_remediation:`Run ollama pull ${BL} or configure providers.ollama.model explicitly (and search.embedding_model if you need an override).`}}import{spawn as lM}from"node:child_process";import{mkdirSync as $h,rmSync as Uh,statSync as dM}from"node:fs";import Ws 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]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}catch{}})();var zh="reindex",uM="search/pending-refresh.json",fM="search/pending-refresh.gate.lock",pM=3e4,mM="PM_SEARCH_REFRESH_INLINE",qh="PM_SEARCH_REFRESH_CHILD",_M=3e4;function jh(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function Zd(){if(jh(process.env[mM])||jh(process.env[qh]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}function Vh(e){return Ws.join(e,uM)}function Gh(e){return Ws.join(e,fM)}function gM(e){let t=Gh(e);try{if(Date.now()-dM(t).mtimeMs<pM)return!1;Uh(t,{recursive:!0,force:!0})}catch{}try{return $h(Ws.dirname(t),{recursive:!0}),$h(t),!0}catch{return!1}}function yM(e){try{Uh(Gh(e),{recursive:!0,force:!0})}catch{}}async function Bh(e,t,n){for(let r=0;r<50;r+=1){if(gM(e))try{return await t()}finally{yM(e)}await hM(20)}return n}function hM(e){return new Promise(t=>{setTimeout(t,e)})}async function eu(e){let t=await Y(Vh(e));if(!t||t.trim().length===0)return[];try{let n=JSON.parse(t);return Array.isArray(n.ids)?n.ids.filter(r=>typeof r=="string"&&r.length>0):[]}catch{return[]}}async function Hh(e,t){await L(Vh(e),`${JSON.stringify({ids:t})}
96
+ `)}async function Qd(e,t){let n=t.filter(i=>typeof i=="string"&&i.trim().length>0);if(n.length===0)return;let r=async()=>{let i=await eu(e),s=[...new Set([...i,...n])].sort((a,c)=>a.localeCompare(c));await Hh(e,s)};await Bh(e,async()=>(await r(),!0),!1)||await r()}async function bM(e){return Bh(e,async()=>{let t=await eu(e);return t.length>0&&await Hh(e,[]),t},[])}function wM(){return Ws.join(yt(import.meta.url,["../../.."]),"dist","cli","search-refresh.js")}function tu(e){try{let t=lM(process.execPath,[wM()],{detached:!0,stdio:"ignore",env:{...process.env,PM_PATH:e,[qh]:"1"}});t.on("error",()=>{}),t.unref()}catch{}}function EM(e){setTimeout(()=>tu(e),_M)}async function Wh(e,t){await Qd(e,t),tu(e)}async function k8(e,t,n=EM){let r=[],o=[];if(!await ee(e))return{processed:o,rounds:0,warnings:r};let i;try{let u=await Zt(e),f=u.warnings.find(p=>p.startsWith("settings_read_"));if(f)return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${f}`]};i=Sr(u.settings).settings}catch(u){return n(e),{processed:o,rounds:0,warnings:[`search_background_refresh_settings_read_failed:${q(u)}`]}}let s=null;try{s=await Te(e,zh,i.locks.ttl_seconds,wo(void 0,"pm-search-refresh"),!1,i.governance.force_required_for_stale_lock,i.locks.wait_ms)}catch{}if(!s)return{processed:o,rounds:0,warnings:r};let a=0,c=!1,l=!1;try{for(;;){let u=await bM(e);if(u.length===0)break;a+=1;try{let f=await t(e,u);if(r.push(...f.warnings),f.warnings.some(p=>p.startsWith("search_semantic_refresh_skipped:settings_read_failed:"))){await Qd(e,u),c=!0,l=!0;break}o.push(...f.refreshed)}catch(f){r.push(`search_background_refresh_failed:${q(f)}`),await Qd(e,u),c=!0;break}}}finally{await s?.()}return l&&n(e),(c?[]:await eu(e)).length>0&&tu(e),{processed:[...new Set(o)].sort((u,f)=>u.localeCompare(f)),rounds:a,warnings:r}}import Nn from"node:fs/promises";import Yh from"node:path";import{randomUUID as vM}from"node:crypto";import{createRequire as TM}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 kM="metadata-query-index.sqlite",$o="4";function AM(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Ks;function SM(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?AM(t):null}function jo(){return Ks!==void 0||(Ks=SM(process.versions.node,TM(import.meta.url))),Ks}function Kh(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function xr(e){return Yh.join(e,"runtime",kM)}function xM(e){e.exec(`
97
97
  PRAGMA foreign_keys = ON;
98
98
  PRAGMA journal_mode = OFF;
99
99
  PRAGMA synchronous = OFF;
@@ -148,7 +148,7 @@ ${a.join(`
148
148
  tags,
149
149
  tokenize = 'unicode61'
150
150
  );
151
- `)}function Js(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function Kh(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
151
+ `)}function Xs(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function Xh(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
152
152
  id, relative_path, metadata_json, status, type, priority,
153
153
  updated_at, created_at, parent, assignee, sprint, release
154
154
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -163,10 +163,10 @@ ${a.join(`
163
163
  parent = excluded.parent,
164
164
  assignee = excluded.assignee,
165
165
  sprint = excluded.sprint,
166
- 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 Yh(e){let t=Sr(e.pmRoot),n=jo();if(!n){await Nn.rm(t,{force:!0});return}await Nn.mkdir(Wh.dirname(t),{recursive:!0});let r=`${t}.${wM()}.tmp`,o;try{o=new n(r),AM(o),o.exec("BEGIN IMMEDIATE"),Js(o,"version",$o),Js(o,"context_fingerprint",e.contextFingerprint),Js(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Kh(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Nn.rm(t,{force:!0}),await Nn.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Nn.rm(r,{force:!0})]),i}}function Qs(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Xh(e){let t=Sr(e.pmRoot),n;try{await Nn.access(t);let r=jo();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Qs(n);if(o.version!==$o||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 l=s.get(c);i.run(c),l&&a.run(l.id)}return e.row&&Kh(n,e.row),Js(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}function Xs(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function SM(e){let t=[],n=[];Xs(t,n,"status",e.statuses,"IN"),Xs(t,n,"status",e.excludeStatuses,"NOT IN"),Xs(t,n,"type",e.types,"IN"),Xs(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 xM(e){let t=jo();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=SM(n),i;try{i=new t(Sr(e.pmRoot),{readOnly:!0});let s=Qs(i);if(s.version!==$o||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],l="";n.limit!==void 0?(l+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(l+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(l+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let u=i.prepare(`SELECT metadata_json FROM items${r}
167
- 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${l}`).all(...o,...n.terminalStatuses??[],...c).map(f=>{let p=JSON.parse(String(f.metadata_json));if(!p.id)throw new TypeError("Indexed metadata row has no id");return p});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:u}}catch{return i?.close(),null}}async function CM(e){let t=jo();if(!t||e.paths.length===0)return null;let n;try{n=new t(Sr(e.pmRoot),{readOnly:!0});let r=Qs(n);if(r.version!==$o||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
166
+ 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 Jh(e){let t=xr(e.pmRoot),n=jo();if(!n){await Nn.rm(t,{force:!0});return}await Nn.mkdir(Yh.dirname(t),{recursive:!0});let r=`${t}.${vM()}.tmp`,o;try{o=new n(r),xM(o),o.exec("BEGIN IMMEDIATE"),Xs(o,"version",$o),Xs(o,"context_fingerprint",e.contextFingerprint),Xs(o,"source_cursor",e.sourceCursor);for(let i of e.rows)Xh(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Nn.rm(t,{force:!0}),await Nn.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Nn.rm(r,{force:!0})]),i}}function Js(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function Qh(e){let t=xr(e.pmRoot),n;try{await Nn.access(t);let r=jo();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Js(n);if(o.version!==$o||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 l=s.get(c);i.run(c),l&&a.run(l.id)}return e.row&&Xh(n,e.row),Xs(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}function Ys(e,t,n,r,o){!r||r.length===0||(e.push(`${n} ${o} (${r.map(()=>"?").join(", ")})`),t.push(...r))}function CM(e){let t=[],n=[];Ys(t,n,"status",e.statuses,"IN"),Ys(t,n,"status",e.excludeStatuses,"NOT IN"),Ys(t,n,"type",e.types,"IN"),Ys(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 OM(e){let t=jo();if(!t)return null;let n=e.query??{},{where:r,parameters:o}=CM(n),i;try{i=new t(xr(e.pmRoot),{readOnly:!0});let s=Js(i);if(s.version!==$o||s.source_cursor!==e.expectedSourceCursor)return i.close(),null;let a=i.prepare(`SELECT COUNT(*) AS count FROM items${r}`).get(...o),c=[],l="";n.limit!==void 0?(l+=" LIMIT ?",c.push(Math.max(0,Math.floor(n.limit))),n.offset!==void 0&&(l+=" OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))))):n.offset!==void 0&&(l+=" LIMIT -1 OFFSET ?",c.push(Math.max(0,Math.floor(n.offset))));let u=i.prepare(`SELECT metadata_json FROM items${r}
167
+ 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${l}`).all(...o,...n.terminalStatuses??[],...c).map(f=>{let p=JSON.parse(String(f.metadata_json));if(!p.id)throw new TypeError("Indexed metadata row has no id");return p});return i.close(),{source_cursor:s.source_cursor,total:Number(a.count),items:u}}catch{return i?.close(),null}}async function IM(e){let t=jo();if(!t||e.paths.length===0)return null;let n;try{n=new t(xr(e.pmRoot),{readOnly:!0});let r=Js(n);if(r.version!==$o||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
168
168
  FROM item_linked_files
169
- WHERE ${a}`).get(...s),l=Hh(e.limit,50),d=Hh(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
169
+ WHERE ${a}`).get(...s),l=Kh(e.limit,50),d=Kh(e.offset,0),u=n.prepare(`SELECT items.id, items.metadata_json
170
170
  FROM items
171
171
  WHERE EXISTS (
172
172
  SELECT 1 FROM item_linked_files
@@ -177,29 +177,29 @@ ${a.join(`
177
177
  FROM item_linked_files
178
178
  WHERE item_id IN (${p.map(()=>"?").join(", ")})
179
179
  AND ${a}
180
- ORDER BY path ASC, scope ASC`).all(...p,...s),y=new Map(p.map(b=>[b,[]]));for(let b of _){let E=String(b.item_id),T=y.get(E);T.push({path:String(b.path),scope:String(b.scope),...b.note===null?{}:{note:String(b.note)}}),y.set(E,T)}for(let b of u){let E=JSON.parse(String(b.metadata_json));f.push({item:E,files:y.get(String(b.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:f}}catch{return n?.close(),null}}async function OM(e){let t=jo();if(!t)return null;let n;try{n=new t(Sr(e.pmRoot),{readOnly:!0});let r=Qs(n);if(r.version!==$o||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let i=n.prepare(`SELECT items.metadata_json
180
+ ORDER BY path ASC, scope ASC`).all(...p,...s),y=new Map(p.map(b=>[b,[]]));for(let b of _){let E=String(b.item_id),T=y.get(E);T.push({path:String(b.path),scope:String(b.scope),...b.note===null?{}:{note:String(b.note)}}),y.set(E,T)}for(let b of u){let E=JSON.parse(String(b.metadata_json));f.push({item:E,files:y.get(String(b.id))})}}return n.close(),{source_cursor:r.source_cursor,total:Number(c.count),matches:f}}catch{return n?.close(),null}}async function RM(e){let t=jo();if(!t)return null;let n;try{n=new t(xr(e.pmRoot),{readOnly:!0});let r=Js(n);if(r.version!==$o||r.source_cursor!==e.expectedSourceCursor)return n.close(),null;let i=n.prepare(`SELECT items.metadata_json
181
181
  FROM item_search
182
182
  JOIN items ON items.id = item_search.id
183
183
  WHERE item_search MATCH ?
184
184
  ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
185
- 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 Zs(e){await Nn.rm(Sr(e),{force:!0})}import me from"node:fs/promises";import Z from"node:path";import{createHash as IM,randomUUID as tb}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]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var st=8,ru=500,RM="metadata-derived-index",NM="metadata-cache.json",DM="metadata-cache-bodies.json",PM="metadata-cache-collections.json",LM="metadata-cache-delta.json",MM="metadata-cache-manifest.json",Jh=4,FM=["comments","notes","learnings","files","tests","test_runs","docs"];function nb(){return lo(Pt())}function ta(e){let t={...e},n={};for(let r of FM)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function rb(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function ob(e,t,n,r){let o=IM("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 na(e){return Z.join(e,"runtime",NM)}function ra(e){return Z.join(e,"runtime",DM)}function oa(e){return Z.join(e,"runtime",PM)}function ou(e){return Z.join(e,"runtime",LM)}function iu(e){return Z.join(e,"runtime",MM)}function ia(e,t){let n=Z.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var $M=24,ze=new Map,sa=new WeakMap;function su(e){return sa.get(e)??e.source_cursor}function jM(e,t){let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){sa.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 UM(e,t){if(!e)return;let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){sa.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 zM(e,t){if(!e)return;let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){sa.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 qM(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(jM(e,r),UM(t,r),zM(n,r))}function nu(e,t){ze.size>=$M&&!ze.has(e)&&Wn(ze),ze.set(e,t)}async function Xt(e,t){let n;try{n=await me.stat(e)}catch{return ze.delete(e),null}let r=ze.get(e);if(r&&Uo(r.signature,n.mtimeMs,n.ctimeMs,n.size))return ze.delete(e),ze.set(e,r),r.envelope;let o;try{o=t(await me.readFile(e,"utf8"))}catch{o=null}return nu(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function VM(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==st||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=na(e),i=await Xt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await Xt(ia(o,t),r);return s===null&&Vo(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function GM(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==st||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=ra(e),o=await Xt(r,n);return t&&o?.context_fingerprint!==t?await Xt(ia(r,t),n):o}async function BM(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==st||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=oa(e),o=await Xt(r,n);return t&&o?.context_fingerprint!==t?await Xt(ia(r,t),n):o}async function au(e){let t=ou(e),n=await Xt(t,r=>{let o=JSON.parse(r);return o.version!==st||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 me.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function cu(e){let t=iu(e),n=await Xt(t,r=>{let o=JSON.parse(r);return o.version!==st||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 me.stat(t),await xr(e)}catch{}return null}async function zo(e,t){await me.mkdir(Z.dirname(e),{recursive:!0}),await P(e,JSON.stringify(t));try{let r=await me.stat(e);nu(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{ze.delete(e)}let n=Z.dirname(Z.dirname(e));if(e===na(n)||e===ra(n)||e===oa(n)){let r=ia(e,t.context_fingerprint);await P(r,JSON.stringify(t));try{let c=await me.stat(r);nu(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{ze.delete(r)}let o=Z.dirname(e),i=Z.extname(e),s=Z.basename(e,i),a=(await me.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==Z.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>Z.join(o,c.name));if(a.length>Jh){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await me.stat(l)).mtimeMs}}catch{return null}}))).filter(l=>l!==null);for(let l of c.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,c.length-Jh)))await me.rm(l.path,{force:!0}),ze.delete(l.path)}}}function HM(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ib(e,t,n){return e===void 0||HM(e,t,n)}function Vo(e,t){e&&!e.includes(t)&&e.push(t)}function Uo(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function WM(e,t,n){let r=Z.join(e,t);try{let o=await me.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!de(o)&&Vo(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function KM(e,t){try{let n=await me.stat(Z.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 ea(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await KM(e,n))))}function qo(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&&Uo(o,r.mtime_ms,r.ctime_ms,r.size)})}function YM(e){return Ci.some(t=>e.toLowerCase().endsWith(t))}function XM(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function JM(e,t,n){if(n)for(let r of await He({path:e,scope:"project"}))Vo(t,r)}function Qh(e,t,n,r){if(e)return t&&n?n.collections:r}async function QM(e,t,n){let r=await me.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Hr(e);await JM(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Uo(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Uo(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&Uo(f,o,i,s);if(!(!l||n.includeBody&&!u||n.includeCollections&&!p))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:Qh(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let y=await me.readFile(e,"utf8"),b=bn(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:T=>Vo(n.warnings,T)}),E=ta(b.metadata);return XM(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:E.light,heavyMetadata:Qh(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function ZM(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?rb(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};ib(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function eF(e,t,n,r){try{let o=await QM(t,n,r);ZM(t,n,r,o)}catch{Vo(r.warnings,`item_list_item_read_failed:${e}/${Z.basename(t)}`)}}function tF(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function nF(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function rF(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function oF(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function iF(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!YM(s))continue;let a=Z.join(o,s),c=Z.relative(t.pmRoot,a);n.push(eF(r,a,c,t))}return n}async function sF(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!qo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await zo(na(e.pmRoot),{version:st,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await zo(iu(e.pmRoot),{version:st,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:Z.relative(e.pmRoot,r.item_path),metadata:ta(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Yh({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Zs(e.pmRoot)}catch{}}async function aF(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 zo(ra(e.pmRoot),{version:st,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function cF(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 zo(oa(e.pmRoot),{version:st,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function aa(e,t,n={}){let r=await cu(e);return n.required!==!0&&(r===null||r.entry_count<ru)?async()=>{}:ke(e,RM,30,t,!1,!1,3e3)}async function lF(e,t){let n=await cu(e);if(n===null)return null;let r=await au(e);if(r.invalid)return await xr(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&&!qo(i,await ea(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function Zh(e,t){let n=Z.relative(e,t);return n===""||n===".."||n.startsWith(`..${Z.sep}`)||Z.isAbsolute(n)?null:n}async function xr(e){await Promise.all([na(e),ra(e),oa(e),ou(e),iu(e)].map(async t=>{await me.rm(t,{force:!0}),ze.delete(t)})),await Zs(e)}async function dF(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await me.stat(e.mutation.itemPath),n=ta(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 uF(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function ca(e){let t=Zh(e.pmRoot,e.itemPath),n=e.previousItemPath?Zh(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await xr(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=ob(e.preferredFormat,e.typeToFolder,e.schema,nb()),o=await cu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await au(e.pmRoot);if(s.invalid)return await xr(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=uF(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 dF({mutation:e});let l=tb();return await zo(ou(e.pmRoot),{version:st,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await ea(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Xh({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:ta(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Zs(e.pmRoot),[]}catch{return await xr(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function fF(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function eb(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function pF(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function mF(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Hr(n);if(!o)continue;let i=e.includeCollections?rb(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ib(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:Z.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function _F(e){return e.forceSourceScan||el()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!qo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||eb(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||eb(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&pF(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Go(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=nb(),l=ob(t,n,o,c),d=await au(e);d.invalid&&await xr(e);let u=await VM(e,l,i.cacheDiagnostics),f=s?await GM(e,l):null,p=a?await BM(e,l):null;qM(u,f,p,d.envelope);let _=tF(u,l),y=nF(f,l),b=rF(p,l),E=[...new Set(Object.values(n))],T=await ea(e,E),O=Object.keys(_),M=Math.max(1,Math.floor(i.derivedIndexMinimumItems??ru));if(_F({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:T,entryKeys:O,minimumIndexedItems:M,includeBody:s,includeCollections:a,previousBodies:y,previousCollections:b}))return mF({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:y,previousCollections:b});let W=await Promise.all(E.map(Zv=>WM(e,Zv,r))),Ee=el(),le=oF(),tn={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:Ee,previousEntries:_,previousBodies:y,previousCollections:b,state:le};await Promise.all(iF(W,tn));let nn=await ea(e,E),Fr=qo(T,nn)?nn:{},Xa=le.misses.metadata||Object.keys(_).length!==Object.keys(le.newEntries).length||!qo(u?.directory_signatures,Fr)||u===null?tb():u.source_cursor;return await sF({pmRoot:e,contextFingerprint:l,sourceCursor:Xa,existingCache:u,previousEntries:_,directorySignatures:Fr,state:le,minimumIndexedItems:M}),s&&await aF({pmRoot:e,contextFingerprint:l,sourceCursor:Xa,existingBodyCache:f,previousBodies:y,state:le}),a&&await cF({pmRoot:e,contextFingerprint:l,sourceCursor:Xa,existingCollectionsCache:p,previousCollections:b,state:le}),fF(le)}async function sb(e,t,n,r,o){return(await Go(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}async function ab(e,t,n,r,o){return(await Go(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}import du from"node:fs/promises";import la 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]="8b0efe32-43f5-51ed-b1d5-5c26a3ae5bf0")}catch{}})();function Jt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function uu(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:`pm ${t.map(n=>`'${n.replaceAll("'",`'"'"'`)}'`).join(" ")}`,suggested_retry_args:t}}function da(e){return new h(`Tracker root is not a directory at ${e}.`,g.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function lu(e){return new h(`Tracker root is not readable at ${e}.`,g.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function gF(e){let t=la.resolve(e),n=la.parse(t).root,r=la.dirname(t);for(;r!==n;){let o;try{o=await du.stat(r)}catch(i){if(Jt(i,"ENOTDIR"))throw da(e);if(!Jt(i,"ENOENT"))throw i;r=la.dirname(r);continue}if(!o.isDirectory())throw da(e);return}}async function Cr(e){let t;try{t=await du.stat(e)}catch(n){throw Jt(n,"ENOENT")?(await gF(e),new h(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,g.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:uu(e)})):Jt(n,"ENOTDIR")?da(e):Jt(n,"EACCES")||Jt(n,"EPERM")?lu(e):n}if(!t.isDirectory())throw da(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw lu(e);try{await(await du.opendir(e)).close()}catch(n){throw Jt(n,"EACCES")||Jt(n,"EPERM")?lu(e):n}}async function yF(e){if(await Cr(e),!await ee(ge(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:uu(e)})}import Or from"node:fs/promises";import hF 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]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function bF(e){try{return await Or.access(e),!0}catch{return!1}}function wF(e,t){e&&(e.includes(t)||e.push(t))}function cb(e){return e??lo(Pt())}function EF(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Bo(e,t,n="pm-",r,o=_e){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=In(t,n),c=Us(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=EF(r);for(let f of l)for(let[p]of d)for(let _ of u){let y=Qn(e,p,f,_,o);if(await bF(y))return{id:f,type:p,itemPath:y,item_format:_}}return null}async function Ho(e,t={}){let n=await Or.readFile(e.itemPath,"utf8");await He({path:e.itemPath,scope:"project"});let r=bn(n,{format:e.item_format,schema:t.schema,extensionFieldNames:cb(t.extensionFieldNames),onWarning:o=>wF(t.warnings,o)});return{raw:n,document:r}}async function lb(e,t,n=_e,r,o){return await Cr(e),(await sb(e,t,n,r,o)).map(s=>s.metadata)}async function vF(e,t,n=_e,r,o){return await Cr(e),(await ab(e,t,n,r,o)).map(s=>s.metadata)}async function p3(e,t,n=_e,r,o,i={}){return await Cr(e),(await Go(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function fu(e){return{async get(t){let n=await Bo(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Ho(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>lb(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function TF(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await Or.readdir(hF.join(e,o));for(let s of i)for(let a of Ci)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function kF(e,t,n,r){let o=In(t,n),i=await TF(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Be(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function db(e,t,n,r){let o=await kF(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 h(`Item ${t} not found`,g.NOT_FOUND,{nextSteps:i})}function AF(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 ub(e){let t=e.typeToFolder??Vr(e.settings,Pt()).type_to_folder,n=await Bo(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await db(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await ke(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 Ho(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=Vl(e.author),d=Ws(e.settings);if(a&&c!==l&&!e.force&&!AF(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new h(`Item ${n.id} is assigned to ${a}. Use --force to override.`,g.CONFLICT);d.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 SF(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 xF(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await P(e.originalItemPath,e.originalRaw),await Or.rm(e.effectiveTargetItemPath,{force:!0});return}await P(e.originalItemPath,e.originalRaw)}}async function pu(e){let t=await ub({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=je(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=je(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=await e.mutate(l);if(e.skipNoop===!0&&d.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...d.warnings??[]]};let u=e.resolveHistoryContext?.();l.metadata.updated_at=oe();let f=je(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Yi({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:fu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await js({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",y=ho(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=Qn(e.pmRoot,f.metadata.type,r.id,_,n),E=Zn(e.pmRoot,r.id),T=await $e("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:b,history_path:E,item_format:_,before:c,after:f,contents:y}),{effectiveTargetItemPath:O,effectiveSerializedAfter:M,skipItemWrite:W}=SF(T,b,y),Ee=await aa(e.pmRoot,e.author),le=[];try{W||await P(O,M),!W&&O!==r.itemPath&&await Or.rm(r.itemPath);let nn=vt({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await Tt(E,nn)}catch(Fr){throw await xF({skipItemWrite:W,effectiveTargetItemPath:O,originalItemPath:r.itemPath,originalRaw:o}),Fr}W||(le=await ca({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:O,previousItemPath:r.itemPath,document:f}))}finally{await Ee()}let tn=[...await ye({path:O,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await ye({path:E,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields})];return Ki({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:co(c.metadata,d.changedFields),current:co(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...T.warnings,...le,...tn]}}finally{await a()}}async function CF(e){let{historyContext:t,...n}=e;return pu({...n,resolveHistoryContext:()=>t})}async function m3(e){return pu(e)}async function OF(e){return pu(e)}async function IF(e){let t=await ub({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=cb(void 0),c=je(o,{schema:e.settings.schema,extensionFieldNames:a});await Yi({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:fu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let l=await js({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),d=oe(),u=Bn,f=vt({nowIso:d,author:e.author,op:"delete",before:c,after:u,message:e.message}),p=Zn(e.pmRoot,n.id),_=await $e("item_store_delete",{op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:p,before:c}),y=n.itemPath,b=!1;if(_.handled&&typeof _.result=="object"&&_.result!==null){let M=_.result;typeof M.item_path=="string"&&M.item_path.trim().length>0&&(y=M.item_path),M.skip_delete===!0&&(b=!0)}if(e.dryRun===!0)return{item:c.metadata,changedFields:["deleted"],targetPath:y,warnings:[...i,...l.warnings,..._.warnings]};let E=await aa(e.pmRoot,e.author),T=[];try{b||await Or.rm(y);try{await Tt(p,f)}catch(M){throw b||await P(y,r),M}b||(T=await ca({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:y,document:null}))}finally{await E()}let O=[...await ye({path:y,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:u,changed_fields:["deleted"]}),...await ye({path:p,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:u,changed_fields:["deleted"]})];return Ki({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:co(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,..._.warnings,...T,...O]}}finally{await 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]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();var RF=3e4;function Dn(e,t,n=RF){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Pn(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function NF(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${z(t)})`}}async function ua(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${z(o)}`)}if(!r.ok){let o=await NF(r),i=o.length>0?`: ${o}`:"";throw new Error(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${z(o)}`)}}finally{clearTimeout(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]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();function w3(e,t){let n=F(e);if(!n)return"unconfigured";let r=F(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function DF(e){let t=jr(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function pb(e){let t=e.search?.embedding_model;return F(t)||null}function PF(e){let t=F(e.providers?.openai?.base_url),n=F(e.providers?.openai?.model);if(!t||!n)return null;let r=pb(e),o=F(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function LF(e){let t=F(e.providers?.ollama?.base_url),n=F(e.providers?.ollama?.model);if(!t||!n)return null;let r=pb(e);return{name:"ollama",base_url:t,model:r??n}}function mb(e){let t=(Array.isArray(e)?e:[e]).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function MF(e){let t=[],n=[],r=new Map;for(let o of e){let i=r.get(o);if(i===void 0){let s=t.length;t.push(o),r.set(o,s),n.push(s);continue}n.push(i)}return{uniqueInputs:t,originalToUniqueIndex:n}}function FF(e){let t=e.map((r,o)=>({embedding:r.embedding,index:r.index,position:o}));if(t.some(r=>r.index!==void 0)){for(let r of t)if(!Number.isInteger(r.index))throw new TypeError(`OpenAI embedding response entry at position ${r.position} is missing a valid integer index`);return[...t].sort((r,o)=>{let i=r.index-o.index;return i!==0?i:r.position-o.position})}return t}function fa(e){let t=PF(e),n=LF(e),r=[t,n].filter(a=>a!==null),o=F(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(a=>a.name===i):void 0)??r[0]??null,available:r}}function fb(e){let t=jr(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:DF(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function $F(e,t){let n=mb(t);return e.name==="openai"?{target:fb(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:n.length===1?n[0]:n}}:{target:fb(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function jF(e,t){if(e.name==="openai"){let o=t.data;if(!Array.isArray(o)||o.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return FF(o).map((s,a)=>{let c=s.embedding;if(!Hn(c))throw new Error(`OpenAI embedding response entry at index ${a} is missing a numeric embedding vector`);return[...c]})}let n=t.embedding;if(Hn(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Hn(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function _b(e,t,n={}){let r=Dn(n.timeout_ms,"Embedding request"),o=Pn(n.fetcher,"Embedding request"),i=mb(t),s=MF(i),a=$F(e,s.uniqueInputs),c=await ua({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),l=jF(e,c);if(l.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${l.length}`);return s.originalToUniqueIndex.map(d=>[...l[d]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();var pa=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function mu(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...pa];let n=new Set(pa),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...pa]}var UF=8e3,_u=3200,Ln="...[semantic corpus truncated]",zF="search_embedding_corpus_max_characters_invalid:using_provider_default";function ct(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function qF(e){return(e.reminders??[]).map(t=>ct([t.at,t.text]))}function VF(e){return(e.events??[]).map(t=>ct([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function GF(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let n of t.linked_items??[])e.push(`${n.kind} ${n.id}`,n.note);for(let n of t.files??[])e.push(n.path,n.note);for(let n of t.tests??[])e.push(n.command,n.path,n.note);for(let n of t.docs??[])e.push(n.path,n.note)}function BF(e,t){for(let n of t.plan_decisions??[])e.push(n.decision,n.rationale,n.evidence);for(let n of t.plan_discoveries??[])e.push(n.text);for(let n of t.plan_validation??[])e.push(n.text,n.command,n.expected)}function T3(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let n of e.plan_steps??[])GF(t,n);return BF(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function HF(e){let t=(e.plan_steps??[]).map(s=>ct([s.order,s.id,s.title,s.body,s.status,s.owner,s.evidence,s.blocked_reason,s.superseded_by,(s.linked_items??[]).map(a=>ct([a.kind,a.id,a.note])).join(" "),(s.files??[]).map(a=>ct([a.path,a.note])).join(" "),(s.tests??[]).map(a=>ct([a.command,a.path,a.note])).join(" "),(s.docs??[]).map(a=>ct([a.path,a.note])).join(" ")])),n=(e.plan_decisions??[]).map(s=>ct([s.decision,s.rationale,s.evidence,s.step_id])),r=(e.plan_discoveries??[]).map(s=>ct([s.text,s.step_id])),o=(e.plan_validation??[]).map(s=>ct([s.text,s.command,s.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(s=>s!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function at(e){return typeof e=="string"&&e.trim().length>0}var WF={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>at(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>at(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>at(e.metadata.goal)?e.metadata.goal:void 0,value:e=>at(e.metadata.value)?e.metadata.value:void 0,why_now:e=>at(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>at(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>at(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>at(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>at(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>at(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>(e.metadata.comments??[]).map(t=>t.text),notes:e=>(e.metadata.notes??[]).map(t=>t.text),learnings:e=>(e.metadata.learnings??[]).map(t=>t.text),reminders:e=>qF(e.metadata),events:e=>VF(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>HF(e.metadata)};function gb(e,t={}){let n=t.fields??pa,r={};for(let o of n){let i=WF[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function KF(e){return e?.trim().toLowerCase()==="ollama"?_u:UF}function Ir(e,t){let n=KF(e),r=Xf(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:zF}}function gu(e,t={}){let n=JSON.stringify(gb(e,{fields:t.fields})),r=Ir(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=Ln.length)return Ln.slice(0,r);let o=Math.max(0,r-Ln.length);return`${n.slice(0,o)}${Ln}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();function YF(e,t){let n=e.search.embedding_batch_size,r=e.search.embedding_timeout_ms,o=e.search.scanner_max_batch_retries,i=Number.isFinite(n)&&n>0?Math.floor(n):1,s=Number.isFinite(r)&&r>0?Math.floor(r):3e4,a=Number.isFinite(o)&&o>=0?Math.floor(o):0;return{batchSize:i,timeoutMs:s,maxRetries:a,maxBatchInputCharacters:Number.POSITIVE_INFINITY,maxInputCharacters:t}}function XF(e,t,n){let r=[],o=[],i=0;for(let s of e){let a=o.length>=t,c=o.length>0&&Number.isFinite(n)&&i+s.length>n;(a||c)&&(r.push(o),o=[],i=0),o.push(s),i+=s.length}return r.push(o),r}function JF(e,t){return e.name!=="ollama"?t:{...t,maxBatchInputCharacters:_u}}function QF(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-Ln.length);return`${e.slice(0,n)}${Ln}`.slice(0,t)}function yb(e){let t=z(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function ZF(e,t,n,r,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${z(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${n} timeout_ms=${r}`;return yb(i)?`${s} (${a}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`:`${s} (${a})`}async function yu(e,t,n,r,o,i){let s=null;for(let a=0;a<=o;a+=1)try{let c=await _b(e,t,{timeout_ms:r});return a>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${n}:attempt=${a+1}:size=${t.length}`),c}catch(c){if(s=c,yb(c)&&t.length>1){let l=Math.ceil(t.length/2),d=t.slice(0,l),u=t.slice(l);return i.push(`search_embedding_batch_split_after_timeout:batch=${n}:size=${t.length}:parts=${d.length}|${u.length}`),[...await yu(e,d,`${n}.1`,r,o,i),...await yu(e,u,`${n}.2`,r,o,i)]}if(a<o){let l=Math.min(1e3*2**a,8e3);await new Promise(d=>setTimeout(d,l))}}throw new Error(ZF(e,n,t.length,r,o+1,s))}async function hu(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=[],i=Ir(e.name,t.search.embedding_corpus_max_characters);i.warning&&o.push(i.warning);let s=JF(e,YF(t,i.maxCharacters)),a=0,c=n.map(f=>{let p=QF(f,s.maxInputCharacters);return p.length<f.length&&(a+=1),p});a>0&&o.push(`search_embedding_input_truncated:count=${a}:max_characters=${s.maxInputCharacters}`);let l=XF(c,s.batchSize,s.maxBatchInputCharacters),d=[],u=0;for(let f=0;f<l.length;f+=1){let p=l[f];r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"start"}),d.push(...await yu(e,p,String(f+1),s.timeoutMs,s.maxRetries,o)),u+=p.length,r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"complete"})}return{vectors:d,warnings:o}}import{mkdir as e$,readFile as t$,stat as Eu,unlink as n$}from"node:fs/promises";import{basename as hb,dirname as bu,isAbsolute as r$,join as o$,resolve as vu}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]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}catch{}})();var Tu="pm_items",i$=/[^a-zA-Z0-9_-]/g,s$=128,a$=".pm-cli-local-vectors",wu=1,Mn=new Map;function Ko(e){return(F(e.collection_name)??Tu).replaceAll(i$,"_").slice(0,s$)}function ma(e){if(!Hn(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function wb(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function c$(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let n=t.map((r,o)=>{let i=r.id,s=typeof i=="number"?String(i):i,a=F(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=r.score;if(typeof c!="number"||!Number.isFinite(c))throw new TypeError(`Qdrant query response entry at index ${o} is missing a finite numeric score`);let l=r.payload;if(l!==void 0&&(typeof l!="object"||l===null||Array.isArray(l)))throw new Error(`Qdrant query response entry at index ${o} must provide payload as an object when set`);return{id:a,score:c,...l?{payload:l}:{}}});return n.sort((r,o)=>r.score!==o.score?o.score-r.score:r.id.localeCompare(o.id)),n}function ku(e){let t=F(e.result?.status);if(t)return{status:t};let n=F(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function Wo(e,t,n,r,o){return await ua({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function l$(e){let t=F(e.vector_store?.qdrant?.url);if(!t)return null;let n=F(e.vector_store?.collection_name),r=F(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Tu?{collection_name:n}:{},...r?{api_key:r}:{}}}function d$(e){let t=vu(e),n=bu(t);return hb(t)==="pm"&&hb(n)===".agents"?bu(n):t}function u$(e,t){return!t||r$(e)?e:vu(d$(t),e)}function f$(e,t){let n=F(e.vector_store?.lancedb?.path);if(!n)return null;let r=F(e.vector_store?.collection_name);return{name:"lancedb",path:u$(n,t),...r&&r!==Tu?{collection_name:r}:{}}}function p$(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=F(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=ma(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function m$(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=F(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function _$(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function g$(e){return e.replace(/\/points\?wait=true$/,"")}function _a(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function ga(e,t){return Rr(e,t)}function Rr(e,t){return o$(vu(e),a$,`${t}.json`)}function y$(e,t,n){let r=F(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=ma(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function h$(e,t,n){let r;try{r=JSON.parse(n)}catch(c){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${z(c)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==wu)throw new Error(`LanceDB local snapshot at '${e}' must include version=${wu}`);let i=F(r.table);if(!i)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(i!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${i}'`);let s=r.records;if(!Array.isArray(s))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let a=new Map;for(let c=0;c<s.length;c+=1){let l=y$(s[c],c,e);a.set(l.id,l)}return a}async function b$(e){try{let t=await Eu(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!de(t))throw t;return null}}function w$(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Mn.set(e,{records:n,mtimeMs:null,size:null}),n}function E$(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Au(e,t){let n=ga(e,t),r=Rr(e,t),o=await b$(r),i=Mn.get(n);if(!o){let a=w$(n,i);if(a)return a}if(E$(i,o))return i.records;let s=new Map;try{let a=await t$(r,"utf8");s=h$(r,t,a)}catch(a){if(!de(a))throw a}return Mn.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function v$(e){let t=[...e.values()];return t.sort((n,r)=>n.id.localeCompare(r.id)),t.map(n=>({id:n.id,vector:[...n.vector],...n.payload?{payload:n.payload}:{}}))}async function Eb(e){try{await n$(e)}catch(t){if(!de(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${z(t)}`)}}async function vb(e,t,n){let r=Rr(e,t);if(n.size===0){await Eb(r);return}let o=bu(r);try{await e$(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${z(s)}`)}let i=`${JSON.stringify({version:wu,table:t,records:v$(n)})}
186
- `;try{await P(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${z(s)}`)}}async function T$(e,t){let n=ga(e,t),r=Rr(e,t);await Eb(r),Mn.delete(n)}function bb(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function k$(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=bb(e),o=bb(t);return r===0||o===0?0:n/(r*o)}function ya(e,t){let n=l$(e),r=f$(e,t),o=[n,r].filter(c=>c!==null),i=F(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(c=>c.name===s):void 0)??o[0]??null,available:o}}function ha(e){let t=Ko(e);if(e.name==="qdrant"){let o=jr(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function A$(e,t,n){let r=ha(e),o=ma(t),i=wb(n);return e.name==="qdrant"?{target:r,method:"POST",headers:_a(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:Ko(e),vector:o,limit:i}}}function S$(e,t){let n=ha(e),r=p$(t);return e.name==="qdrant"?{target:n,method:"POST",headers:_a(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ko(e),records:r}}}function x$(e,t){let n=ha(e),r=m$(t);return e.name==="qdrant"?{target:n,method:"POST",headers:_a(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ko(e),ids:r}}}async function P3(e,t,n,r={}){let o=A$(e,t,n);if(o.method==="LOCAL"){let c=e,l=o.body,d=await Au(c.path,l.table);if(d.size===0)return[];let u=ma(l.vector),f=wb(l.limit),p=[],_=0;for(let y of d.values()){if(y.vector.length!==u.length){_++;continue}p.push({id:y.id,score:k$(u,y.vector),...y.payload?{payload:y.payload}:{}})}return _>0&&r.warnings&&r.warnings.push(`vector_dimension_mismatch:${_} records skipped (expected ${u.length} dimensions)`),p.sort((y,b)=>y.score!==b.score?b.score-y.score:y.id.localeCompare(b.id)),p.slice(0,f)}let i=Dn(r.timeout_ms,"Vector request"),s=Pn(r.fetcher,"Vector request"),a=await Wo(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return c$(a)}async function Su(e,t,n={}){let r=S$(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=ga(a.path,c.table),d=await Au(a.path,c.table);for(let p of c.records)d.set(p.id,p);await vb(a.path,c.table,d);let u=Rr(a.path,c.table),f=await Eu(u);return Mn.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=Dn(n.timeout_ms,"Vector request"),i=Pn(n.fetcher,"Vector request"),s=await Wo(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return ku(s)}async function ba(e,t,n={}){let r=x$(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=ga(a.path,c.table),d=await Au(a.path,c.table);if(d.size===0)return{status:"ok"};for(let u of c.ids)d.delete(u);if(await vb(a.path,c.table,d),d.size===0)Mn.delete(l);else{let u=Rr(a.path,c.table),f=await Eu(u);Mn.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=Dn(n.timeout_ms,"Vector request"),i=Pn(n.fetcher,"Vector request"),s=await Wo(_$(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return ku(s)}async function Tb(e,t=[],n={},r){if(e.name==="lancedb")return await T$(e.path,Ko(e)),{status:"ok"};if(r!==void 0){if(!Number.isInteger(r)||r<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=ha(e),s=g$(i.upsert_target),a=Dn(n.timeout_ms,"Vector request"),c=Pn(n.fetcher,"Vector request"),l=_a(e);try{await Wo(s,{method:"DELETE",headers:l,body:{}},a,c,"delete")}catch(u){if(!z(u).includes("failed with status 404"))throw u}let d=await Wo(s,{method:"PUT",headers:l,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return ku(d)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await ba(e,o,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}catch{}})();function wa(e,t){let n=F(e),r=F(t);return!n||!r?null:{provider:n,model:r}}function kb(e){if(e==null)return null;if(typeof e!="object"||Array.isArray(e))throw new Error("Vectorization embedding metadata must be an object when set");let t=wa(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function xu(e,t){if(!Number.isInteger(t)||t<=0)throw new Error("Vectorization embedding metadata requires a positive vector dimension");return{provider:e.provider,model:e.model,vector_dimension:t}}function Cu(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Ou(e,t){return!!(e&&e.vector_dimension!==t)}function Iu(e,t){if(e.length===0)throw new Error(`${t} returned no vectors`);let r=e[0].length;if(!Number.isInteger(r)||r<=0)throw new Error(`${t} returned an empty vector`);for(let o=1;o<e.length;o+=1)if(e[o]?.length!==r)throw new Error(`${t} returned mixed vector dimensions`);return r}import Ru 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]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();var C$=["index/manifest.json","search/embeddings.jsonl"],Sb="search/vectorization-status.json";function O$(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Nr(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function xb(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function Cb(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!xb(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Ob(e){let t=Ru.join(e,Sb),n=await Y(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.items){if(typeof s!="object"||s===null)return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let a=s.id,c=s.updated_at;if(typeof a!="string"||a.trim().length===0||!xb(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=kb(r.embedding)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}return{entries:Object.fromEntries([...o.entries()].sort((s,a)=>s[0].localeCompare(a[0]))),embedding:i,warnings:[]}}async function Ib(e,t,n){let r=Cb(t),o=Ru.join(e,Sb),i=`${JSON.stringify({version:1,generated_at:oe(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
187
- `;await P(o,i)}function I$(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function R$(e){let t=wa(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function Yo(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function N$(e,t,n){if(!n.settings&&!await ee(ge(e)))return Yo(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await Yt(e),c=a.warnings.find(l=>l.startsWith("settings_read_"));if(c)return Yo(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return Yo(t,`search_semantic_refresh_skipped:settings_read_failed:${z(a)}`)}let o=n.apply_runtime_defaults?Ar(r).settings:r,i=fa(o).active;if(!i)return Yo(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=ya(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:Yo(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function D$(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,l=[];for(let d of r){let u=await Bo(e,d,t,n,o);if(!u){c.add(d);continue}try{let f=await Ho(u,{schema:i});l.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${z(f)}`)}}return l.sort((d,u)=>d.id.localeCompare(u.id)),{documents:l,missingIds:Nr(c),skippedIds:Nr(a),warnings:s}}async function P$(e,t,n){let r=Ir(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=mu(e),i=n.map(a=>gu(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await hu(t,e,i);return{vectors:s.vectors,vector_dimension:Iu(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function L$(e,t,n){return await Su(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:I$(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function M$(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await ba(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${z(n)}`]}}}async function F$(e){let t=[],n=[];for(let r of C$){let o=Ru.join(e,r);try{if(!await ee(o))continue;await $r(o),t.push(r)}catch(i){n.push(O$(r,i))}}return{invalidated:t,warnings:n}}async function Ab(e,t,n={}){let r=Nr(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await N$(e,r,n);if(!("settings"in o))return o;let i=Vr(o.settings,Pt()),s=await D$(e,o.settings.id_prefix,o.settings.item_format,r,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Ob(e):{entries:{},embedding:null,warnings:[]},c=R$(o.provider),l=a.entries,d={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Cu(a.embedding,c))d={refreshed:[],skipped:s.documents.map(b=>b.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let b=await P$(o.settings,o.provider,s.documents);if(Ou(a.embedding,b.vector_dimension))d={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[...b.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=xu(c,b.vector_dimension);let E=await L$(o.vectorStore,s.documents,b.vectors);d={refreshed:E.refreshed,skipped:E.skipped,warnings:[...b.warnings,...E.warnings]}}}catch(b){d={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[`search_semantic_refresh_failed:${z(b)}`]}}let f=await M$(o.vectorStore,s.missingIds),p=new Set(d.refreshed),_=Object.fromEntries(s.documents.filter(b=>p.has(b.id)).map(b=>[b.id,b.document.metadata.updated_at])),y=[];if(Object.keys(_).length>0||s.missingIds.length>0){let b={...l,...Cb(_)};for(let E of s.missingIds)delete b[E];try{await Ib(e,b,u)}catch(E){y.push(`search_vectorization_status_ledger_write_failed:${z(E)}`)}y.push(...a.warnings)}return{refreshed:Nr([...d.refreshed,...f.refreshed]),skipped:Nr([...s.skippedIds,...d.skipped,...f.skipped]),warnings:[...s.warnings,...d.warnings,...f.warnings,...y]}}function $$(e,t){let n=t?Ar(e).settings:e;return!!(fa(n).active&&ya(n).active)}async function Nu(e,t,n={}){let r=await F$(e),o=Nr(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await ee(ge(e))){let c=await Ab(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await Yt(e),l=c.warnings.find(d=>d.startsWith("settings_read_"));if(l)return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${l}`]};i=c.settings}catch(c){return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${z(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:r.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(n.background&&$$(i,s))return await Bh(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await Ab(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:r.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...r.warnings,...a.warnings]}}import{createRequire as j$}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]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var Rb=new Set(["1","true","yes","on"]);function U$(){return!!(Rb.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||Rb.has((process.env.PM_TELEMETRY_DISABLED??"").trim().toLowerCase())||process.env.VITEST||process.env.VITEST_WORKER_ID)}var Mb=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,z$=new RegExp(`\\b(${Mb.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu"),q$=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,V$=/file:\/\/\/?[^\s"'`),;]+/giu,G$=/\b[A-Za-z]:\\[^\s"'`),;]+/g,B$=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,H$=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var W$=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function Nb(e){let t=e.trim();return t.length===0?!1:t.startsWith("/")||t.startsWith("file://")||/^[A-Za-z]:\\/.test(t)||t.startsWith("\\\\")?!0:t.includes("/home/")}function lt(e,t){if(t&&H$.test(t)&&Nb(e))return"[scrubbed_path]";let n=e.replaceAll(z$,(r,o)=>`${o}=[scrubbed]`).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(B$,"[scrubbed_ip]").replaceAll(V$,"[scrubbed_path]").replaceAll(G$,"[scrubbed_path]").replaceAll(q$,(r,o)=>`${o}[scrubbed_path]`);return Nb(n)?"[scrubbed_path]":n}function Qt(e){let t={};for(let[n,r]of Object.entries(e))Mb.test(n)?t[n]="[scrubbed]":typeof r=="string"?t[n]=lt(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?lt(o,n):o&&typeof o=="object"?Qt(o):o):r&&typeof r=="object"?t[n]=Qt(r):t[n]=r;return t}function K$(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=lt(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=lt(t,"context_line"));for(let n of["pre_context","post_context"]){let r=e[n];Array.isArray(r)&&(e[n]=r.map(o=>typeof o=="string"?lt(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=Qt(e.vars)),e.data&&typeof e.data=="object"&&(e.data=Qt(e.data))}var Y$=j$(import.meta.url),X$=()=>Y$("@sentry/node"),Du,Db=!1,J$=X$,Q$="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function Pu(e){return/^\s*PmCliError:/.test(e)}function Lu(e){let t=e.trim().toLowerCase();return t.length===0?!1:W$.some(n=>t.includes(n))}function Z$(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Lu(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Lu(t.value))}function ej(e){if(e.logger!=="console")return!1;let t=n=>typeof n=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(n);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(n=>t(n.value))}function tj(e){return!!(e.exception?.values?.some(t=>t.type==="PmCliError")||e.exception?.values?.some(t=>typeof t.value=="string"&&Pu(t.value))||e.logger==="console"&&typeof e.message=="string"&&Pu(e.message))}function Fb(e){return e.category==="console"&&typeof e.message=="string"&&Pu(e.message)}function $b(e){return e.category==="console"&&typeof e.message=="string"&&Lu(e.message)}function nj(){return lc(import.meta.url,["../../.."])??"0.0.0"}function rj(){let e=process.env.SENTRY_ENVIRONMENT?.trim();return e&&e.length>0?e:process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test"?"test":process.env.CI?"ci":"production"}var Pb=.2;function oj(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return Pb;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?Pb:t}function ij(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=lt(t.value,"value")),t.stacktrace?.frames)for(let n of t.stacktrace.frames)K$(n)}}function jb(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=lt(t.message)),t.data&&typeof t.data=="object"&&(t.data=Qt(t.data))}function Ub(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=Qt(n))}function Lb(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=Qt(r))}var sj=e=>{if(tj(e)||Z$(e))return null;ej(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=lt(e.message,"message")),e.transaction&&(e.transaction=lt(e.transaction,"transaction")),ij(e),jb(e),Lb(e,"extra"),Ub(e);for(let t of["request","user","tags"])Lb(e,t);return e},aj=e=>(e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!Fb(t)&&!$b(t)),jb(e)),Ub(e),e),cj=e=>Fb(e)||$b(e)?null:(e.message&&(e.message=lt(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=Qt(e.data)),e);async function lj(){if(Db)return Du;if(Db=!0,U$())return;let e=J$();Du=e;let t=process.env.SENTRY_DSN?.trim()||Q$,n=nj();return e.init({dsn:t,release:`pm-cli@${n}`,environment:rj(),tracesSampleRate:oj(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,sendDefaultPii:!1,serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":n,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:sj,beforeSendTransaction:aj,beforeBreadcrumb:cj}),e}function Fn(){return Du}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var dj=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),uj=new Set(["list","list-all","list-open","list-in-progress","list-blocked","list-closed","list-canceled","list-draft","search","get","context","calendar","history","activity","aggregate","deps","contracts","stats"]),fj=new Set(["create","update","update-many","close-many","append","close","delete","restore","claim","release","comments","notes","learnings","files","docs","start-task","pause-task","close-task"]),pj=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),mj=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function _j(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function zb(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var gj=[{code:"unknown_command",matches:e=>e.includes("unknown command")},{code:"unknown_option",matches:e=>e.includes("unknown option")},{code:"missing_required_option",matches:e=>e.includes("missing required options")||e.includes("missing required option")},{code:"missing_required_argument",matches:e=>e.includes("missing required argument")},{code:"no_update_fields",matches:e=>e.includes("no update flags provided")},{code:"ownership_conflict",matches:e=>e.includes("is assigned to")&&e.includes("use --force")},{code:"lock_conflict",matches:e=>e.includes("is locked")},{code:"terminal_state_conflict",matches:e=>e.includes("already terminal")&&e.includes("use --force")},{code:"tracker_not_initialized",matches:e=>e.includes("tracker is not initialized")},{code:"item_not_found",matches:e=>e.includes(" not found")},{code:"close_through_update",matches:e=>e.includes('use "pm close <id> <text>" to close an item')||e.includes("invalid --status value")&&e.includes('"closed"')},{code:"invalid_argument_value",matches:e=>e.startsWith("invalid ")||e.includes(" must be ")||e.includes(" requires ")},{code:"invalid_command_usage",matches:e=>e.includes("either as positional")&&e.includes("not both")}],yj=new Map([[g.USAGE,"invalid_command_usage"],[g.NOT_FOUND,"item_not_found"],[g.CONFLICT,"lock_conflict"],[g.DEPENDENCY_FAILED,"dependency_failed"]]);function Dr(e){let t=_j(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return dj.has(r)?i="setup":uj.has(r)?i="query":fj.has(r)?i="mutation":pj.has(r)?i="testing":r==="extension"?i="extension":mj.has(r)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:r,command_leaf:o,command_depth:n.length,command_family:i}}function Mu(e){if(e.ok)return;let t=zb(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of gj)if(o.matches(n))return o.code;let r=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return r!==void 0?yj.get(r)??"command_failed":"command_failed"}function Pr(e){if(e.ok)return"success";let t=zb(e.errorCode);return t==="unknown_command"?"nonexistent_command":t==="unknown_option"?"invalid_option":t==="missing_required_option"?"missing_required_option":t==="missing_required_argument"?"missing_required_argument":t==="health_findings"?"health_findings":t==="validation_findings"?"validation_findings":e.errorCategory==="usage"?"invalid_usage":e.errorCategory==="validation"?"validation_failed":e.errorCategory==="conflict"?"conflict":e.errorCategory==="runtime"?"runtime_failed":"unknown_failed"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e6ba316-b067-51df-abeb-c3e3488a504d")}catch{}})();var Lr;function Zt(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function Ea(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function hj(e,t,n){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof n?.exit_code=="number"&&(e.setTag("pm.exit_code",String(n.exit_code)),e.setTag("pm.command_exit_code",String(n.exit_code))),Ea(e,"pm.error_code",n?.error_code),Ea(e,"pm.error_category",n?.error_category),Ea(e,"pm.command_resolution",n?.command_resolution),Ea(e,"pm.resolution_stage",n?.resolution_stage)}function bj(e,t,n,r){Zt(e,"pm.ok",t),Zt(e,"pm.command_ok",t),Zt(e,"pm.exit_code",n),Zt(e,"pm.command_exit_code",n),Zt(e,"pm.error_code",r?.error_code),Zt(e,"pm.error_category",r?.error_category),Zt(e,"pm.command_resolution",r?.command_resolution),Zt(e,"pm.resolution_stage",r?.resolution_stage)}function wj(e,t,n,r){let o=Fn();if(!o)return;let i=Dr(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),typeof r?.source_context=="string"&&r.source_context.trim().length>0&&o.setTag("pm.source_context",r.source_context);let s=t.map(a=>a.startsWith("--")?a.split("=")[0]:a);o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(n).sort(),source_context:r?.source_context,source_context_source:r?.source_context_source}),o.addBreadcrumb({category:"pm.command",message:`pm ${e}`,level:"info",data:{args:s,command_root:i.command_root,command_family:i.command_family,source_context:r?.source_context}})}function Ej(e){let t=Fn();t&&(Lr=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0}))}function vj(e,t,n){if(!Lr)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Fn();i&&hj(i,r,n),bj(Lr,r,o,n),Lr.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Lr.end(),Lr=void 0}var Tj="unclassified_runtime_error";function kj(e){let t=typeof e=="object"&&e!==null?e:void 0,n=typeof t?.exitCode=="number",r=n?Math.trunc(t?.exitCode):g.GENERIC_FAILURE;return{error_code:typeof t?.code=="string"&&t.code.length>0&&n?t?.code:Tj,exit_code:r}}function Aj(e){let t=kj(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Sj(e){if(!Cj(e))return;let t=Fn();if(!t)return;let n=Aj(e);if(e instanceof Error){let r={};"exitCode"in e&&typeof e.exitCode=="number"&&(r.exit_code=e.exitCode),"context"in e&&typeof e.context=="object"&&(r.error_context=e.context),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function xj(e){let t=Fn();if(!t)return;let n=e.command_resolution??Pr({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),r=e.resolution_stage??"unknown",o={"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":e.exit_code,"pm.error_message":e.error_message,"pm.command_resolution":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??""},i=t.logger;if(i&&typeof i.warn=="function"){i.warn("pm_cli_usage_error",o);return}t.captureMessage(`pm_cli_usage_error:${e.error_code}`,{level:"warning",tags:{"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":String(e.exit_code),"pm.command_resolution":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??"unknown"},extra:o})}function Cj(e){if(e instanceof h||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+[cd]|sigint|user[- ]initiated)/i.test(e.message))return!1;if(typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"){if(e instanceof Error&&e.name==="CommandError")return!1;let t=Math.trunc(e.exitCode);return!new Set([g.SUCCESS,g.USAGE,g.NOT_FOUND,g.CONFLICT]).has(t)}return!0}async function Oj(e=3e3){let t=Fn();if(t)try{await t.flush(e)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var Ij=/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/,Rj=/\bnpm_[A-Za-z0-9]{36}\b/,Nj=/\bxox[baprs]-(?=[A-Za-z0-9-]{20,80}\b)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{20,80}\b/,Dj=/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,Pj=/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,qb=/\b(?:token|secret|password|passwd|api[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9+/=_-]{24,})/gi,Lj=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],$u=new Map(Lj.map(e=>[e.action,e]));function Mj(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function Fu(e,t="$",n=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:n.has(e)?[]:(n.add(e),Array.isArray(e)?e.flatMap((r,o)=>Fu(r,`${t}[${o}]`,n)):Object.entries(e).flatMap(([r,o])=>Fu(o,`${t}.${r}`,n)))}function Vb(e){let t=[];for(let n of Fu(e)){Ij.test(n.value)&&t.push({rule:"github_token",path:n.path}),Rj.test(n.value)&&t.push({rule:"npm_token",path:n.path}),Nj.test(n.value)&&t.push({rule:"slack_token",path:n.path}),Dj.test(n.value)&&t.push({rule:"private_key",path:n.path}),Pj.test(n.value)&&t.push({rule:"aws_access_key",path:n.path}),qb.lastIndex=0;for(let r of n.value.matchAll(qb)){let o=r[1];if(Mj(o)>=3.5){t.push({rule:"high_entropy_assignment",path:n.path});break}}}return t.filter((n,r,o)=>o.findIndex(i=>i.rule===n.rule&&i.path===n.path)===r)}function Fj(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new h("Mutation author is required by workspace policy.",g.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let n;try{n=Vb(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};let r=[...new Set(n.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new h(`Mutation blocked by secret guard (${r}). No detected value was logged.`,g.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:n,warnings:[`secret_guard_detected:${n.length}:rules=${r}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function $j(e){return $u.has(e.trim().toLowerCase())}function jj(){return[...$u.keys()].sort((e,t)=>e.localeCompare(t))}function p4(e){return $u.get(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ad30a32-0f83-5473-b0a3-349e271d8378")}catch{}})();function Uj(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function _4(e){return Uj(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function va(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).size;return o/i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dff9b113-2b29-5154-afbf-f191f2f556a6")}catch{}})();var zj=/\b[a-z][a-z0-9]*-\d+(?:-[a-z0-9]+)*\b/giu;function ju(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Bb(e){return[...new Set(ju(e).match(/[\p{L}\p{N}]+/gu)??[])]}function Gb(e){let t=ju(e);return{normalized:t,tokens:Bb(t),issueCodes:[...new Set(t.match(zj)?.map(n=>n.toLowerCase())??[])]}}function qj(e,t){return Vj(Gb(e),Gb(t))}function Vj(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let n=new Set(e.issueCodes);return t.issueCodes.some(r=>n.has(r))?{score:.99,reason:"issue_code"}:{score:va(e.tokens,t.tokens),reason:"title_token_jaccard"}}import Gj 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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();function Ta(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Bj(e,t){return[e.updated_at,t].map(r=>({value:r,time:Date.parse(r??"")})).filter(r=>typeof r.value=="string"&&Number.isFinite(r.time)).sort((r,o)=>o.time-r.time)[0]?.value??e.updated_at}function Hb(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=Ta(t.in_progress_status),i=[];for(let s of e){if(Ta(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Bj(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let l=Math.max(0,Math.floor((r-c)/36e5));l>=n&&i.push({id:s.id,last_activity_at:a,age_hours:l})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:n,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Hj(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>Ta(String(o.status))===Ta(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await Ke(Gj.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&r.set(o.id,s)})),Hb(t,{...n,last_history_activity:o=>r.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var Wj=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),Kj=/&(?:lt|gt|quot|#39|amp);/g;function Yj(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(Kj,t=>Wj[t])}function Xj(e){return Uu(e,new WeakMap)}function Uu(e,t){if(typeof e=="string")return Yj(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let n=[];t.set(e,n);for(let r of e)n.push(Uu(r,t));return n}if(e!==null&&typeof e=="object"){if(!Jj(e))return e;if(t.has(e))return t.get(e);let n=e,r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let[o,i]of Object.entries(n))Object.defineProperty(r,o,{value:Uu(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function Jj(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();function Qj(e){let t=null;return()=>(t??=e(),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]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();function Wb(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function Zj(e){return Wb(e)[0]??null}function e1(e,t){let n=Zj(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Wb(e).some(o=>!o.slice(2).includes("-")||n===o?!1:r(n)===r(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]="4ecab833-db06-5baa-bfe6-d28b4c97f85a")}catch{}})();function t1(e,t){if(e==null)return[];let n=t?.separators??/,/,o=e.split(n).map(a=>a.trim()).filter(a=>a.length>0),s=t?.unique!==!1?Array.from(new Set(o)):o;return t?.sort===!0?[...s].sort():s}import Kb from"node:fs/promises";import ka 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]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();function n1(e){return"json_markdown"}function Yb(e,t){return ka.relative(e,t).replaceAll("\\","/")}function r1(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function o1(e,t,n="item_format:migrate",r=_e,o){if(t!=="toon")throw new Error("Only toon item-format migration targets are supported. Markdown item files are legacy read-only input.");let i=new Set,s=new Set,a=[],c=0,l=n1(t),d=Object.entries(r);for(let[u,f]of d){let p=ka.join(e,f),_=[];try{_=await Kb.readdir(p)}catch{continue}let y=new Map;for(let E of _){let T=ka.join(p,E),O=Hr(T);if(!O)continue;let M=ka.extname(E),W=E.slice(0,E.length-M.length).trim();if(W.length===0)continue;let Ee=y.get(W)??{};Ee[O]=T,y.set(W,Ee)}let b=[...y.keys()].sort((E,T)=>E.localeCompare(T));for(let E of b){let T=y.get(E);c+=1;let O=T[l];if(!O)continue;let M=T[t]??O,W=M===T[t]?t:l;try{let Ee=await Kb.readFile(M,"utf8"),le=bn(Ee,{format:W,schema:o,onWarning:Gf=>a.push(`item_format_migration_parse_warning:${E}:${Gf}`)}),tn=Qn(e,u,E,t,r),nn=ho(le,{format:t,schema:o});await Y(tn)!==nn&&(await P(tn,nn),a.push(...await ye({path:tn,scope:"project",op:n})),i.add(E)),await $r(O),s.add(Yb(e,O)),a.push(...await ye({path:O,scope:"project",op:`${n}:remove`})),i.add(E)}catch(Ee){a.push(`item_format_migration_skipped:${Yb(e,M)}:${r1(Ee)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((u,f)=>u.localeCompare(f)),removed:[...s].sort((u,f)=>u.localeCompare(f)),warnings: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]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();var i1=new Set(["completed","superseded"]);function s1(e){return e!==void 0&&i1.has(e)}function a1(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(n=>n.status==="completed")}import c1 from"node:readline/promises";import{stdin as l1,stdout as Xb}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();var d1="PM_TELEMETRY_PROMPT",Jb=new Set(["0","false","no","off"]),u1=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function f1(e){return typeof e!="string"?!1:Jb.has(e.trim().toLowerCase())}function p1(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!Jb.has(t)}function m1(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||f1(process.env[d1])||p1(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:u1.has(n)}function _1(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function g1(e){let n=`pm telemetry helps improve reliability and usage diagnostics.
185
+ 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 Qs(e){await Nn.rm(xr(e),{force:!0})}import pe from"node:fs/promises";import Z from"node:path";import{createHash as NM,randomUUID as rb}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]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var lt=8,ru=500,DM="metadata-derived-index",PM="metadata-cache.json",LM="metadata-cache-bodies.json",MM="metadata-cache-collections.json",FM="metadata-cache-delta.json",$M="metadata-cache-manifest.json",Zh=4,jM=["comments","notes","learnings","files","tests","test_runs","docs"];function ob(){return lo($t())}function ea(e){let t={...e},n={};for(let r of jM)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function ib(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function sb(e,t,n,r){let o=NM("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 ta(e){return Z.join(e,"runtime",PM)}function na(e){return Z.join(e,"runtime",LM)}function ra(e){return Z.join(e,"runtime",MM)}function ou(e){return Z.join(e,"runtime",FM)}function iu(e){return Z.join(e,"runtime",$M)}function oa(e,t){let n=Z.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var UM=24,ze=new Map,ia=new WeakMap;function su(e){return ia.get(e)??e.source_cursor}function zM(e,t){let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ia.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 qM(e,t){if(!e)return;let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ia.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 VM(e,t){if(!e)return;let n=su(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){ia.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 GM(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(zM(e,r),qM(t,r),VM(n,r))}function nu(e,t){ze.size>=UM&&!ze.has(e)&&Wn(ze),ze.set(e,t)}async function en(e,t){let n;try{n=await pe.stat(e)}catch{return ze.delete(e),null}let r=ze.get(e);if(r&&Uo(r.signature,n.mtimeMs,n.ctimeMs,n.size))return ze.delete(e),ze.set(e,r),r.envelope;let o;try{o=t(await pe.readFile(e,"utf8"))}catch{o=null}return nu(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function BM(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==lt||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=ta(e),i=await en(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await en(oa(o,t),r);return s===null&&Vo(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function HM(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==lt||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=na(e),o=await en(r,n);return t&&o?.context_fingerprint!==t?await en(oa(r,t),n):o}async function WM(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==lt||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=ra(e),o=await en(r,n);return t&&o?.context_fingerprint!==t?await en(oa(r,t),n):o}async function au(e){let t=ou(e),n=await en(t,r=>{let o=JSON.parse(r);return o.version!==lt||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 pe.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function cu(e){let t=iu(e),n=await en(t,r=>{let o=JSON.parse(r);return o.version!==lt||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 pe.stat(t),await Cr(e)}catch{}return null}async function zo(e,t){await pe.mkdir(Z.dirname(e),{recursive:!0}),await L(e,JSON.stringify(t));try{let r=await pe.stat(e);nu(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{ze.delete(e)}let n=Z.dirname(Z.dirname(e));if(e===ta(n)||e===na(n)||e===ra(n)){let r=oa(e,t.context_fingerprint);await L(r,JSON.stringify(t));try{let c=await pe.stat(r);nu(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{ze.delete(r)}let o=Z.dirname(e),i=Z.extname(e),s=Z.basename(e,i),a=(await pe.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==Z.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>Z.join(o,c.name));if(a.length>Zh){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await pe.stat(l)).mtimeMs}}catch{return null}}))).filter(l=>l!==null);for(let l of c.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,c.length-Zh)))await pe.rm(l.path,{force:!0}),ze.delete(l.path)}}}function KM(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function ab(e,t,n){return e===void 0||KM(e,t,n)}function Vo(e,t){e&&!e.includes(t)&&e.push(t)}function Uo(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function YM(e,t,n){let r=Z.join(e,t);try{let o=await pe.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!le(o)&&Vo(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function XM(e,t){try{let n=await pe.stat(Z.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 Zs(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await XM(e,n))))}function qo(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&&Uo(o,r.mtime_ms,r.ctime_ms,r.size)})}function JM(e){return Ci.some(t=>e.toLowerCase().endsWith(t))}function QM(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function ZM(e,t,n){if(n)for(let r of await Ke({path:e,scope:"project"}))Vo(t,r)}function eb(e,t,n,r){if(e)return t&&n?n.collections:r}async function eF(e,t,n){let r=await pe.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Hr(e);await ZM(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Uo(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Uo(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&Uo(f,o,i,s);if(!(!l||n.includeBody&&!u||n.includeCollections&&!p))return{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:c.metadata,heavyMetadata:eb(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let y=await pe.readFile(e,"utf8"),b=wn(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:T=>Vo(n.warnings,T)}),E=ea(b.metadata);return QM(n.state.misses,n.includeBody,n.includeCollections,l,u,p),{mtimeMs:o,ctimeMs:i,size:s,itemFormat:a,lightMetadata:l?c.metadata:E.light,heavyMetadata:eb(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function tF(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?ib(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};ab(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function nF(e,t,n,r){try{let o=await eF(t,n,r);tF(t,n,r,o)}catch{Vo(r.warnings,`item_list_item_read_failed:${e}/${Z.basename(t)}`)}}function rF(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function oF(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function iF(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function sF(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function aF(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!JM(s))continue;let a=Z.join(o,s),c=Z.relative(t.pmRoot,a);n.push(nF(r,a,c,t))}return n}async function cF(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!qo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await zo(ta(e.pmRoot),{version:lt,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await zo(iu(e.pmRoot),{version:lt,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:Z.relative(e.pmRoot,r.item_path),metadata:ea(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await Jh({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Qs(e.pmRoot)}catch{}}async function lF(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 zo(na(e.pmRoot),{version:lt,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function dF(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 zo(ra(e.pmRoot),{version:lt,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function sa(e,t,n={}){let r=await cu(e);return n.required!==!0&&(r===null||r.entry_count<ru)?async()=>{}:Te(e,DM,30,t,!1,!1,3e3)}async function uF(e,t){let n=await cu(e);if(n===null)return null;let r=await au(e);if(r.invalid)return await Cr(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&&!qo(i,await Zs(e,t))?null:{source_cursor:o,entry_count:n.entry_count}}function tb(e,t){let n=Z.relative(e,t);return n===""||n===".."||n.startsWith(`..${Z.sep}`)||Z.isAbsolute(n)?null:n}async function Cr(e){await Promise.all([ta(e),na(e),ra(e),ou(e),iu(e)].map(async t=>{await pe.rm(t,{force:!0}),ze.delete(t)})),await Qs(e)}async function fF(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await pe.stat(e.mutation.itemPath),n=ea(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 pF(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function aa(e){let t=tb(e.pmRoot,e.itemPath),n=e.previousItemPath?tb(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Cr(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=sb(e.preferredFormat,e.typeToFolder,e.schema,ob()),o=await cu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await au(e.pmRoot);if(s.invalid)return await Cr(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=pF(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 fF({mutation:e});let l=rb();return await zo(ou(e.pmRoot),{version:lt,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await Zs(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await Qh({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:ea(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Qs(e.pmRoot),[]}catch{return await Cr(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function mF(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function nb(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function _F(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function gF(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Hr(n);if(!o)continue;let i=e.includeCollections?ib(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);ab(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:Z.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function yF(e){return e.forceSourceScan||Zc()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!qo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||nb(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||nb(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&_F(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Go(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=ob(),l=sb(t,n,o,c),d=await au(e);d.invalid&&await Cr(e);let u=await BM(e,l,i.cacheDiagnostics),f=s?await HM(e,l):null,p=a?await WM(e,l):null;GM(u,f,p,d.envelope);let _=rF(u,l),y=oF(f,l),b=iF(p,l),E=[...new Set(Object.values(n))],T=await Zs(e,E),O=Object.keys(_),P=Math.max(1,Math.floor(i.derivedIndexMinimumItems??ru));if(yF({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:T,entryKeys:O,minimumIndexedItems:P,includeBody:s,includeCollections:a,previousBodies:y,previousCollections:b}))return gF({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:y,previousCollections:b});let F=await Promise.all(E.map(tT=>YM(e,tT,r))),xe=Zc(),me=sF(),et={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:xe,previousEntries:_,previousBodies:y,previousCollections:b,state:me};await Promise.all(aF(F,et));let Be=await Zs(e,E),He=qo(T,Be)?Be:{},Ya=me.misses.metadata||Object.keys(_).length!==Object.keys(me.newEntries).length||!qo(u?.directory_signatures,He)||u===null?rb():u.source_cursor;return await cF({pmRoot:e,contextFingerprint:l,sourceCursor:Ya,existingCache:u,previousEntries:_,directorySignatures:He,state:me,minimumIndexedItems:P}),s&&await lF({pmRoot:e,contextFingerprint:l,sourceCursor:Ya,existingBodyCache:f,previousBodies:y,state:me}),a&&await dF({pmRoot:e,contextFingerprint:l,sourceCursor:Ya,existingCollectionsCache:p,previousCollections:b,state:me}),mF(me)}async function cb(e,t,n,r,o){return(await Go(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}async function lb(e,t,n,r,o){return(await Go(e,t,n,r,o,{includeBody:!1,includeCollections:!1})).map(s=>({metadata:s.metadata,body:s.body??""}))}import du from"node:fs/promises";import ca 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]="8b0efe32-43f5-51ed-b1d5-5c26a3ae5bf0")}catch{}})();function tn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function uu(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:`pm ${t.map(n=>`'${n.replaceAll("'",`'"'"'`)}'`).join(" ")}`,suggested_retry_args:t}}function la(e){return new h(`Tracker root is not a directory at ${e}.`,g.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function lu(e){return new h(`Tracker root is not readable at ${e}.`,g.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function hF(e){let t=ca.resolve(e),n=ca.parse(t).root,r=ca.dirname(t);for(;r!==n;){let o;try{o=await du.stat(r)}catch(i){if(tn(i,"ENOTDIR"))throw la(e);if(!tn(i,"ENOENT"))throw i;r=ca.dirname(r);continue}if(!o.isDirectory())throw la(e);return}}async function Or(e){let t;try{t=await du.stat(e)}catch(n){throw tn(n,"ENOENT")?(await hF(e),new h(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,g.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:uu(e)})):tn(n,"ENOTDIR")?la(e):tn(n,"EACCES")||tn(n,"EPERM")?lu(e):n}if(!t.isDirectory())throw la(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw lu(e);try{await(await du.opendir(e)).close()}catch(n){throw tn(n,"EACCES")||tn(n,"EPERM")?lu(e):n}}async function bF(e){if(await Or(e),!await ee(ge(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,g.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:uu(e)})}import Ir from"node:fs/promises";import wF 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]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function EF(e){try{return await Ir.access(e),!0}catch{return!1}}function vF(e,t){e&&(e.includes(t)||e.push(t))}function db(e){return e??lo($t())}function TF(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Bo(e,t,n="pm-",r,o=_e){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=In(t,n),c=js(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=TF(r);for(let f of l)for(let[p]of d)for(let _ of u){let y=Qn(e,p,f,_,o);if(await EF(y))return{id:f,type:p,itemPath:y,item_format:_}}return null}async function Ho(e,t={}){let n=await Ir.readFile(e.itemPath,"utf8");await Ke({path:e.itemPath,scope:"project"});let r=wn(n,{format:e.item_format,schema:t.schema,extensionFieldNames:db(t.extensionFieldNames),onWarning:o=>vF(t.warnings,o)});return{raw:n,document:r}}async function ub(e,t,n=_e,r,o){return await Or(e),(await cb(e,t,n,r,o)).map(s=>s.metadata)}async function kF(e,t,n=_e,r,o){return await Or(e),(await lb(e,t,n,r,o)).map(s=>s.metadata)}async function g3(e,t,n=_e,r,o,i={}){return await Or(e),(await Go(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function fu(e){return{async get(t){let n=await Bo(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Ho(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>ub(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function AF(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await Ir.readdir(wF.join(e,o));for(let s of i)for(let a of Ci)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function SF(e,t,n,r){let o=In(t,n),i=await AF(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:We(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function fb(e,t,n,r){let o=await SF(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 h(`Item ${t} not found`,g.NOT_FOUND,{nextSteps:i})}function xF(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 pb(e){let t=e.typeToFolder??Vr(e.settings,$t()).type_to_folder,n=await Bo(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await fb(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await Te(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 Ho(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=ql(e.author),d=Hs(e.settings);if(a&&c!==l&&!e.force&&!xF(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new h(`Item ${n.id} is assigned to ${a}. Use --force to override.`,g.CONFLICT);d.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 CF(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 OF(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await L(e.originalItemPath,e.originalRaw),await Ir.rm(e.effectiveTargetItemPath,{force:!0});return}await L(e.originalItemPath,e.originalRaw)}}async function pu(e){let t=await pb({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=je(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=je(structuredClone(i),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=await e.mutate(l);if(e.skipNoop===!0&&d.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...d.warnings??[]]};let u=e.resolveHistoryContext?.();l.metadata.updated_at=oe();let f=je(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Yi({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:fu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await $s({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",y=ho(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=Qn(e.pmRoot,f.metadata.type,r.id,_,n),E=Zn(e.pmRoot,r.id),T=await $e("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:r.id,source_item_path:r.itemPath,target_item_path:b,history_path:E,item_format:_,before:c,after:f,contents:y}),{effectiveTargetItemPath:O,effectiveSerializedAfter:P,skipItemWrite:F}=CF(T,b,y),xe=await sa(e.pmRoot,e.author),me=[];try{F||await L(O,P),!F&&O!==r.itemPath&&await Ir.rm(r.itemPath);let Be=At({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await St(E,Be)}catch(He){throw await OF({skipItemWrite:F,effectiveTargetItemPath:O,originalItemPath:r.itemPath,originalRaw:o}),He}F||(me=await aa({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:O,previousItemPath:r.itemPath,document:f}))}finally{await xe()}let et=[...await ye({path:O,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await ye({path:E,scope:"project",op:`${e.op}:history`,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields})];return Ki({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:co(c.metadata,d.changedFields),current:co(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...T.warnings,...me,...et]}}finally{await a()}}async function IF(e){let{historyContext:t,...n}=e;return pu({...n,resolveHistoryContext:()=>t})}async function y3(e){return pu(e)}async function RF(e){return pu(e)}async function NF(e){let t=await pb({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=db(void 0),c=je(o,{schema:e.settings.schema,extensionFieldNames:a});await Yi({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:fu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let l=await $s({pmRoot:e.pmRoot,settings:e.settings,itemId:n.id,commandLabel:"delete"}),d=oe(),u=Bn,f=At({nowIso:d,author:e.author,op:"delete",before:c,after:u,message:e.message}),p=Zn(e.pmRoot,n.id),_=await $e("item_store_delete",{op:"delete",pm_root:e.pmRoot,item_id:n.id,item_path:n.itemPath,history_path:p,before:c}),y=n.itemPath,b=!1;if(_.handled&&typeof _.result=="object"&&_.result!==null){let P=_.result;typeof P.item_path=="string"&&P.item_path.trim().length>0&&(y=P.item_path),P.skip_delete===!0&&(b=!0)}if(e.dryRun===!0)return{item:c.metadata,changedFields:["deleted"],targetPath:y,warnings:[...i,...l.warnings,..._.warnings]};let E=await sa(e.pmRoot,e.author),T=[];try{b||await Ir.rm(y);try{await St(p,f)}catch(P){throw b||await L(y,r),P}b||(T=await aa({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:y,document:null}))}finally{await E()}let O=[...await ye({path:y,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:u,changed_fields:["deleted"]}),...await ye({path:p,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:u,changed_fields:["deleted"]})];return Ki({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:co(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...i,...l.warnings,..._.warnings,...T,...O]}}finally{await 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]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}catch{}})();var DF=3e4;function Dn(e,t,n=DF){let r=e??n;if(!Number.isFinite(r)||r<=0)throw new Error(`${t} timeout must be a positive finite number`);return Math.floor(r)}function Pn(e,t){if(e)return e;if(typeof globalThis.fetch=="function")return globalThis.fetch.bind(globalThis);throw new Error(`${t} execution requires a fetch implementation`)}async function PF(e){try{return(await e.text()).replaceAll(/\s+/g," ").trim()}catch(t){return`(failed to read response body: ${q(t)})`}}async function da(e){let t=new AbortController,n=setTimeout(()=>{t.abort()},e.timeoutMs);try{let r;try{r=await e.fetcher(e.endpoint,{method:e.method,headers:e.headers,body:JSON.stringify(e.body),signal:t.signal})}catch(o){throw o instanceof Error&&o.name==="AbortError"?new Error(`${e.requestLabel} timed out after ${e.timeoutMs}ms`):new Error(`${e.requestLabel} execution failed: ${q(o)}`)}if(!r.ok){let o=await PF(r),i=o.length>0?`: ${o}`:"";throw new Error(`${e.requestLabel} failed with status ${r.status} ${r.statusText}${i}`)}try{return await r.json()}catch(o){throw new Error(`${e.responseLabel} JSON parse failed: ${q(o)}`)}}finally{clearTimeout(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]="af754be6-8026-530a-8a20-b03d4ed742e1")}catch{}})();function T3(e,t){let n=$(e);if(!n)return"unconfigured";let r=$(t);return r&&r.toLowerCase()===n.toLowerCase()?"configured":"auto-detected"}function LF(e){let t=jr(e),n=t.toLowerCase();return n.endsWith("/embeddings")?t:n.endsWith("/v1")?`${t}/embeddings`:`${t}/v1/embeddings`}function _b(e){let t=e.search?.embedding_model;return $(t)||null}function MF(e){let t=$(e.providers?.openai?.base_url),n=$(e.providers?.openai?.model);if(!t||!n)return null;let r=_b(e),o=$(e.providers?.openai?.api_key);return{name:"openai",base_url:t,model:r??n,...o?{api_key:o}:{}}}function FF(e){let t=$(e.providers?.ollama?.base_url),n=$(e.providers?.ollama?.model);if(!t||!n)return null;let r=_b(e);return{name:"ollama",base_url:t,model:r??n}}function gb(e){let t=(Array.isArray(e)?e:[e]).map(n=>n.trim()).filter(n=>n.length>0);if(t.length===0)throw new Error("Embedding input must include at least one non-empty string");return t}function $F(e){let t=[],n=[],r=new Map;for(let o of e){let i=r.get(o);if(i===void 0){let s=t.length;t.push(o),r.set(o,s),n.push(s);continue}n.push(i)}return{uniqueInputs:t,originalToUniqueIndex:n}}function jF(e){let t=e.map((r,o)=>({embedding:r.embedding,index:r.index,position:o}));if(t.some(r=>r.index!==void 0)){for(let r of t)if(!Number.isInteger(r.index))throw new TypeError(`OpenAI embedding response entry at position ${r.position} is missing a valid integer index`);return[...t].sort((r,o)=>{let i=r.index-o.index;return i!==0?i:r.position-o.position})}return t}function ua(e){let t=MF(e),n=FF(e),r=[t,n].filter(a=>a!==null),o=$(e.search?.provider),i=o?o.toLowerCase():null;return{active:(i?r.find(a=>a.name===i):void 0)??r[0]??null,available:r}}function mb(e){let t=jr(e.base_url);return e.name==="openai"?{provider:"openai",endpoint:LF(t),model:e.model}:{provider:"ollama",endpoint:`${t}/api/embed`,model:e.model}}function UF(e,t){let n=gb(t);return e.name==="openai"?{target:mb(e),method:"POST",headers:{"content-type":"application/json",...e.api_key?{authorization:`Bearer ${e.api_key}`}:{}},body:{model:e.model,input:n.length===1?n[0]:n}}:{target:mb(e),method:"POST",headers:{"content-type":"application/json"},body:{model:e.model,input:n}}}function zF(e,t){if(e.name==="openai"){let o=t.data;if(!Array.isArray(o)||o.length===0)throw new Error("OpenAI embedding response must include a non-empty data array");return jF(o).map((s,a)=>{let c=s.embedding;if(!Hn(c))throw new Error(`OpenAI embedding response entry at index ${a} is missing a numeric embedding vector`);return[...c]})}let n=t.embedding;if(Hn(n))return[[...n]];let r=t.embeddings;if(Array.isArray(r)&&r.length>0)return r.map((o,i)=>{if(!Hn(o))throw new Error(`Ollama embedding response entry at index ${i} is missing a numeric embedding vector`);return[...o]});throw new Error("Ollama embedding response must include embedding or embeddings vectors")}async function yb(e,t,n={}){let r=Dn(n.timeout_ms,"Embedding request"),o=Pn(n.fetcher,"Embedding request"),i=gb(t),s=$F(i),a=UF(e,s.uniqueInputs),c=await da({endpoint:a.target.endpoint,method:a.method,headers:a.headers,body:a.body,timeoutMs:r,fetcher:o,requestLabel:"Embedding request",responseLabel:"Embedding response"}),l=zF(e,c);if(l.length!==s.uniqueInputs.length)throw new Error(`Embedding response cardinality mismatch: expected ${s.uniqueInputs.length} vector(s), received ${l.length}`);return s.originalToUniqueIndex.map(d=>[...l[d]])}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}catch{}})();var fa=["title","description","tags","status","type","priority","assignee","parent","goal","value","why_now","risk","confidence","estimated_minutes","acceptance_criteria","resolution","expected_result","actual_result","body","comments","notes","learnings","reminders","events","dependencies","plan"];function mu(e){let t=e?.search?.corpus_fields;if(!Array.isArray(t))return[...fa];let n=new Set(fa),r=Array.from(new Set(t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0&&n.has(o))));return r.length>0?r:[...fa]}var qF=8e3,_u=3200,Ln="...[semantic corpus truncated]",VF="search_embedding_corpus_max_characters_invalid:using_provider_default";function ut(e){return e.map(t=>t==null?"":String(t).trim()).filter(t=>t.length>0).join(" ")}function GF(e){return(e.reminders??[]).map(t=>ut([t.at,t.text]))}function BF(e){return(e.events??[]).map(t=>ut([t.start_at,t.end_at,t.title,t.description,t.location,t.all_day===!0?"all day":void 0,t.timezone,t.recurrence?.freq,t.recurrence?.interval,t.recurrence?.count,t.recurrence?.until,t.recurrence?.by_weekday?.join(" "),t.recurrence?.by_month_day?.join(" "),t.recurrence?.exdates?.join(" ")]))}function HF(e,t){e.push(t.title,t.body,t.status,t.owner,t.evidence,t.blocked_reason,t.superseded_by);for(let n of t.linked_items??[])e.push(`${n.kind} ${n.id}`,n.note);for(let n of t.files??[])e.push(n.path,n.note);for(let n of t.tests??[])e.push(n.command,n.path,n.note);for(let n of t.docs??[])e.push(n.path,n.note)}function WF(e,t){for(let n of t.plan_decisions??[])e.push(n.decision,n.rationale,n.evidence);for(let n of t.plan_discoveries??[])e.push(n.text);for(let n of t.plan_validation??[])e.push(n.text,n.command,n.expected)}function S3(e){let t=[];t.push(e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context);for(let n of e.plan_steps??[])HF(t,n);return WF(t,e),t.filter(n=>typeof n=="string"&&n.length>0).join(" ")}function KF(e){let t=(e.plan_steps??[]).map(s=>ut([s.order,s.id,s.title,s.body,s.status,s.owner,s.evidence,s.blocked_reason,s.superseded_by,(s.linked_items??[]).map(a=>ut([a.kind,a.id,a.note])).join(" "),(s.files??[]).map(a=>ut([a.path,a.note])).join(" "),(s.tests??[]).map(a=>ut([a.command,a.path,a.note])).join(" "),(s.docs??[]).map(a=>ut([a.path,a.note])).join(" ")])),n=(e.plan_decisions??[]).map(s=>ut([s.decision,s.rationale,s.evidence,s.step_id])),r=(e.plan_discoveries??[]).map(s=>ut([s.text,s.step_id])),o=(e.plan_validation??[]).map(s=>ut([s.text,s.command,s.expected]));if([e.plan_mode,e.plan_scope,e.plan_harness,e.plan_resume_context,...t,...n,...r,...o].some(s=>s!==void 0))return{mode:e.plan_mode,scope:e.plan_scope,harness:e.plan_harness,resume_context:e.plan_resume_context,steps:t,decisions:n,discoveries:r,validation:o}}function dt(e){return typeof e=="string"&&e.trim().length>0}var YF={title:e=>e.metadata.title,description:e=>e.metadata.description,tags:e=>e.metadata.tags,status:e=>e.metadata.status,type:e=>e.metadata.type,priority:e=>typeof e.metadata.priority=="number"?e.metadata.priority:void 0,assignee:e=>dt(e.metadata.assignee)?e.metadata.assignee:void 0,parent:e=>dt(e.metadata.parent)?e.metadata.parent:void 0,goal:e=>dt(e.metadata.goal)?e.metadata.goal:void 0,value:e=>dt(e.metadata.value)?e.metadata.value:void 0,why_now:e=>dt(e.metadata.why_now)?e.metadata.why_now:void 0,risk:e=>dt(e.metadata.risk)?e.metadata.risk:void 0,confidence:e=>e.metadata.confidence!==void 0&&e.metadata.confidence!==null?e.metadata.confidence:void 0,estimated_minutes:e=>typeof e.metadata.estimated_minutes=="number"?e.metadata.estimated_minutes:void 0,acceptance_criteria:e=>dt(e.metadata.acceptance_criteria)?e.metadata.acceptance_criteria:void 0,resolution:e=>dt(e.metadata.resolution)?e.metadata.resolution:void 0,expected_result:e=>dt(e.metadata.expected_result)?e.metadata.expected_result:void 0,actual_result:e=>dt(e.metadata.actual_result)?e.metadata.actual_result:void 0,body:e=>e.body,comments:e=>(e.metadata.comments??[]).map(t=>t.text),notes:e=>(e.metadata.notes??[]).map(t=>t.text),learnings:e=>(e.metadata.learnings??[]).map(t=>t.text),reminders:e=>GF(e.metadata),events:e=>BF(e.metadata),dependencies:e=>(e.metadata.dependencies??[]).map(t=>({id:t.id,kind:t.kind})),plan:e=>KF(e.metadata)};function hb(e,t={}){let n=t.fields??fa,r={};for(let o of n){let i=YF[o];if(!i)continue;let s=i(e);s!==void 0&&(r[o]=s)}return r}function XF(e){return e?.trim().toLowerCase()==="ollama"?_u:qF}function Rr(e,t){let n=XF(e),r=Xf(t);return r!==null?{maxCharacters:r,warning:null}:{maxCharacters:n,warning:t==null?null:VF}}function gu(e,t={}){let n=JSON.stringify(hb(e,{fields:t.fields})),r=Rr(t.providerName,t.maxCharacters).maxCharacters;if(n.length<=r)return n;if(r<=Ln.length)return Ln.slice(0,r);let o=Math.max(0,r-Ln.length);return`${n.slice(0,o)}${Ln}`}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c518b97-bc75-5e3f-91e8-d6779d565558")}catch{}})();function JF(e,t){let n=e.search.embedding_batch_size,r=e.search.embedding_timeout_ms,o=e.search.scanner_max_batch_retries,i=Number.isFinite(n)&&n>0?Math.floor(n):1,s=Number.isFinite(r)&&r>0?Math.floor(r):3e4,a=Number.isFinite(o)&&o>=0?Math.floor(o):0;return{batchSize:i,timeoutMs:s,maxRetries:a,maxBatchInputCharacters:Number.POSITIVE_INFINITY,maxInputCharacters:t}}function QF(e,t,n){let r=[],o=[],i=0;for(let s of e){let a=o.length>=t,c=o.length>0&&Number.isFinite(n)&&i+s.length>n;(a||c)&&(r.push(o),o=[],i=0),o.push(s),i+=s.length}return r.push(o),r}function ZF(e,t){return e.name!=="ollama"?t:{...t,maxBatchInputCharacters:_u}}function e$(e,t){if(!Number.isFinite(t)||t<=0||e.length<=t)return e;let n=Math.max(0,t-Ln.length);return`${e.slice(0,n)}${Ln}`.slice(0,t)}function bb(e){let t=q(e).toLowerCase();return t.includes("timed out")||t.includes("timeout")}function t$(e,t,n,r,o,i){let s=`Embedding batch ${t} failed after ${o} attempt(s): ${q(i)}`,a=`provider=${e.name} model=${e.model} batch_size=${n} timeout_ms=${r}`;return bb(i)?`${s} (${a}; guidance=check provider availability or lower search.embedding_batch_size, raise search.embedding_timeout_ms, or run keyword search while semantic indexing catches up)`:`${s} (${a})`}async function yu(e,t,n,r,o,i){let s=null;for(let a=0;a<=o;a+=1)try{let c=await yb(e,t,{timeout_ms:r});return a>0&&i.push(`search_embedding_batch_retry_succeeded:batch=${n}:attempt=${a+1}:size=${t.length}`),c}catch(c){if(s=c,bb(c)&&t.length>1){let l=Math.ceil(t.length/2),d=t.slice(0,l),u=t.slice(l);return i.push(`search_embedding_batch_split_after_timeout:batch=${n}:size=${t.length}:parts=${d.length}|${u.length}`),[...await yu(e,d,`${n}.1`,r,o,i),...await yu(e,u,`${n}.2`,r,o,i)]}if(a<o){let l=Math.min(1e3*2**a,8e3);await new Promise(d=>setTimeout(d,l))}}throw new Error(t$(e,n,t.length,r,o+1,s))}async function hu(e,t,n,r={}){if(n.length===0)return{vectors:[],warnings:[]};let o=[],i=Rr(e.name,t.search.embedding_corpus_max_characters);i.warning&&o.push(i.warning);let s=ZF(e,JF(t,i.maxCharacters)),a=0,c=n.map(f=>{let p=e$(f,s.maxInputCharacters);return p.length<f.length&&(a+=1),p});a>0&&o.push(`search_embedding_input_truncated:count=${a}:max_characters=${s.maxInputCharacters}`);let l=QF(c,s.batchSize,s.maxBatchInputCharacters),d=[],u=0;for(let f=0;f<l.length;f+=1){let p=l[f];r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"start"}),d.push(...await yu(e,p,String(f+1),s.timeoutMs,s.maxRetries,o)),u+=p.length,r.onProgress?.({batch_index:f+1,batch_total:l.length,batch_size:p.length,completed_inputs:u,total_inputs:c.length,phase:"complete"})}return{vectors:d,warnings:o}}import{mkdir as n$,readFile as r$,stat as Eu,unlink as o$}from"node:fs/promises";import{basename as wb,dirname as bu,isAbsolute as i$,join as s$,resolve as vu}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]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}catch{}})();var Tu="pm_items",a$=/[^a-zA-Z0-9_-]/g,c$=128,l$=".pm-cli-local-vectors",wu=1,Mn=new Map;function Ko(e){return($(e.collection_name)??Tu).replaceAll(a$,"_").slice(0,c$)}function pa(e){if(!Hn(e)||e.length===0)throw new Error("Vector values must be a non-empty numeric array");return[...e]}function vb(e){if(!Number.isFinite(e)||e<=0)throw new Error("Vector query limit must be a positive number");return Math.floor(e)}function d$(e){let t=e.result;if(!Array.isArray(t))throw new TypeError("Qdrant query response must include a result array");let n=t.map((r,o)=>{let i=r.id,s=typeof i=="number"?String(i):i,a=$(s);if(!a)throw new Error(`Qdrant query response entry at index ${o} is missing a non-empty id`);let c=r.score;if(typeof c!="number"||!Number.isFinite(c))throw new TypeError(`Qdrant query response entry at index ${o} is missing a finite numeric score`);let l=r.payload;if(l!==void 0&&(typeof l!="object"||l===null||Array.isArray(l)))throw new Error(`Qdrant query response entry at index ${o} must provide payload as an object when set`);return{id:a,score:c,...l?{payload:l}:{}}});return n.sort((r,o)=>r.score!==o.score?o.score-r.score:r.id.localeCompare(o.id)),n}function ku(e){let t=$(e.result?.status);if(t)return{status:t};let n=$(e.status);if(n)return{status:n};throw new Error("Qdrant upsert response must include status metadata")}async function Wo(e,t,n,r,o){return await da({endpoint:e,method:t.method,headers:t.headers,body:t.body,timeoutMs:n,fetcher:r,requestLabel:`Vector ${o} request`,responseLabel:`Vector ${o} response`})}function u$(e){let t=$(e.vector_store?.qdrant?.url);if(!t)return null;let n=$(e.vector_store?.collection_name),r=$(e.vector_store?.qdrant?.api_key);return{name:"qdrant",url:t,...n&&n!==Tu?{collection_name:n}:{},...r?{api_key:r}:{}}}function f$(e){let t=vu(e),n=bu(t);return wb(t)==="pm"&&wb(n)===".agents"?bu(n):t}function p$(e,t){return!t||i$(e)?e:vu(f$(t),e)}function m$(e,t){let n=$(e.vector_store?.lancedb?.path);if(!n)return null;let r=$(e.vector_store?.collection_name);return{name:"lancedb",path:p$(n,t),...r&&r!==Tu?{collection_name:r}:{}}}function _$(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector upsert records must include at least one entry");return e.map((t,n)=>{let r=$(t.id);if(!r)throw new Error(`Vector upsert record at index ${n} is missing a non-empty id`);let o=pa(t.vector),i=t.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`Vector upsert record at index ${n} must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}})}function g$(e){if(!Array.isArray(e)||e.length===0)throw new Error("Vector delete ids must include at least one entry");let t=e.map((r,o)=>{let i=$(r);if(!i)throw new Error(`Vector delete id at index ${o} is missing a non-empty value`);return i}).sort((r,o)=>r.localeCompare(o)),n=[];for(let r of t)n.at(-1)!==r&&n.push(r);return n}function y$(e){return e.replace(/\/points\?wait=true$/,"/points/delete?wait=true")}function h$(e){return e.replace(/\/points\?wait=true$/,"")}function ma(e){return{"content-type":"application/json",...e.api_key?{"api-key":e.api_key}:{}}}function _a(e,t){return Nr(e,t)}function Nr(e,t){return s$(vu(e),l$,`${t}.json`)}function b$(e,t,n){let r=$(e.id);if(!r)throw new Error(`LanceDB local snapshot '${n}' record at index ${t} is missing a non-empty id`);let o=pa(e.vector),i=e.payload;if(i!==void 0&&(typeof i!="object"||i===null||Array.isArray(i)))throw new Error(`LanceDB local snapshot '${n}' record '${r}' must provide payload as an object when set`);return{id:r,vector:o,...i?{payload:i}:{}}}function w$(e,t,n){let r;try{r=JSON.parse(n)}catch(c){throw new Error(`LanceDB local snapshot at '${e}' is not valid JSON: ${q(c)}`)}if(typeof r!="object"||r===null||Array.isArray(r))throw new Error(`LanceDB local snapshot at '${e}' must be a JSON object`);if(r.version!==wu)throw new Error(`LanceDB local snapshot at '${e}' must include version=${wu}`);let i=$(r.table);if(!i)throw new Error(`LanceDB local snapshot at '${e}' must include a non-empty table value`);if(i!==t)throw new Error(`LanceDB local snapshot at '${e}' table mismatch: expected '${t}', received '${i}'`);let s=r.records;if(!Array.isArray(s))throw new TypeError(`LanceDB local snapshot at '${e}' must include a records array`);let a=new Map;for(let c=0;c<s.length;c+=1){let l=b$(s[c],c,e);a.set(l.id,l)}return a}async function E$(e){try{let t=await Eu(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch(t){if(!le(t))throw t;return null}}function v$(e,t){if(!t)return null;if(t.mtimeMs===null&&t.size===null&&t.records.size===0)return t.records;let n=new Map;return Mn.set(e,{records:n,mtimeMs:null,size:null}),n}function T$(e,t){return e!==void 0&&t!==null&&e.mtimeMs===t.mtimeMs&&e.size===t.size}async function Au(e,t){let n=_a(e,t),r=Nr(e,t),o=await E$(r),i=Mn.get(n);if(!o){let a=v$(n,i);if(a)return a}if(T$(i,o))return i.records;let s=new Map;try{let a=await r$(r,"utf8");s=w$(r,t,a)}catch(a){if(!le(a))throw a}return Mn.set(n,{records:s,mtimeMs:o?.mtimeMs??null,size:o?.size??null}),s}function k$(e){let t=[...e.values()];return t.sort((n,r)=>n.id.localeCompare(r.id)),t.map(n=>({id:n.id,vector:[...n.vector],...n.payload?{payload:n.payload}:{}}))}async function Tb(e){try{await o$(e)}catch(t){if(!le(t))throw new Error(`LanceDB local snapshot delete failed at '${e}': ${q(t)}`)}}async function kb(e,t,n){let r=Nr(e,t);if(n.size===0){await Tb(r);return}let o=bu(r);try{await n$(o,{recursive:!0})}catch(s){throw new Error(`LanceDB local snapshot directory create failed at '${o}': ${q(s)}`)}let i=`${JSON.stringify({version:wu,table:t,records:k$(n)})}
186
+ `;try{await L(r,i)}catch(s){throw new Error(`LanceDB local snapshot write failed at '${r}': ${q(s)}`)}}async function A$(e,t){let n=_a(e,t),r=Nr(e,t);await Tb(r),Mn.delete(n)}function Eb(e){let t=0;for(let n=0;n<e.length;n+=1)t+=e[n]*e[n];return Math.sqrt(t)}function S$(e,t){let n=0;for(let i=0;i<e.length;i+=1)n+=e[i]*t[i];let r=Eb(e),o=Eb(t);return r===0||o===0?0:n/(r*o)}function ga(e,t){let n=u$(e),r=m$(e,t),o=[n,r].filter(c=>c!==null),i=$(e.vector_store?.adapter),s=i?i.toLowerCase():null;return{active:(s?o.find(c=>c.name===s):void 0)??o[0]??null,available:o}}function ya(e){let t=Ko(e);if(e.name==="qdrant"){let o=jr(e.url),i=encodeURIComponent(t);return{store:"qdrant",query_target:`${o}/collections/${i}/points/search`,upsert_target:`${o}/collections/${i}/points?wait=true`}}let n=encodeURIComponent(e.path),r=encodeURIComponent(t);return{store:"lancedb",query_target:`lancedb://${n}#${r}`,upsert_target:`lancedb://${n}#${r}`}}function x$(e,t,n){let r=ya(e),o=pa(t),i=vb(n);return e.name==="qdrant"?{target:r,method:"POST",headers:ma(e),body:{vector:o,limit:i,with_payload:!0}}:{target:r,method:"LOCAL",headers:{},body:{table:Ko(e),vector:o,limit:i}}}function C$(e,t){let n=ya(e),r=_$(t);return e.name==="qdrant"?{target:n,method:"POST",headers:ma(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ko(e),records:r}}}function O$(e,t){let n=ya(e),r=g$(t);return e.name==="qdrant"?{target:n,method:"POST",headers:ma(e),body:{points:r}}:{target:n,method:"LOCAL",headers:{},body:{table:Ko(e),ids:r}}}async function F3(e,t,n,r={}){let o=x$(e,t,n);if(o.method==="LOCAL"){let c=e,l=o.body,d=await Au(c.path,l.table);if(d.size===0)return[];let u=pa(l.vector),f=vb(l.limit),p=[],_=0;for(let y of d.values()){if(y.vector.length!==u.length){_++;continue}p.push({id:y.id,score:S$(u,y.vector),...y.payload?{payload:y.payload}:{}})}return _>0&&r.warnings&&r.warnings.push(`vector_dimension_mismatch:${_} records skipped (expected ${u.length} dimensions)`),p.sort((y,b)=>y.score!==b.score?b.score-y.score:y.id.localeCompare(b.id)),p.slice(0,f)}let i=Dn(r.timeout_ms,"Vector request"),s=Pn(r.fetcher,"Vector request"),a=await Wo(o.target.query_target,{method:"POST",headers:o.headers,body:o.body},i,s,"query");return d$(a)}async function Su(e,t,n={}){let r=C$(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=_a(a.path,c.table),d=await Au(a.path,c.table);for(let p of c.records)d.set(p.id,p);await kb(a.path,c.table,d);let u=Nr(a.path,c.table),f=await Eu(u);return Mn.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size}),{status:"ok"}}let o=Dn(n.timeout_ms,"Vector request"),i=Pn(n.fetcher,"Vector request"),s=await Wo(r.target.upsert_target,{method:"POST",headers:r.headers,body:r.body},o,i,"upsert");return ku(s)}async function ha(e,t,n={}){let r=O$(e,t);if(r.method==="LOCAL"){let a=e,c=r.body,l=_a(a.path,c.table),d=await Au(a.path,c.table);if(d.size===0)return{status:"ok"};for(let u of c.ids)d.delete(u);if(await kb(a.path,c.table,d),d.size===0)Mn.delete(l);else{let u=Nr(a.path,c.table),f=await Eu(u);Mn.set(l,{records:d,mtimeMs:f.mtimeMs,size:f.size})}return{status:"ok"}}let o=Dn(n.timeout_ms,"Vector request"),i=Pn(n.fetcher,"Vector request"),s=await Wo(y$(r.target.upsert_target),{method:"POST",headers:r.headers,body:r.body},o,i,"delete");return ku(s)}async function Ab(e,t=[],n={},r){if(e.name==="lancedb")return await A$(e.path,Ko(e)),{status:"ok"};if(r!==void 0){if(!Number.isInteger(r)||r<=0)throw new Error("Vector reset dimension must be a positive integer when provided");let i=ya(e),s=h$(i.upsert_target),a=Dn(n.timeout_ms,"Vector request"),c=Pn(n.fetcher,"Vector request"),l=ma(e);try{await Wo(s,{method:"DELETE",headers:l,body:{}},a,c,"delete")}catch(u){if(!q(u).includes("failed with status 404"))throw u}let d=await Wo(s,{method:"PUT",headers:l,body:{vectors:{size:r,distance:"Cosine"}}},a,c,"upsert");return ku(d)}let o=t.map(i=>i.trim()).filter(i=>i.length>0);return o.length===0?{status:"ok"}:await ha(e,o,n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}catch{}})();function ba(e,t){let n=$(e),r=$(t);return!n||!r?null:{provider:n,model:r}}function Sb(e){if(e==null)return null;if(typeof e!="object"||Array.isArray(e))throw new Error("Vectorization embedding metadata must be an object when set");let t=ba(e.provider,e.model),n=e.vector_dimension;if(!t||typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error("Vectorization embedding metadata must include provider, model, and positive vector_dimension");return{...t,vector_dimension:n}}function xu(e,t){if(!Number.isInteger(t)||t<=0)throw new Error("Vectorization embedding metadata requires a positive vector dimension");return{provider:e.provider,model:e.model,vector_dimension:t}}function Cu(e,t){return!e||e.provider!==t.provider||e.model!==t.model}function Ou(e,t){return!!(e&&e.vector_dimension!==t)}function Iu(e,t){if(e.length===0)throw new Error(`${t} returned no vectors`);let r=e[0].length;if(!Number.isInteger(r)||r<=0)throw new Error(`${t} returned an empty vector`);for(let o=1;o<e.length;o+=1)if(e[o]?.length!==r)throw new Error(`${t} returned mixed vector dimensions`);return r}import Ru 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]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();var I$=["index/manifest.json","search/embeddings.jsonl"],Cb="search/vectorization-status.json";function R$(e,t){return`search_cache_invalidation_failed:${e}:${String(t)}`}function Dr(e){return[...new Set([...e].map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ob(e){return typeof e=="string"&&e.trim().length>0&&Number.isFinite(Date.parse(e))}function Ib(e){let t=new Map;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Ob(r)||t.set(o,r)}return Object.fromEntries([...t.entries()].sort((n,r)=>n[0].localeCompare(r[0])))}async function Rb(e){let t=Ru.join(e,Cb),n=await Y(t);if(n===null||n.trim().length===0)return{entries:{},embedding:null,warnings:[]};let r;try{r=JSON.parse(n)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}if(typeof r!="object"||r===null||r.version!==1||!Array.isArray(r.items))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let o=new Map;for(let s of r.items){if(typeof s!="object"||s===null)return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};let a=s.id,c=s.updated_at;if(typeof a!="string"||a.trim().length===0||!Ob(c))return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]};o.set(a.trim(),c)}let i=null;try{i=Sb(r.embedding)}catch{return{entries:{},embedding:null,warnings:["search_vectorization_status_ledger_invalid"]}}return{entries:Object.fromEntries([...o.entries()].sort((s,a)=>s[0].localeCompare(a[0]))),embedding:i,warnings:[]}}async function Nb(e,t,n){let r=Ib(t),o=Ru.join(e,Cb),i=`${JSON.stringify({version:1,generated_at:oe(),...n?{embedding:n}:{},items:Object.entries(r).map(([s,a])=>({id:s,updated_at:a}))},null,2)}
187
+ `;await L(o,i)}function N$(e){return{id:e.id,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function D$(e){let t=ba(e.name,e.model);if(!t)throw new Error("Embedding provider must include a provider name and model");return t}function Yo(e,t){return{refreshed:[],skipped:e,warnings:[t]}}async function P$(e,t,n){if(!n.settings&&!await ee(ge(e)))return Yo(t,"search_semantic_refresh_skipped:settings_not_initialized");let r;try{if(n.settings)r=n.settings;else{let a=await Zt(e),c=a.warnings.find(l=>l.startsWith("settings_read_"));if(c)return Yo(t,`search_semantic_refresh_skipped:settings_read_failed:${c}`);r=a.settings}}catch(a){return Yo(t,`search_semantic_refresh_skipped:settings_read_failed:${q(a)}`)}let o=n.apply_runtime_defaults?Sr(r).settings:r,i=ua(o).active;if(!i)return Yo(t,"search_semantic_refresh_skipped:provider_unconfigured");let s=ga(o,e).active;return s?{settings:o,provider:i,vectorStore:s}:Yo(t,"search_semantic_refresh_skipped:vector_store_unconfigured")}async function L$(e,t,n,r,o,i){let s=[],a=new Set,c=new Set,l=[];for(let d of r){let u=await Bo(e,d,t,n,o);if(!u){c.add(d);continue}try{let f=await Ho(u,{schema:i});l.push({id:f.document.metadata.id,document:f.document})}catch(f){a.add(u.id),s.push(`search_semantic_refresh_item_read_failed:${u.id}:${q(f)}`)}}return l.sort((d,u)=>d.id.localeCompare(u.id)),{documents:l,missingIds:Dr(c),skippedIds:Dr(a),warnings:s}}async function M$(e,t,n){let r=Rr(t.name,e.search.embedding_corpus_max_characters).maxCharacters,o=mu(e),i=n.map(a=>gu(a.document,{providerName:t.name,maxCharacters:r,fields:o})),s=await hu(t,e,i);return{vectors:s.vectors,vector_dimension:Iu(s.vectors,"Semantic refresh embedding"),warnings:s.warnings}}async function F$(e,t,n){return await Su(e,t.map((r,o)=>({id:r.id,vector:n[o],payload:N$(r.document.metadata)}))),{refreshed:t.map(r=>r.id),skipped:[],warnings:[]}}async function $$(e,t){if(t.length===0)return{refreshed:[],skipped:[],warnings:[]};try{return await ha(e,t),{refreshed:[],skipped:[],warnings:[]}}catch(n){return{refreshed:[],skipped:t,warnings:[`search_semantic_refresh_delete_failed:${q(n)}`]}}}async function j$(e){let t=[],n=[];for(let r of I$){let o=Ru.join(e,r);try{if(!await ee(o))continue;await $r(o),t.push(r)}catch(i){n.push(R$(r,i))}}return{invalidated:t,warnings:n}}async function xb(e,t,n={}){let r=Dr(t);if(r.length===0)return{refreshed:[],skipped:[],warnings:[]};let o=await P$(e,r,n);if(!("settings"in o))return o;let i=Vr(o.settings,$t()),s=await L$(e,o.settings.id_prefix,o.settings.item_format,r,i.type_to_folder,o.settings.schema),a=s.documents.length>0||s.missingIds.length>0?await Rb(e):{entries:{},embedding:null,warnings:[]},c=D$(o.provider),l=a.entries,d={refreshed:[],skipped:[],warnings:[]},u=a.embedding;if(s.documents.length>0)if(a.embedding&&Cu(a.embedding,c))d={refreshed:[],skipped:s.documents.map(b=>b.id),warnings:["search_semantic_refresh_requires_reindex:embedding_identity_changed"]};else try{let b=await M$(o.settings,o.provider,s.documents);if(Ou(a.embedding,b.vector_dimension))d={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[...b.warnings,"search_semantic_refresh_requires_reindex:vector_dimension_changed"]};else{u=xu(c,b.vector_dimension);let E=await F$(o.vectorStore,s.documents,b.vectors);d={refreshed:E.refreshed,skipped:E.skipped,warnings:[...b.warnings,...E.warnings]}}}catch(b){d={refreshed:[],skipped:s.documents.map(E=>E.id),warnings:[`search_semantic_refresh_failed:${q(b)}`]}}let f=await $$(o.vectorStore,s.missingIds),p=new Set(d.refreshed),_=Object.fromEntries(s.documents.filter(b=>p.has(b.id)).map(b=>[b.id,b.document.metadata.updated_at])),y=[];if(Object.keys(_).length>0||s.missingIds.length>0){let b={...l,...Ib(_)};for(let E of s.missingIds)delete b[E];try{await Nb(e,b,u)}catch(E){y.push(`search_vectorization_status_ledger_write_failed:${q(E)}`)}y.push(...a.warnings)}return{refreshed:Dr([...d.refreshed,...f.refreshed]),skipped:Dr([...s.skippedIds,...d.skipped,...f.skipped]),warnings:[...s.warnings,...d.warnings,...f.warnings,...y]}}function U$(e,t){let n=t?Sr(e).settings:e;return!!(ua(n).active&&ga(n).active)}async function Nu(e,t,n={}){let r=await j$(e),o=Dr(t);if(o.length===0)return{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:r.warnings};if(!await ee(ge(e))){let c=await xb(e,o);return{invalidated:r.invalidated,refreshed:c.refreshed,skipped:c.skipped,warnings:[...r.warnings,...c.warnings]}}let i;try{let c=await Zt(e),l=c.warnings.find(d=>d.startsWith("settings_read_"));if(l)return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${l}`]};i=c.settings}catch(c){return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:[...r.warnings,`search_semantic_refresh_skipped:settings_read_failed:${q(c)}`]}}if(i.search.mutation_refresh_policy==="cache_only")return{invalidated:r.invalidated,refreshed:[],skipped:o,warnings:r.warnings};let s=i.search.mutation_refresh_policy==="semantic_auto";if(n.background&&U$(i,s))return await Wh(e,o),{invalidated:r.invalidated,refreshed:[],skipped:[],warnings:[...r.warnings,"search_semantic_refresh_scheduled_background"],scheduled:!0};let a=await xb(e,o,{settings:i,apply_runtime_defaults:s});return{invalidated:r.invalidated,refreshed:a.refreshed,skipped:a.skipped,warnings:[...r.warnings,...a.warnings]}}import{createRequire as z$}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]="8eb48648-6e55-5710-990e-6471c7cdcde0")}catch{}})();var Db=new Set(["1","true","yes","on"]);function q$(){return!!(Db.has((process.env.PM_SENTRY_DISABLED??"").trim().toLowerCase())||Db.has((process.env.PM_TELEMETRY_DISABLED??"").trim().toLowerCase())||process.env.VITEST||process.env.VITEST_WORKER_ID)}var $b=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,V$=new RegExp(`\\b(${$b.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu"),G$=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,B$=/file:\/\/\/?[^\s"'`),;]+/giu,H$=/\b[A-Za-z]:\\[^\s"'`),;]+/g,W$=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g,K$=/(?:^|[_-])(path|filename|file|module|cwd|dir|directory|location|source|script)s?$/i;var Y$=["[starter-extension] activating","[starter-extension] all 8 capabilities registered.","[starter-extension] commands:","[starter] preflight check for workspace","[starter] output_format service override active","[pm-ext-ts-starter] activating","[pm-ext-ts-starter] all capabilities registered.","run `pm init` first to initialise a pm workspace"];function Pb(e){let t=e.trim();return t.length===0?!1:t.startsWith("/")||t.startsWith("file://")||/^[A-Za-z]:\\/.test(t)||t.startsWith("\\\\")?!0:t.includes("/home/")}function ft(e,t){if(t&&K$.test(t)&&Pb(e))return"[scrubbed_path]";let n=e.replaceAll(V$,(r,o)=>`${o}=[scrubbed]`).replaceAll(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/giu,"[scrubbed_email]").replaceAll(/bearer\s+[a-z0-9._=-]+/giu,"bearer [scrubbed]").replaceAll(/sntr[ysu]_[A-Za-z0-9_-]+/g,"[scrubbed_sentry_token]").replaceAll(W$,"[scrubbed_ip]").replaceAll(B$,"[scrubbed_path]").replaceAll(H$,"[scrubbed_path]").replaceAll(G$,(r,o)=>`${o}[scrubbed_path]`);return Pb(n)?"[scrubbed_path]":n}function nn(e){let t={};for(let[n,r]of Object.entries(e))$b.test(n)?t[n]="[scrubbed]":typeof r=="string"?t[n]=ft(r,n):Array.isArray(r)?t[n]=r.map(o=>typeof o=="string"?ft(o,n):o&&typeof o=="object"?nn(o):o):r&&typeof r=="object"?t[n]=nn(r):t[n]=r;return t}function X$(e){for(let n of["filename","absPath","abs_path","module"]){let r=e[n];typeof r=="string"&&(e[n]=ft(r,n))}let t=e.context_line;typeof t=="string"&&(e.context_line=ft(t,"context_line"));for(let n of["pre_context","post_context"]){let r=e[n];Array.isArray(r)&&(e[n]=r.map(o=>typeof o=="string"?ft(o,n):o))}e.vars&&typeof e.vars=="object"&&(e.vars=nn(e.vars)),e.data&&typeof e.data=="object"&&(e.data=nn(e.data))}var J$=z$(import.meta.url),Q$=()=>J$("@sentry/node"),Du,Lb=!1,Z$=Q$,ej="https://bf7ad2ec76c0051c2ee94e48e8bd6868@o4510603477712896.ingest.de.sentry.io/4511316775338064";function Pu(e){return/^\s*PmCliError:/.test(e)}function Lu(e){let t=e.trim().toLowerCase();return t.length===0?!1:Y$.some(n=>t.includes(n))}function tj(e){return e.logger!=="console"?!1:typeof e.message=="string"&&Lu(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(t=>typeof t.value=="string"&&Lu(t.value))}function nj(e){if(e.logger!=="console")return!1;let t=n=>typeof n=="string"&&/^\(node:\d+\) MaxListenersExceededWarning: Possible EventEmitter memory leak detected\./.test(n);return t(e.message)?!0:Array.isArray(e.exception?.values)&&e.exception.values.some(n=>t(n.value))}function rj(e){return!!(e.exception?.values?.some(t=>t.type==="PmCliError")||e.exception?.values?.some(t=>typeof t.value=="string"&&Pu(t.value))||e.logger==="console"&&typeof e.message=="string"&&Pu(e.message))}function jb(e){return e.category==="console"&&typeof e.message=="string"&&Pu(e.message)}function Ub(e){return e.category==="console"&&typeof e.message=="string"&&Lu(e.message)}function oj(){return cc(import.meta.url,["../../.."])??"0.0.0"}function ij(){let e=process.env.SENTRY_ENVIRONMENT?.trim();return e&&e.length>0?e:process.env.VITEST||process.env.VITEST_WORKER_ID||process.env.NODE_ENV==="test"?"test":process.env.CI?"ci":"production"}var Mb=.2;function sj(){let e=process.env.SENTRY_TRACES_SAMPLE_RATE?.trim();if(!e)return Mb;let t=Number(e);return!Number.isFinite(t)||t<0||t>1?Mb:t}function aj(e){if(e.exception?.values){for(let t of e.exception.values)if(t.value&&(t.value=ft(t.value,"value")),t.stacktrace?.frames)for(let n of t.stacktrace.frames)X$(n)}}function zb(e){if(e.breadcrumbs)for(let t of e.breadcrumbs)t.message&&(t.message=ft(t.message)),t.data&&typeof t.data=="object"&&(t.data=nn(t.data))}function qb(e){if(e.contexts)for(let[t,n]of Object.entries(e.contexts))n&&typeof n=="object"&&(e.contexts[t]=nn(n))}function Fb(e,t){let n=e,r=n[t];r&&typeof r=="object"&&(n[t]=nn(r))}var cj=e=>{if(rj(e)||tj(e))return null;nj(e)&&(e.level="warning",e.tags={...e.tags,"pm.diagnostic_class":"node_runtime_warning"}),e.message&&(e.message=ft(e.message,"message")),e.transaction&&(e.transaction=ft(e.transaction,"transaction")),aj(e),zb(e),Fb(e,"extra"),qb(e);for(let t of["request","user","tags"])Fb(e,t);return e},lj=e=>(e.breadcrumbs&&(e.breadcrumbs=e.breadcrumbs.filter(t=>!jb(t)&&!Ub(t)),zb(e)),qb(e),e),dj=e=>jb(e)||Ub(e)?null:(e.message&&(e.message=ft(e.message,"message")),e.data&&typeof e.data=="object"&&(e.data=nn(e.data)),e);async function uj(){if(Lb)return Du;if(Lb=!0,q$())return;let e=Z$();Du=e;let t=process.env.SENTRY_DSN?.trim()||ej,n=oj();return e.init({dsn:t,release:`pm-cli@${n}`,environment:ij(),tracesSampleRate:sj(),enableLogs:!0,attachStacktrace:!0,normalizeDepth:6,shutdownTimeout:3e3,sendDefaultPii:!1,serverName:void 0,integrations:[e.extraErrorDataIntegration({depth:4}),e.captureConsoleIntegration({levels:["warn","error"]})],initialScope:{tags:{"cli.name":"pm-cli","cli.version":n,"runtime.node":process.version,"runtime.platform":process.platform,"runtime.arch":process.arch}},beforeSend:cj,beforeSendTransaction:lj,beforeBreadcrumb:dj}),e}function Fn(){return Du}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var fj=new Set(["init","config","completion","completion-statuses","completion-tags","completion-types"]),pj=new Set(["list","list-all","list-open","list-in-progress","list-blocked","list-closed","list-canceled","list-draft","search","get","context","calendar","history","activity","aggregate","deps","contracts","stats"]),mj=new Set(["create","update","update-many","close-many","append","close","delete","restore","claim","release","comments","notes","learnings","files","docs","start-task","pause-task","close-task"]),_j=new Set(["test","test-all","test-runs","test-verify","trace-test","test-ping"]),gj=new Set(["health","validate","normalize","reindex","gc","telemetry","extension-doctor"]);function yj(e){return e.trim().replaceAll(/\s+/g," ").toLowerCase()}function Vb(e){let t=e?.trim().toLowerCase();return t&&t.length>0?t:void 0}var hj=[{code:"unknown_command",matches:e=>e.includes("unknown command")},{code:"unknown_option",matches:e=>e.includes("unknown option")},{code:"missing_required_option",matches:e=>e.includes("missing required options")||e.includes("missing required option")},{code:"missing_required_argument",matches:e=>e.includes("missing required argument")},{code:"no_update_fields",matches:e=>e.includes("no update flags provided")},{code:"ownership_conflict",matches:e=>e.includes("is assigned to")&&e.includes("use --force")},{code:"lock_conflict",matches:e=>e.includes("is locked")},{code:"terminal_state_conflict",matches:e=>e.includes("already terminal")&&e.includes("use --force")},{code:"tracker_not_initialized",matches:e=>e.includes("tracker is not initialized")},{code:"item_not_found",matches:e=>e.includes(" not found")},{code:"close_through_update",matches:e=>e.includes('use "pm close <id> <text>" to close an item')||e.includes("invalid --status value")&&e.includes('"closed"')},{code:"invalid_argument_value",matches:e=>e.startsWith("invalid ")||e.includes(" must be ")||e.includes(" requires ")},{code:"invalid_command_usage",matches:e=>e.includes("either as positional")&&e.includes("not both")}],bj=new Map([[g.USAGE,"invalid_command_usage"],[g.NOT_FOUND,"item_not_found"],[g.CONFLICT,"lock_conflict"],[g.DEPENDENCY_FAILED,"dependency_failed"]]);function Pr(e){let t=yj(e),n=t.length>0?t.split(" "):["<unknown>"],r=n[0],o=n[n.length-1],i="other";return fj.has(r)?i="setup":pj.has(r)?i="query":mj.has(r)?i="mutation":_j.has(r)?i="testing":r==="extension"?i="extension":gj.has(r)&&(i="diagnostics"),{command_path:t.length>0?t:"<unknown>",command_root:r,command_leaf:o,command_depth:n.length,command_family:i}}function Mu(e){if(e.ok)return;let t=Vb(e.errorCode);if(t)return t;let n=(e.errorMessage??"").trim().toLowerCase();for(let o of hj)if(o.matches(n))return o.code;let r=Number.isFinite(e.exitCode)?Math.max(0,Math.trunc(e.exitCode)):void 0;return r!==void 0?bj.get(r)??"command_failed":"command_failed"}function Lr(e){if(e.ok)return"success";let t=Vb(e.errorCode);return t==="unknown_command"?"nonexistent_command":t==="unknown_option"?"invalid_option":t==="missing_required_option"?"missing_required_option":t==="missing_required_argument"?"missing_required_argument":t==="health_findings"?"health_findings":t==="validation_findings"?"validation_findings":e.errorCategory==="usage"?"invalid_usage":e.errorCategory==="validation"?"validation_failed":e.errorCategory==="conflict"?"conflict":e.errorCategory==="runtime"?"runtime_failed":"unknown_failed"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e6ba316-b067-51df-abeb-c3e3488a504d")}catch{}})();var Mr;function rn(e,t,n){if(n===void 0)return;let r=e;typeof r.setAttribute=="function"&&r.setAttribute(t,n)}function wa(e,t,n){typeof n=="string"&&n.trim().length>0&&e.setTag(t,n)}function wj(e,t,n){e.setTag("pm.ok",t),e.setTag("pm.command_ok",t),typeof n?.exit_code=="number"&&(e.setTag("pm.exit_code",String(n.exit_code)),e.setTag("pm.command_exit_code",String(n.exit_code))),wa(e,"pm.error_code",n?.error_code),wa(e,"pm.error_category",n?.error_category),wa(e,"pm.command_resolution",n?.command_resolution),wa(e,"pm.resolution_stage",n?.resolution_stage)}function Ej(e,t,n,r){rn(e,"pm.ok",t),rn(e,"pm.command_ok",t),rn(e,"pm.exit_code",n),rn(e,"pm.command_exit_code",n),rn(e,"pm.error_code",r?.error_code),rn(e,"pm.error_category",r?.error_category),rn(e,"pm.command_resolution",r?.command_resolution),rn(e,"pm.resolution_stage",r?.resolution_stage)}function vj(e,t,n,r){let o=Fn();if(!o)return;let i=Pr(e);o.setTag("pm.command",e),o.setTag("pm.command_root",i.command_root),o.setTag("pm.command_family",i.command_family),typeof r?.source_context=="string"&&r.source_context.trim().length>0&&o.setTag("pm.source_context",r.source_context);let s=t.map(a=>a.startsWith("--")?a.split("=")[0]:a);o.setContext("pm.command",{name:e,root:i.command_root,leaf:i.command_leaf,family:i.command_family,args:s,option_keys:Object.keys(n).sort(),source_context:r?.source_context,source_context_source:r?.source_context_source}),o.addBreadcrumb({category:"pm.command",message:`pm ${e}`,level:"info",data:{args:s,command_root:i.command_root,command_family:i.command_family,source_context:r?.source_context}})}function Tj(e){let t=Fn();t&&(Mr=t.startInactiveSpan({op:"pm.command",name:`pm ${e}`,forceTransaction:!0}))}function kj(e,t,n){if(!Mr)return;let r=e?"true":"false",o=typeof n?.exit_code=="number"?String(n.exit_code):void 0,i=Fn();i&&wj(i,r,n),Ej(Mr,r,o,n),Mr.setStatus(e?{code:1}:{code:2,message:t??"command_failed"}),Mr.end(),Mr=void 0}var Aj="unclassified_runtime_error";function Sj(e){let t=typeof e=="object"&&e!==null?e:void 0,n=typeof t?.exitCode=="number",r=n?Math.trunc(t?.exitCode):g.GENERIC_FAILURE;return{error_code:typeof t?.code=="string"&&t.code.length>0&&n?t?.code:Aj,exit_code:r}}function xj(e){let t=Sj(e);return{"pm.error_code":t.error_code,"pm.exit_code":String(t.exit_code)}}function Cj(e){if(!Ij(e))return;let t=Fn();if(!t)return;let n=xj(e);if(e instanceof Error){let r={};"exitCode"in e&&typeof e.exitCode=="number"&&(r.exit_code=e.exitCode),"context"in e&&typeof e.context=="object"&&(r.error_context=e.context),t.captureException(e,{extra:r,tags:n})}else t.captureException(new Error(String(e)),{tags:n})}function Oj(e){let t=Fn();if(!t)return;let n=e.command_resolution??Lr({ok:!1,errorCode:e.error_code,errorCategory:e.error_category}),r=e.resolution_stage??"unknown",o={"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":e.exit_code,"pm.error_message":e.error_message,"pm.command_resolution":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??""},i=t.logger;if(i&&typeof i.warn=="function"){i.warn("pm_cli_usage_error",o);return}t.captureMessage(`pm_cli_usage_error:${e.error_code}`,{level:"warning",tags:{"pm.command":e.command,"pm.error_code":e.error_code,"pm.error_category":e.error_category,"pm.exit_code":String(e.exit_code),"pm.command_resolution":n,"pm.resolution_stage":r,"pm.source_context":e.source_context??"unknown"},extra:o})}function Ij(e){if(e instanceof h||e instanceof Error&&e.name==="AbortError"&&/(?:ctrl\+[cd]|sigint|user[- ]initiated)/i.test(e.message))return!1;if(typeof e=="object"&&e!==null&&"exitCode"in e&&typeof e.exitCode=="number"){if(e instanceof Error&&e.name==="CommandError")return!1;let t=Math.trunc(e.exitCode);return!new Set([g.SUCCESS,g.USAGE,g.NOT_FOUND,g.CONFLICT]).has(t)}return!0}async function Rj(e=3e3){let t=Fn();if(t)try{await t.flush(e)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7775a1f2-5167-5853-a2c5-a44d46f8e80e")}catch{}})();var Nj=/\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/,Dj=/\bnpm_[A-Za-z0-9]{36}\b/,Pj=/\bxox[baprs]-(?=[A-Za-z0-9-]{20,80}\b)(?=[A-Za-z0-9-]*\d)[A-Za-z0-9-]{20,80}\b/,Lj=/-----BEGIN (?:[A-Z0-9]+ )?PRIVATE KEY-----/,Mj=/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,Gb=/\b(?:token|secret|password|passwd|api[_-]?key)\s*[:=]\s*["']?([A-Za-z0-9+/=_-]{24,})/gi,Fj=[{action:"append",history_scope:"item"},{action:"claim",history_scope:"item"},{action:"close",history_scope:"item"},{action:"close-many",history_scope:"item"},{action:"close-task",history_scope:"item"},{action:"comments",history_scope:"conditional"},{action:"config",history_scope:"conditional"},{action:"copy",history_scope:"item"},{action:"create",history_scope:"item"},{action:"delete",history_scope:"item"},{action:"deps",history_scope:"conditional"},{action:"discover",history_scope:"item"},{action:"docs",history_scope:"conditional"},{action:"files",history_scope:"conditional"},{action:"focus",history_scope:"conditional"},{action:"gc",history_scope:"conditional"},{action:"history-compact",history_scope:"history"},{action:"history-author-acknowledge",history_scope:"workspace"},{action:"history-redact",history_scope:"history"},{action:"history-repair",history_scope:"history"},{action:"init",history_scope:"workspace"},{action:"install",history_scope:"conditional"},{action:"learnings",history_scope:"conditional"},{action:"notes",history_scope:"conditional"},{action:"package",history_scope:"conditional"},{action:"pause-task",history_scope:"item"},{action:"plan",history_scope:"conditional"},{action:"profile",history_scope:"conditional"},{action:"release",history_scope:"item"},{action:"restore",history_scope:"item"},{action:"schema",history_scope:"conditional"},{action:"start-task",history_scope:"item"},{action:"templates",history_scope:"conditional"},{action:"test",history_scope:"conditional"},{action:"test-all",history_scope:"conditional"},{action:"update",history_scope:"item"},{action:"update-many",history_scope:"item"},{action:"upgrade",history_scope:"conditional"}],$u=new Map(Fj.map(e=>[e.action,e]));function $j(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);let n=0;for(let r of t.values()){let o=r/e.length;n-=o*Math.log2(o)}return n}function Fu(e,t="$",n=new WeakSet){return typeof e=="string"?[{path:t,value:e}]:typeof e!="object"||e===null?[]:n.has(e)?[]:(n.add(e),Array.isArray(e)?e.flatMap((r,o)=>Fu(r,`${t}[${o}]`,n)):Object.entries(e).flatMap(([r,o])=>Fu(o,`${t}.${r}`,n)))}function Bb(e){let t=[];for(let n of Fu(e)){Nj.test(n.value)&&t.push({rule:"github_token",path:n.path}),Dj.test(n.value)&&t.push({rule:"npm_token",path:n.path}),Pj.test(n.value)&&t.push({rule:"slack_token",path:n.path}),Lj.test(n.value)&&t.push({rule:"private_key",path:n.path}),Mj.test(n.value)&&t.push({rule:"aws_access_key",path:n.path}),Gb.lastIndex=0;for(let r of n.value.matchAll(Gb)){let o=r[1];if($j(o)>=3.5){t.push({rule:"high_entropy_assignment",path:n.path});break}}}return t.filter((n,r,o)=>o.findIndex(i=>i.rule===n.rule&&i.path===n.path)===r)}function jj(e){let t=e.author.trim()||"unknown";if(e.settings.require_attributed_author&&t.toLowerCase()==="unknown")throw new h("Mutation author is required by workspace policy.",g.USAGE,{code:"mutation_author_required",required:"Pass --author <id>, set PM_AUTHOR, or configure author_default.",nextSteps:["Retry with --author <stable-agent-id>.","Set PM_AUTHOR for this agent session."]});if(e.settings.secret_guard==="off")return{author:t,findings:[],warnings:[],override_applied:!1};let n;try{n=Bb(e.payload)}catch{return{author:t,findings:[],warnings:["secret_guard_scan_failed_open"],override_applied:!1}}if(n.length===0)return{author:t,findings:n,warnings:[],override_applied:!1};let r=[...new Set(n.map(o=>o.rule))].sort().join(",");if(e.settings.secret_guard==="block"&&e.force!==!0)throw new h(`Mutation blocked by secret guard (${r}). No detected value was logged.`,g.CONFLICT,{code:"mutation_secret_guard_blocked",required:"Remove the credential-shaped content or retry with --force after explicit review.",nextSteps:["Replace the value with a secret-manager reference.","Use pm history-redact if equivalent content already entered history."],recovery:{recovery_mode:"compact",attempted_command:"pm <mutation> [REDACTED]",normalized_args:["[REDACTED]"],suggested_retry:"Remove credential-shaped content, then retry the mutation."}});return{author:t,findings:n,warnings:[`secret_guard_detected:${n.length}:rules=${r}`,...e.settings.secret_guard==="block"&&e.force===!0?["secret_guard_force_override"]:[]],override_applied:e.settings.secret_guard==="block"&&e.force===!0}}function Uj(e){return $u.has(e.trim().toLowerCase())}function zj(){return[...$u.keys()].sort((e,t)=>e.localeCompare(t))}function g9(e){return $u.get(e.trim().toLowerCase())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ad30a32-0f83-5473-b0a3-349e271d8378")}catch{}})();function qj(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function h9(e){return qj(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function Ea(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).size;return o/i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="dff9b113-2b29-5154-afbf-f191f2f556a6")}catch{}})();var Vj=/\b[a-z][a-z0-9]*-\d+(?:-[a-z0-9]+)*\b/giu;function ju(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Wb(e){return[...new Set(ju(e).match(/[\p{L}\p{N}]+/gu)??[])]}function Hb(e){let t=ju(e);return{normalized:t,tokens:Wb(t),issueCodes:[...new Set(t.match(Vj)?.map(n=>n.toLowerCase())??[])]}}function Gj(e,t){return Bj(Hb(e),Hb(t))}function Bj(e,t){if(e.normalized===t.normalized)return{score:1,reason:"exact_title"};let n=new Set(e.issueCodes);return t.issueCodes.some(r=>n.has(r))?{score:.99,reason:"issue_code"}:{score:Ea(e.tokens,t.tokens),reason:"title_token_jaccard"}}import Hj 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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}catch{}})();function va(e){return(e??"in_progress").trim().toLowerCase().replaceAll("-","_")}function Wj(e,t){return[e.updated_at,t].map(r=>({value:r,time:Date.parse(r??"")})).filter(r=>typeof r.value=="string"&&Number.isFinite(r.time)).sort((r,o)=>o.time-r.time)[0]?.value??e.updated_at}function Kb(e,t){let n=Math.max(1,Math.trunc(t.threshold_hours)),r=(t.now??new Date).getTime(),o=va(t.in_progress_status),i=[];for(let s of e){if(va(String(s.status))!==o||(s.assignee?.trim().length??0)>0)continue;let a=Wj(s,t.last_history_activity?.(s)),c=Date.parse(a);if(!Number.isFinite(c))continue;let l=Math.max(0,Math.floor((r-c)/36e5));l>=n&&i.push({id:s.id,last_activity_at:a,age_hours:l})}return i.sort((s,a)=>a.age_hours-s.age_hours||s.id.localeCompare(a.id)),{threshold_hours:n,count:i.length,items:i,remediation:"Claim active work with `pm claim <id>` or return abandoned work to open with `pm update <id> --status open`."}}async function Kj(e,t,n){let r=new Map;return await Promise.all(t.filter(o=>va(String(o.status))===va(n.in_progress_status)&&(o.assignee?.trim().length??0)===0).map(async o=>{let i;try{i=await Xe(Hj.join(e,"history",`${o.id}.jsonl`),o.id)}catch{return}let s=i.map(a=>a.ts).filter(a=>Number.isFinite(Date.parse(a))).sort((a,c)=>Date.parse(c)-Date.parse(a))[0];s&&r.set(o.id,s)})),Kb(t,{...n,last_history_activity:o=>r.get(o.id)})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var Yj=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"}),Xj=/&(?:lt|gt|quot|#39|amp);/g;function Jj(e){return typeof e!="string"||!e.includes("&lt;")&&!e.includes("&gt;")?e:e.replace(Xj,t=>Yj[t])}function Qj(e){return Uu(e,new WeakMap)}function Uu(e,t){if(typeof e=="string")return Jj(e);if(Array.isArray(e)){if(t.has(e))return t.get(e);let n=[];t.set(e,n);for(let r of e)n.push(Uu(r,t));return n}if(e!==null&&typeof e=="object"){if(!Zj(e))return e;if(t.has(e))return t.get(e);let n=e,r=Object.create(Object.getPrototypeOf(e));t.set(e,r);for(let[o,i]of Object.entries(n))Object.defineProperty(r,o,{value:Uu(i,t),enumerable:!0,writable:!0,configurable:!0});return r}return e}function Zj(e){let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0ce743d1-917a-5c96-b038-c95e3922bc48")}catch{}})();function e1(e){let t=null;return()=>(t??=e(),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]="868dfae8-2575-5d5f-8425-c7e68aefdc84")}catch{}})();function Yb(e){return e.split(/[\s,|]+/).map(t=>t.trim()).filter(t=>t.startsWith("--"))}function t1(e){return Yb(e)[0]??null}function n1(e,t){let n=t1(t);if(n===null)return!1;let r=o=>o.slice(2).replaceAll("-","_");return Yb(e).some(o=>!o.slice(2).includes("-")||n===o?!1:r(n)===r(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]="4ecab833-db06-5baa-bfe6-d28b4c97f85a")}catch{}})();function r1(e,t){if(e==null)return[];let n=t?.separators??/,/,o=e.split(n).map(a=>a.trim()).filter(a=>a.length>0),s=t?.unique!==!1?Array.from(new Set(o)):o;return t?.sort===!0?[...s].sort():s}import Xb from"node:fs/promises";import Ta 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]="4baf0ef3-2412-51cf-9ade-18b5c6e610d1")}catch{}})();function o1(e){return"json_markdown"}function Jb(e,t){return Ta.relative(e,t).replaceAll("\\","/")}function i1(e){return String(e).replaceAll(/[^a-zA-Z0-9._-]+/g,"_").slice(0,120)}async function s1(e,t,n="item_format:migrate",r=_e,o){if(t!=="toon")throw new Error("Only toon item-format migration targets are supported. Markdown item files are legacy read-only input.");let i=new Set,s=new Set,a=[],c=0,l=o1(t),d=Object.entries(r);for(let[u,f]of d){let p=Ta.join(e,f),_=[];try{_=await Xb.readdir(p)}catch{continue}let y=new Map;for(let E of _){let T=Ta.join(p,E),O=Hr(T);if(!O)continue;let P=Ta.extname(E),F=E.slice(0,E.length-P.length).trim();if(F.length===0)continue;let xe=y.get(F)??{};xe[O]=T,y.set(F,xe)}let b=[...y.keys()].sort((E,T)=>E.localeCompare(T));for(let E of b){let T=y.get(E);c+=1;let O=T[l];if(!O)continue;let P=T[t]??O,F=P===T[t]?t:l;try{let xe=await Xb.readFile(P,"utf8"),me=wn(xe,{format:F,schema:o,onWarning:Gf=>a.push(`item_format_migration_parse_warning:${E}:${Gf}`)}),et=Qn(e,u,E,t,r),Be=ho(me,{format:t,schema:o});await Y(et)!==Be&&(await L(et,Be),a.push(...await ye({path:et,scope:"project",op:n})),i.add(E)),await $r(O),s.add(Jb(e,O)),a.push(...await ye({path:O,scope:"project",op:`${n}:remove`})),i.add(E)}catch(xe){a.push(`item_format_migration_skipped:${Jb(e,P)}:${i1(xe)}`)}}}return{target_format:t,scanned:c,migrated:[...i].sort((u,f)=>u.localeCompare(f)),removed:[...s].sort((u,f)=>u.localeCompare(f)),warnings: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]="f280c1df-b134-57c3-91f6-cbf5a37e6e31")}catch{}})();var a1=new Set(["completed","superseded"]);function c1(e){return e!==void 0&&a1.has(e)}function l1(e){if(e.type.trim().toLowerCase()!=="plan")return!1;let t=e.plan_steps??[];return t.length>0&&t.every(n=>n.status==="completed")}import d1 from"node:readline/promises";import{stdin as u1,stdout as Qb}from"node:process";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();var f1="PM_TELEMETRY_PROMPT",Zb=new Set(["0","false","no","off"]),p1=new Set(["init","completion","completion-statuses","completion-tags","completion-types"]);function m1(e){return typeof e!="string"?!1:Zb.has(e.trim().toLowerCase())}function _1(e){if(typeof e!="string")return!1;let t=e.trim().toLowerCase();return t.length===0?!1:!Zb.has(t)}function g1(e,t){if(t.json===!0||t.quiet===!0||process.stdin.isTTY!==!0||process.stdout.isTTY!==!0||m1(process.env[f1])||_1(process.env.CI))return!0;let n=e.trim().toLowerCase();return n.length===0?!0:p1.has(n)}function y1(e){let t=e.trim().toLowerCase();return!(t==="n"||t==="no")}async function h1(e){let n=`pm telemetry helps improve reliability and usage diagnostics.
188
188
  It is enabled by default and can be changed anytime via:
189
189
  pm config global set telemetry-tracking --policy disabled
190
- Enable telemetry now? [${e?"Y/n":"y/N"}] `,r=c1.createInterface({input:l1,output:Xb});try{let o=await r.question(n);return o.trim().length===0?e:_1(o)}finally{r.close()}}async function y1(e,t){if(!m1(e,t))try{let n=It(process.cwd()),r=await ot(n);if(r.telemetry.first_run_prompt_completed)return;let o=await g1(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await Fo(n,r,"telemetry:first_run_prompt"),Xb.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
191
- `)}catch{}}import ut from"node:crypto";import{spawn as h1}from"node:child_process";import{mkdirSync as zu,rmSync as b1,statSync as cw}from"node:fs";import{mkdir as qu,readdir as w1,rm as Ku,stat as lw}from"node:fs/promises";import{request as E1}from"node:http";import{request as v1}from"node:https";import Yu from"node:os";import Pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var T1=Pe.join("runtime","telemetry","events.jsonl"),k1=Pe.join("runtime","telemetry","state.json"),A1=Pe.join("runtime","telemetry","otel-spans.jsonl"),S1=8,Qb=500,Sa=1,Zb=1,x1=100,C1=36e5,O1=3e4,ew=2e4,I1=1e3,R1=25e3,N1=864e5,xa=65536,dw=6,uw=20,fw=15,D1=8192,pw=[25,50,100,200],P1=3600*1e3,mw=6e4,L1=6e4,M1="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",F1="OTEL_EXPORTER_OTLP_ENDPOINT",$1="OTEL_SERVICE_NAME",j1="PM_TELEMETRY_DISABLED",U1="PM_NO_TELEMETRY",tw=new Set(["1","true","yes","on"]),z1="PM_TELEMETRY_OTEL_DISABLED",q1=new Set(["1","true","yes","on"]),V1="PM_TELEMETRY_INLINE_FLUSH",_w="PM_TELEMETRY_FLUSH_CHILD",G1="PM_TELEMETRY_SOURCE_CONTEXT",B1="PM_TELEMETRY_HTTP_TIMEOUT_MS",H1=globalThis.fetch,W1=["user","automation","test","dogfood"],nw=Promise.resolve(),rw=Promise.resolve();var K1=new Set(W1),Y1=new Set(["1","true","yes","on"]),Ca=ut.randomUUID(),X1=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],J1=new Set(["literal","literals","regex","regexes","replacement","replacements"]),gw="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",Q1=new RegExp(`\\b(${gw})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),Z1=new RegExp(`(--${gw})(=|\\s+)([^\\s,;]+)`,"giu"),eU=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,tU=/bearer\s+[a-z0-9._=-]+/giu,nU=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function Xo(e){return Pe.join(e,T1)}function Oa(e){return Pe.join(e,A1)}function rU(e){return Pe.dirname(Xo(e))}function yw(e){return Pe.join(e,k1)}function Xu(e){return Pe.join(e,"runtime","telemetry","flush.lock")}function hw(e){return Pe.join(e,"runtime","telemetry","flush.spawn.lock")}function oU(){return Pe.join(mt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function iU(){if(Gu(process.env[V1])||Gu(process.env[_w]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}async function sU(e){let t=await Y(yw(e));if(!t||t.trim().length===0)return{};try{let n=JSON.parse(t);return typeof n!="object"||n===null||Array.isArray(n)?{}:n}catch{return{}}}async function dt(e,t){try{let r={...await sU(e),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await P(yw(e),`${JSON.stringify(o,null,2)}
192
- `)}catch{}}function Vu(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return J1.has(t)||X1.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function bw(e){return e.replaceAll(Q1,(n,r,o)=>`${r}${o}[redacted]`).replaceAll(Z1,(n,r,o)=>`${r}${o}[redacted]`)}function ww(e){return e.replaceAll(eU,(t,n)=>`${n}[redacted_path]`)}function Ew(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function vw(e){if(!e)return!1;let t=e.charCodeAt(0);return Ew(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Tw(e){if(!e)return!1;let t=e.charCodeAt(0);return Ew(t)?!0:e==="."||e==="-"}function aU(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let n=e.slice(0,t),r=e.slice(t+1),o=r.lastIndexOf(".");if(o<=0||o===r.length-1||r.length-(o+1)<2)return!1;for(let i of n)if(!vw(i))return!1;for(let i of r)if(!Tw(i))return!1;return!0}function cU(e){let t="",n=0;for(;n<e.length;){let r=e.indexOf("@",n);if(r<0){t+=e.slice(n);break}let o=r-1;for(;o>=n&&vw(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&Tw(e[i]);)i+=1;let s=e.slice(o,i);if(aU(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function kw(e){return cU(e).replaceAll(tU,"bearer [redacted_token]").replaceAll(nU,"[redacted_ip]")}function lU(e){let t=kw(e),n=bw(t),r=ww(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function dU(e){let t=kw(e),n=bw(t),r=ww(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>2048?`${r.slice(0,2045)}...`:r}function ie(e,t="redacted"){return t==="max"?dU(e):lU(e)}function $n(e,t,n="redacted",r=0){if(t&&Vu(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return ie(e,n);if(typeof e=="number"||typeof e=="boolean")return e;if(r>=dw)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,uw).map(o=>$n(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=$n(a,s,n,r+1);return i}return String(e)}function Aw(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=ie(o,t);if(r){n.push("[redacted]"),r=!1;continue}if(i.startsWith("--")){let s=i.slice(2),a=s.indexOf("=");if(a>=0){let c=s.slice(0,a),l=s.slice(a+1);Vu(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${ie(l,t)}`);continue}if(Vu(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function Sw(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function Gu(e){return Y1.has((e??"").trim().toLowerCase())}function ow(){let e=process.env[B1]?.trim();if(!e)return ew;let t=Number(e);return Number.isFinite(t)?Math.min(R1,Math.max(I1,Math.trunc(t))):ew}async function xw(e,t,n){let r=new URL(e);if(globalThis.fetch!==H1){let i=new AbortController,s,a=new Promise((c,l)=>{s=setTimeout(()=>{i.abort(),l(new Error("telemetry_http_timeout"))},ow())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:n,signal:i.signal}),a])).status}finally{clearTimeout(s)}}let o=r.protocol==="https:"?v1:r.protocol==="http:"?E1:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=ow(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(n)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},l=o(r,c,d=>{d.once("error",s),d.once("end",()=>i(d.statusCode)),d.resume()});l.once("error",s),l.end(n)})}function Cw(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Ju(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Qu(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Ow(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?_i(e.errorCode):"unknown"}function Iw(e){let t=(process.env[G1]??"").trim().toLowerCase();if(K1.has(t))return{source_context:t,source_context_source:"env_override"};let n=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||n==="test")return{source_context:"test",source_context_source:"inferred"};let r=process.stdin.isTTY!==!0||process.stdout.isTTY!==!0,o=Gu(process.env.CI),i=e.json===!0||e.quiet===!0;return r||o||i?{source_context:"automation",source_context_source:"inferred"}:{source_context:"user",source_context_source:"inferred"}}function we(e,t){return ut.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Zu(e,t){let n=(ql()??"").trim(),r=bo({env:process.env,argv:process.argv}),o=r.harness!==void 0||r.model!==void 0;return e==="minimal"?{has_author_context:n.length>0,has_agent_context:o}:{...n.length>0?{author_context_hash:we(t,n)}:{},...r.harness?{agent_harness_hash:we(t,r.harness)}:{},...r.model?{agent_model_hash:we(t,r.model)}:{},...r.model_source?{agent_model_source:r.model_source}:{}}}function Bu(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=dw)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,uw).map(n=>Bu(n,t+1));if(typeof e=="object"){let n=e,r={},o=Object.keys(n).sort((i,s)=>i.localeCompare(s));for(let i of o)r[i]=Bu(n[i],t+1);return r}return String(e)}function Hu(e,t){return we(e,JSON.stringify(Bu(t)))}function Rw(e,t){return{hashes:t.map(n=>we(e,n)),digest:we(e,t.join("\0"))}}function Nw(e,t,n,r){let o=ie(typeof r=="string"?r:"","redacted"),i=typeof n=="string"&&n.length>0?n:"unknown_error",s=`${t}\0${i}\0${o}`;return we(e,s)}function ef(){return tw.has((process.env[j1]??"").trim().toLowerCase())||tw.has((process.env[U1]??"").trim().toLowerCase())}function uU(){if(q1.has((process.env[z1]??"").trim().toLowerCase()))return null;let e=(process.env[M1]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[F1]??"").trim();if(t.length===0)return null;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");return r.endsWith("/v1/traces")||(n.pathname=`${r.length===0?"":r}/v1/traces`),n.toString()}catch{return null}}function iw(e){let t=Date.parse(e),n=Number.isNaN(t)?Date.now():t;return`${BigInt(n)*1000000n}`}function qe(e,t){return{key:e,value:{stringValue:t}}}function fU(e,t){return{key:e,value:{boolValue:t}}}function sw(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function pU(e,t,n,r){if(typeof e.otel_traces_endpoint!="string"||e.otel_traces_endpoint.trim().length===0||typeof e.otel_trace_id!="string"||e.otel_trace_id.length===0||typeof e.otel_span_id!="string"||e.otel_span_id.length===0)return null;let o=ie((process.env[$1]??"").trim()),i=o.length>0?o:"pm-cli",s=Qu(t.exit_code,t.ok),a=Ju(t.error_code),c=Ow({ok:t.ok,errorCode:a,errorCategory:t.error_category}),l=[qe("pm.command",ie(e.command)),qe("pm.version",e.pm_version),qe("pm.source_context",e.source_context),qe("pm.source_context_source",e.source_context_source),qe("pm.installation_id",e.installation_id),qe("pm.session_id",Ca),qe("pm.pm_root_hash",e.pm_root_hash),qe("pm.cwd_hash",e.cwd_hash),fU("pm.ok",t.ok),sw("pm.exit_code",s),sw("pm.duration_ms",r)];typeof a=="string"&&l.push(qe("pm.error_code",a)),typeof c=="string"&&l.push(qe("pm.error_category",c)),typeof t.error=="string"&&t.error.trim().length>0&&l.push(qe("pm.error",ie(t.error)));let d={resourceSpans:[{resource:{attributes:[qe("service.name",i)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${ie(e.command)}`,kind:1,startTimeUnixNano:iw(e.started_at),endTimeUnixNano:iw(n),attributes:l,status:{code:t.ok?1:2,message:t.ok?"":ie(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:e.otel_traces_endpoint,payload:d}}function mU(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:ie(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(n=>$n(n,void 0,t))};if(typeof e=="object"){let n=e,r=Object.keys(n).sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of r.slice(0,25)){let a=$n(n[s],s,t),c=JSON.stringify(a).length;if(i+c>D1){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:r.length,keys_preview:r.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function _U(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=Dr(n.command),l=Rw(a,n.args),d=we(a,`${n.command}\0${n.args.join("\0")}`),u=Hu(a,n.options),f=Hu(a,n.global),p=Zu(t,a);return t==="minimal"?{capture_level:t,pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:l.digest,command_invocation_digest:d,command_options_digest:u,global_options_digest:f,...p}:{pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...p,command_args:Aw(n.args,t),command_args_hashes:l.hashes,command_args_digest:l.digest,command_invocation_digest:d,command_options:$n(n.options,void 0,t),command_options_digest:u,global_options:$n(n.global,void 0,t),global_options_digest:f,pm_root_hash:i,cwd_hash:s,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:we(a,Yu.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function gU(e){let{captureLevel:t,pmVersion:n,sourceContext:r,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:l,exitCode:d,errorCode:u,errorCategory:f,commandResolution:p,resolutionStage:_}=e,y=o.ok===!1?Nw(c,a,u,o.error):void 0,b=Zu(t,c);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:l,command_resolution:p,resolution_stage:_,ok:o.ok,exit_code:d,error_code:u,error_category:f,error:o.error?ie(o.error,"redacted"):void 0,error_fingerprint:y,duration_ms:i,...b}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:l,command_resolution:p,resolution_stage:_,...b,ok:o.ok,exit_code:d,error_code:u,error_category:f,error:o.error?ie(o.error,t):void 0,error_fingerprint:y,duration_ms:i,started_at:s,result_summary:mU(o.result,t)}}function yU(e){let{captureLevel:t,pmVersion:n,sourceContext:r,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:l,pmRootHash:d,cwdHash:u,installationId:f,errorCode:p,errorMessage:_,errorCategory:y,exitCode:b}=e,E=Rw(f,c),T=we(f,o),O=Hu(f,l),M=Nw(f,o,p,_),W=Zu(t,f);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:T,attempted_args_digest:E.digest,attempted_options_digest:O,error_code:p,error_category:y,exit_code:b,error:ie(_,"redacted"),error_fingerprint:M,...W}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...W,attempted_command:ie(o,t),attempted_command_digest:T,attempted_args:Aw(c,t),attempted_args_hashes:E.hashes,attempted_args_digest:E.digest,attempted_options:$n(l,void 0,t),attempted_options_digest:O,error_code:p,error_category:y,exit_code:b,error:ie(_,t),error_fingerprint:M,pm_root_hash:d,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:we(f,Yu.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function tf(e){let t=await ot(e),n=!1;return t.telemetry.installation_id.trim().length===0&&(t.telemetry.installation_id=ut.randomUUID(),n=!0),n&&await Fo(e,t,"telemetry:install_id"),{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days))}}async function nf(e,t){let r=JSON.stringify({client_schema_version:Zb,event:t,attempts:0});if(r.length>xa){let o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:r.length}}};r=JSON.stringify({client_schema_version:Zb,event:o,attempts:0})}await Jo(async()=>{await Ct(Xo(e),r)})}function Dw(e){let t=[];for(let n of e.split(`
193
- `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function Pw(e){let t=Math.min(O1*2**Math.max(e-1,0),C1);return new Date(Date.now()+t).toISOString()}function Lw(e){if(typeof e!="string"||e.trim().length===0)return!0;let t=Date.parse(e);return Number.isNaN(t)?!0:t<=Date.now()}function hU(e){return Lw(e.next_attempt_after)}function Mw(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*N1}function bU(e,t){let n=e.event?.occurred_at;if(typeof n!="string"||n.trim().length===0)return!1;let r=Date.parse(n);return Number.isNaN(r)?!1:r<t}function rf(e,t){let n=Mw(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>xa||bU(i,n)||i.attempts>=fw){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function Aa(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
190
+ Enable telemetry now? [${e?"Y/n":"y/N"}] `,r=d1.createInterface({input:u1,output:Qb});try{let o=await r.question(n);return o.trim().length===0?e:y1(o)}finally{r.close()}}async function b1(e,t){if(!g1(e,t))try{let n=Dt(process.cwd()),r=await at(n);if(r.telemetry.first_run_prompt_completed)return;let o=await h1(r.telemetry.enabled);r.telemetry.enabled=o,r.telemetry.first_run_prompt_completed=!0,await Fo(n,r,"telemetry:first_run_prompt"),Qb.write(`Telemetry ${o?"enabled":"disabled"} for this CLI install. Update any time with pm config global set telemetry-tracking --policy ${o?"disabled":"enabled"}.
191
+ `)}catch{}}import mt from"node:crypto";import{spawn as w1}from"node:child_process";import{mkdirSync as zu,rmSync as E1,statSync as dw}from"node:fs";import{mkdir as qu,readdir as v1,rm as Ku,stat as uw}from"node:fs/promises";import{request as T1}from"node:http";import{request as k1}from"node:https";import Yu from"node:os";import Pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var A1=Pe.join("runtime","telemetry","events.jsonl"),S1=Pe.join("runtime","telemetry","state.json"),x1=Pe.join("runtime","telemetry","otel-spans.jsonl"),C1=8,ew=500,Aa=1,tw=1,O1=100,I1=36e5,R1=3e4,nw=2e4,N1=1e3,D1=25e3,P1=864e5,Sa=65536,fw=6,pw=20,mw=15,L1=8192,_w=[25,50,100,200],M1=3600*1e3,gw=6e4,F1=6e4,$1="OTEL_EXPORTER_OTLP_TRACES_ENDPOINT",j1="OTEL_EXPORTER_OTLP_ENDPOINT",U1="OTEL_SERVICE_NAME",z1="PM_TELEMETRY_DISABLED",q1="PM_NO_TELEMETRY",rw=new Set(["1","true","yes","on"]),V1="PM_TELEMETRY_OTEL_DISABLED",G1=new Set(["1","true","yes","on"]),B1="PM_TELEMETRY_INLINE_FLUSH",yw="PM_TELEMETRY_FLUSH_CHILD",H1="PM_TELEMETRY_SOURCE_CONTEXT",W1="PM_TELEMETRY_HTTP_TIMEOUT_MS",K1=globalThis.fetch,Y1=["user","automation","test","dogfood"],ow=Promise.resolve(),iw=Promise.resolve();var X1=new Set(Y1),J1=new Set(["1","true","yes","on"]),xa=mt.randomUUID(),Q1=["token","secret","password","passwd","api_key","apikey","authorization","cookie","session","credentials","bearer"],Z1=new Set(["literal","literals","regex","regexes","replacement","replacements"]),hw="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",eU=new RegExp(`\\b(${hw})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),tU=new RegExp(`(--${hw})(=|\\s+)([^\\s,;]+)`,"giu"),nU=/(^|[\s"'`(=])\/(?:[^\s"'`),;]+)/g,rU=/bearer\s+[a-z0-9._=-]+/giu,oU=/\b(?:10\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|172\.(?:1[6-9]|2\d|3[01])\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)|192\.168\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d)\.(?:25[0-5]|2[0-4]\d|[01]?\d?\d))\b/g;function Xo(e){return Pe.join(e,A1)}function Ca(e){return Pe.join(e,x1)}function iU(e){return Pe.dirname(Xo(e))}function bw(e){return Pe.join(e,S1)}function Xu(e){return Pe.join(e,"runtime","telemetry","flush.lock")}function ww(e){return Pe.join(e,"runtime","telemetry","flush.spawn.lock")}function sU(){return Pe.join(yt(import.meta.url,["../../.."]),"dist","cli","telemetry-flush.js")}function aU(){if(Gu(process.env[B1])||Gu(process.env[yw]))return!0;let e=(process.env.NODE_ENV??"").trim().toLowerCase();return typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||e==="test"}async function cU(e){let t=await Y(bw(e));if(!t||t.trim().length===0)return{};try{let n=JSON.parse(t);return typeof n!="object"||n===null||Array.isArray(n)?{}:n}catch{return{}}}async function pt(e,t){try{let r={...await cU(e),...t},o=Object.fromEntries(Object.entries(r).filter(([,i])=>i!==void 0).sort((i,s)=>i[0].localeCompare(s[0])));await L(bw(e),`${JSON.stringify(o,null,2)}
192
+ `)}catch{}}function Vu(e){let t=e.trim().toLowerCase().replaceAll("-","_").replaceAll(/[^a-z0-9_]+/g,"_"),n=t.split("_").filter(r=>r.length>0);return Z1.has(t)||Q1.some(r=>t===r||t.endsWith(`_${r}`)||n.includes(r))}function Ew(e){return e.replaceAll(eU,(n,r,o)=>`${r}${o}[redacted]`).replaceAll(tU,(n,r,o)=>`${r}${o}[redacted]`)}function vw(e){return e.replaceAll(nU,(t,n)=>`${n}[redacted_path]`)}function Tw(e){let t=e>=65&&e<=90,n=e>=97&&e<=122,r=e>=48&&e<=57;return t||n||r}function kw(e){if(!e)return!1;let t=e.charCodeAt(0);return Tw(t)?!0:e==="."||e==="_"||e==="%"||e==="+"||e==="-"}function Aw(e){if(!e)return!1;let t=e.charCodeAt(0);return Tw(t)?!0:e==="."||e==="-"}function lU(e){let t=e.indexOf("@");if(t<=0||t!==e.lastIndexOf("@")||t===e.length-1)return!1;let n=e.slice(0,t),r=e.slice(t+1),o=r.lastIndexOf(".");if(o<=0||o===r.length-1||r.length-(o+1)<2)return!1;for(let i of n)if(!kw(i))return!1;for(let i of r)if(!Aw(i))return!1;return!0}function dU(e){let t="",n=0;for(;n<e.length;){let r=e.indexOf("@",n);if(r<0){t+=e.slice(n);break}let o=r-1;for(;o>=n&&kw(e[o]);)o-=1;o+=1;let i=r+1;for(;i<e.length&&Aw(e[i]);)i+=1;let s=e.slice(o,i);if(lU(s)){t+=e.slice(n,o),t+="[redacted_email]",n=i;continue}t+=e.slice(n,r+1),n=r+1}return t}function Sw(e){return dU(e).replaceAll(rU,"bearer [redacted_token]").replaceAll(oU,"[redacted_ip]")}function uU(e){let t=Sw(e),n=Ew(t),r=vw(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>512?`${r.slice(0,509)}...`:r}function fU(e){let t=Sw(e),n=Ew(t),r=vw(n),o=r.trim();return o.startsWith("/")&&o.length>1?"[redacted_path]":r.length>2048?`${r.slice(0,2045)}...`:r}function ie(e,t="redacted"){return t==="max"?fU(e):uU(e)}function $n(e,t,n="redacted",r=0){if(t&&Vu(t))return"[redacted]";if(e==null)return e;if(typeof e=="string")return ie(e,n);if(typeof e=="number"||typeof e=="boolean")return e;if(r>=fw)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,pw).map(o=>$n(o,void 0,n,r+1));if(typeof e=="object"){let o=e,i={};for(let[s,a]of Object.entries(o))i[s]=$n(a,s,n,r+1);return i}return String(e)}function xw(e,t="redacted"){let n=[],r=!1;for(let o of e){let i=ie(o,t);if(r){n.push("[redacted]"),r=!1;continue}if(i.startsWith("--")){let s=i.slice(2),a=s.indexOf("=");if(a>=0){let c=s.slice(0,a),l=s.slice(a+1);Vu(c)?n.push(`--${c}=[redacted]`):n.push(`--${c}=${ie(l,t)}`);continue}if(Vu(s)){n.push(`--${s}`),r=!0;continue}}n.push(i)}return n}function Cw(e){let t=e?.trim().toLowerCase();return t==="minimal"||t==="redacted"||t==="max"?t:"redacted"}function Gu(e){return J1.has((e??"").trim().toLowerCase())}function sw(){let e=process.env[W1]?.trim();if(!e)return nw;let t=Number(e);return Number.isFinite(t)?Math.min(D1,Math.max(N1,Math.trunc(t))):nw}async function Ow(e,t,n){let r=new URL(e);if(globalThis.fetch!==K1){let i=new AbortController,s,a=new Promise((c,l)=>{s=setTimeout(()=>{i.abort(),l(new Error("telemetry_http_timeout"))},sw())});try{return(await Promise.race([globalThis.fetch(e,{method:"POST",headers:t,body:n,signal:i.signal}),a])).status}finally{clearTimeout(s)}}let o=r.protocol==="https:"?k1:r.protocol==="http:"?T1:void 0;if(!o)throw new Error(`telemetry_http_protocol_unsupported_${r.protocol}`);return new Promise((i,s)=>{let a=sw(),c={method:"POST",headers:{...t,"content-length":Buffer.byteLength(n)},signal:AbortSignal.timeout(a),autoSelectFamilyAttemptTimeout:Math.min(5e3,a)},l=o(r,c,d=>{d.once("error",s),d.once("end",()=>i(d.statusCode)),d.resume()});l.once("error",s),l.end(n)})}function Iw(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:"0.0.0"}function Ju(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Qu(e,t){return Number.isFinite(e)?Math.max(0,Math.trunc(e)):t?0:1}function Rw(e){if(!e.ok)return typeof e.errorCategory=="string"&&e.errorCategory.trim().length>0?e.errorCategory:typeof e.errorCode=="string"&&e.errorCode.trim().length>0?_i(e.errorCode):"unknown"}function Nw(e){let t=(process.env[H1]??"").trim().toLowerCase();if(X1.has(t))return{source_context:t,source_context_source:"env_override"};let n=(process.env.NODE_ENV??"").trim().toLowerCase();if(typeof process.env.VITEST=="string"||typeof process.env.VITEST_WORKER_ID=="string"||n==="test")return{source_context:"test",source_context_source:"inferred"};let r=process.stdin.isTTY!==!0||process.stdout.isTTY!==!0,o=Gu(process.env.CI),i=e.json===!0||e.quiet===!0;return r||o||i?{source_context:"automation",source_context_source:"inferred"}:{source_context:"user",source_context_source:"inferred"}}function we(e,t){return mt.createHash("sha256").update(`${e}:${t}`).digest("hex")}function Zu(e,t){let n=(zl()??"").trim(),r=bo({env:process.env,argv:process.argv}),o=r.harness!==void 0||r.model!==void 0;return e==="minimal"?{has_author_context:n.length>0,has_agent_context:o}:{...n.length>0?{author_context_hash:we(t,n)}:{},...r.harness?{agent_harness_hash:we(t,r.harness)}:{},...r.model?{agent_model_hash:we(t,r.model)}:{},...r.model_source?{agent_model_source:r.model_source}:{}}}function Bu(e,t=0){if(e==null||typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(t>=fw)return"[depth_truncated]";if(Array.isArray(e))return e.slice(0,pw).map(n=>Bu(n,t+1));if(typeof e=="object"){let n=e,r={},o=Object.keys(n).sort((i,s)=>i.localeCompare(s));for(let i of o)r[i]=Bu(n[i],t+1);return r}return String(e)}function Hu(e,t){return we(e,JSON.stringify(Bu(t)))}function Dw(e,t){return{hashes:t.map(n=>we(e,n)),digest:we(e,t.join("\0"))}}function Pw(e,t,n,r){let o=ie(typeof r=="string"?r:"","redacted"),i=typeof n=="string"&&n.length>0?n:"unknown_error",s=`${t}\0${i}\0${o}`;return we(e,s)}function ef(){return rw.has((process.env[z1]??"").trim().toLowerCase())||rw.has((process.env[q1]??"").trim().toLowerCase())}function pU(){if(G1.has((process.env[V1]??"").trim().toLowerCase()))return null;let e=(process.env[$1]??"").trim();if(e.length>0)try{return new URL(e).toString()}catch{return null}let t=(process.env[j1]??"").trim();if(t.length===0)return null;try{let n=new URL(t),r=n.pathname.replace(/\/+$/,"");return r.endsWith("/v1/traces")||(n.pathname=`${r.length===0?"":r}/v1/traces`),n.toString()}catch{return null}}function aw(e){let t=Date.parse(e),n=Number.isNaN(t)?Date.now():t;return`${BigInt(n)*1000000n}`}function qe(e,t){return{key:e,value:{stringValue:t}}}function mU(e,t){return{key:e,value:{boolValue:t}}}function cw(e,t){return{key:e,value:{intValue:String(Math.max(0,Math.trunc(t)))}}}function _U(e,t,n,r){if(typeof e.otel_traces_endpoint!="string"||e.otel_traces_endpoint.trim().length===0||typeof e.otel_trace_id!="string"||e.otel_trace_id.length===0||typeof e.otel_span_id!="string"||e.otel_span_id.length===0)return null;let o=ie((process.env[U1]??"").trim()),i=o.length>0?o:"pm-cli",s=Qu(t.exit_code,t.ok),a=Ju(t.error_code),c=Rw({ok:t.ok,errorCode:a,errorCategory:t.error_category}),l=[qe("pm.command",ie(e.command)),qe("pm.version",e.pm_version),qe("pm.source_context",e.source_context),qe("pm.source_context_source",e.source_context_source),qe("pm.installation_id",e.installation_id),qe("pm.session_id",xa),qe("pm.pm_root_hash",e.pm_root_hash),qe("pm.cwd_hash",e.cwd_hash),mU("pm.ok",t.ok),cw("pm.exit_code",s),cw("pm.duration_ms",r)];typeof a=="string"&&l.push(qe("pm.error_code",a)),typeof c=="string"&&l.push(qe("pm.error_category",c)),typeof t.error=="string"&&t.error.trim().length>0&&l.push(qe("pm.error",ie(t.error)));let d={resourceSpans:[{resource:{attributes:[qe("service.name",i)]},scopeSpans:[{scope:{name:"pm-cli.telemetry",version:"1"},spans:[{traceId:e.otel_trace_id,spanId:e.otel_span_id,name:`pm.command.${ie(e.command)}`,kind:1,startTimeUnixNano:aw(e.started_at),endTimeUnixNano:aw(n),attributes:l,status:{code:t.ok?1:2,message:t.ok?"":ie(typeof t.error=="string"?t.error:"command_failed")}}]}]}]};return{endpoint:e.otel_traces_endpoint,payload:d}}function gU(e,t="redacted"){if(e==null)return{type:"nullish"};if(typeof e=="string")return{type:"string",value:ie(e,t)};if(typeof e=="number"||typeof e=="boolean")return{type:typeof e,value:e};if(Array.isArray(e))return{type:"array",length:e.length,sample:e.slice(0,5).map(n=>$n(n,void 0,t))};if(typeof e=="object"){let n=e,r=Object.keys(n).sort((s,a)=>s.localeCompare(a)),o={},i=0;for(let s of r.slice(0,25)){let a=$n(n[s],s,t),c=JSON.stringify(a).length;if(i+c>L1){o[s]="[preview_truncated]";break}i+=c,o[s]=a}return{type:"object",key_count:r.length,keys_preview:r.slice(0,50),preview:o}}return{type:typeof e,value:String(e)}}function yU(e){let{captureLevel:t,context:n,pmVersion:r,sourceContext:o,pmRootHash:i,cwdHash:s,installationId:a}=e,c=Pr(n.command),l=Dw(a,n.args),d=we(a,`${n.command}\0${n.args.join("\0")}`),u=Hu(a,n.options),f=Hu(a,n.global),p=Zu(t,a);return t==="minimal"?{capture_level:t,pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,command_args_digest:l.digest,command_invocation_digest:d,command_options_digest:u,global_options_digest:f,...p}:{pm_version:r,source_context:o.source_context,source_context_source:o.source_context_source,command_taxonomy:c,...p,command_args:xw(n.args,t),command_args_hashes:l.hashes,command_args_digest:l.digest,command_invocation_digest:d,command_options:$n(n.options,void 0,t),command_options_digest:u,global_options:$n(n.global,void 0,t),global_options_digest:f,pm_root_hash:i,cwd_hash:s,capture_level:t,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:we(a,Yu.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}function hU(e){let{captureLevel:t,pmVersion:n,sourceContext:r,outcome:o,durationMs:i,startedAt:s,command:a,installationId:c,commandTaxonomy:l,exitCode:d,errorCode:u,errorCategory:f,commandResolution:p,resolutionStage:_}=e,y=o.ok===!1?Pw(c,a,u,o.error):void 0,b=Zu(t,c);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:l,command_resolution:p,resolution_stage:_,ok:o.ok,exit_code:d,error_code:u,error_category:f,error:o.error?ie(o.error,"redacted"):void 0,error_fingerprint:y,duration_ms:i,...b}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:l,command_resolution:p,resolution_stage:_,...b,ok:o.ok,exit_code:d,error_code:u,error_category:f,error:o.error?ie(o.error,t):void 0,error_fingerprint:y,duration_ms:i,started_at:s,result_summary:gU(o.result,t)}}function bU(e){let{captureLevel:t,pmVersion:n,sourceContext:r,command:o,commandTaxonomy:i,commandResolution:s,resolutionStage:a,args:c,options:l,pmRootHash:d,cwdHash:u,installationId:f,errorCode:p,errorMessage:_,errorCategory:y,exitCode:b}=e,E=Dw(f,c),T=we(f,o),O=Hu(f,l),P=Pw(f,o,p,_),F=Zu(t,f);return t==="minimal"?{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,attempted_command_digest:T,attempted_args_digest:E.digest,attempted_options_digest:O,error_code:p,error_category:y,exit_code:b,error:ie(_,"redacted"),error_fingerprint:P,...F}:{capture_level:t,pm_version:n,source_context:r.source_context,source_context_source:r.source_context_source,command_taxonomy:i,command_resolution:s,resolution_stage:a,...F,attempted_command:ie(o,t),attempted_command_digest:T,attempted_args:xw(c,t),attempted_args_hashes:E.hashes,attempted_args_digest:E.digest,attempted_options:$n(l,void 0,t),attempted_options_digest:O,error_code:p,error_category:y,exit_code:b,error:ie(_,t),error_fingerprint:P,pm_root_hash:d,cwd_hash:u,runtime:{node:process.version,platform:process.platform,arch:process.arch,hostname_hash:we(f,Yu.hostname()),stdin_tty:process.stdin.isTTY===!0,stdout_tty:process.stdout.isTTY===!0}}}async function tf(e){let t=await at(e),n=!1;return t.telemetry.installation_id.trim().length===0&&(t.telemetry.installation_id=mt.randomUUID(),n=!0),n&&await Fo(e,t,"telemetry:install_id"),{installationId:t.telemetry.installation_id,endpoint:t.telemetry.endpoint,retentionDays:Math.max(1,Math.trunc(t.telemetry.retention_days))}}async function nf(e,t){let r=JSON.stringify({client_schema_version:tw,event:t,attempts:0});if(r.length>Sa){let o={...t,payload:{...t.payload,result_summary:{truncated:!0,reason:"payload_size_exceeded",original_bytes:r.length}}};r=JSON.stringify({client_schema_version:tw,event:o,attempts:0})}await Jo(async()=>{await Rt(Xo(e),r)})}function Lw(e){let t=[];for(let n of e.split(`
193
+ `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&o.event&&typeof o.event=="object"&&typeof o.attempts=="number"&&(o.client_schema_version===void 0||typeof o.client_schema_version=="number"&&Number.isFinite(o.client_schema_version))&&t.push(o)}catch{}}return t}function Mw(e){let t=Math.min(R1*2**Math.max(e-1,0),I1);return new Date(Date.now()+t).toISOString()}function Fw(e){if(typeof e!="string"||e.trim().length===0)return!0;let t=Date.parse(e);return Number.isNaN(t)?!0:t<=Date.now()}function wU(e){return Fw(e.next_attempt_after)}function $w(e){let t=Number.isFinite(e)?Math.max(1,Math.trunc(e)):1;return Date.now()-t*P1}function EU(e,t){let n=e.event?.occurred_at;if(typeof n!="string"||n.trim().length===0)return!1;let r=Date.parse(n);return Number.isNaN(r)?!1:r<t}function rf(e,t){let n=$w(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>Sa||EU(i,n)||i.attempts>=mw){o+=1;continue}r.push(i)}return{entries:r,prunedCount:o}}async function ka(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
194
194
  `),r=n.length>0?`${n}
195
- `:"";for(let o=0;;o+=1)try{await P(Xo(e),r);return}catch(i){let s=pw[o];if(s===void 0||!Fw(i))throw i;await $w(s)}}function Fw(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function $w(e){return new Promise(t=>{setTimeout(t,e)})}async function wU(e,t){let n={id:ut.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:oe(),attempts:0},r=JSON.stringify(n);r.length>xa||await Jo(async()=>{await Ct(Oa(e),r)})}function EU(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return ut.createHash("sha256").update(t).digest("hex").slice(0,32)}function jw(e){let t=[];for(let n of e.split(`
196
- `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=EU(o)),t.push(o))}catch{}}return t}function vU(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let n=Date.parse(e.enqueued_at);return Number.isNaN(n)?!1:n<t}function Uw(e,t){let n=Mw(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>xa||vU(i,n)||i.attempts>=fw){o+=1;continue}r.push(i)}if(r.length>Qb){let i=r.length-Qb;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function TU(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
195
+ `:"";for(let o=0;;o+=1)try{await L(Xo(e),r);return}catch(i){let s=_w[o];if(s===void 0||!jw(i))throw i;await Uw(s)}}function jw(e){if(typeof e!="object"||e===null||!("code"in e))return!1;let t=e.code;return t==="EACCES"||t==="EBUSY"||t==="EPERM"}function Uw(e){return new Promise(t=>{setTimeout(t,e)})}async function vU(e,t){let n={id:mt.randomUUID(),endpoint:t.endpoint,payload:t.payload,enqueued_at:oe(),attempts:0},r=JSON.stringify(n);r.length>Sa||await Jo(async()=>{await Rt(Ca(e),r)})}function TU(e){let t=JSON.stringify([e.endpoint,e.enqueued_at,e.payload]);return mt.createHash("sha256").update(t).digest("hex").slice(0,32)}function zw(e){let t=[];for(let n of e.split(`
196
+ `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=TU(o)),t.push(o))}catch{}}return t}function kU(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let n=Date.parse(e.enqueued_at);return Number.isNaN(n)?!1:n<t}function qw(e,t){let n=$w(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>Sa||kU(i,n)||i.attempts>=mw){o+=1;continue}r.push(i)}if(r.length>ew){let i=r.length-ew;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function AU(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
197
197
  `),r=n.length>0?`${n}
198
- `:"";for(let o=0;;o+=1)try{await P(Oa(e),r);return}catch(i){let s=pw[o];if(s===void 0||!Fw(i))throw i;await $w(s)}}async function aw(e,t,n,r){return Jo(async()=>{let o=await Y(Oa(e)),i=o===null?[]:jw(o),s=[];for(let c of i){if(n.has(c.id))continue;let l=r.get(c.id);s.push(l?{...c,attempts:l.attempts,next_attempt_after:l.next_attempt_after}:c)}let{entries:a}=Uw(s,t);return await TU(e,a),a.length})}async function kU(e,t){let n=await Y(Oa(e));if(n===null||n.trim().length===0){await dt(e,{pending_otel_spans:0});return}let r=jw(n),{entries:o,prunedCount:i}=Uw(r,t),s=o.filter(_=>Lw(_.next_attempt_after)).slice(0,S1);if(s.length===0){let _=i>0?await aw(e,t,new Set,new Map):o.length;await dt(e,{pending_otel_spans:_});return}let a=oe(),c=new Set,l=new Map,d=0,u;await Promise.all(s.map(async _=>{try{let y=await xw(_.endpoint,{"content-type":"application/json"},JSON.stringify(_.payload));if(y<200||y>=300)throw new Error(`local_otel_export_http_${y}`);c.add(_.id),d+=1}catch(y){u=y instanceof Error?ie(y.message,"redacted"):"local_otel_export_failed";let b=_.attempts+1;l.set(_.id,{attempts:b,next_attempt_after:Pw(b)})}}));let f=await aw(e,t,c,l),p={pending_otel_spans:f,last_otel_attempt_at:a};d>0&&(p.last_otel_success_at=a),u!==void 0?(p.last_otel_failure_at=a,p.last_otel_failure_error=u):f===0&&(p.last_otel_failure_at=void 0,p.last_otel_failure_error=void 0),await dt(e,p)}async function zw(e,t,n){try{await CU(e,t,n)}catch{}try{await kU(e,n)}catch{}}async function AU(e,t=P1){try{let n=rU(e),r=await w1(n,{withFileTypes:!0}),o=Date.now()-Math.max(0,t);await Promise.all(r.filter(i=>i.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(i.name)).map(async i=>{let s=Pe.join(n,i.name);(await lw(s)).mtimeMs<o&&await Ku(s,{force:!0})}))}catch{}}async function Jo(e){let t=rw.catch(()=>{}).then(e);return rw=t.catch(()=>{}),t}async function of(e){let t=await Y(Xo(e));return t===null||t.trim().length===0?[]:Dw(t)}async function SU(e,t,n){return Jo(async()=>{let r=await of(e),{entries:o}=rf(r,n),i=o.filter(s=>!t.has(s.event.event_id));return await Aa(e,i),i})}async function xU(e,t,n,r){return Jo(async()=>{let o=await of(e),{entries:i}=rf(o,r),s=i.map(a=>{if(!t.has(a.event.event_id))return a;let c=a.attempts+1;return{...a,attempts:c,last_attempt_at:n,next_attempt_after:Pw(c)}});return await Aa(e,s),s})}async function CU(e,t,n){await AU(e);let r=t.trim();if(r.length===0)return;let o=await Y(Xo(e));if(o===null||o.trim().length===0){await dt(e,{endpoint:r,queue_entries:0});return}let i=Dw(o);if(i.length===0){await dt(e,{endpoint:r,queue_entries:0});return}let{entries:s,prunedCount:a}=rf(i,n);if(s.length===0){await Aa(e,[]),await dt(e,{endpoint:r,queue_entries:0});return}let c=s.filter(p=>hU(p)).slice(0,x1);if(c.length===0){a>0&&await Aa(e,s),await dt(e,{endpoint:r,queue_entries:s.length});return}let l=new Set(c.map(p=>p.event.event_id)),d=oe(),u={"content-type":"application/json"},f=process.env.PM_TELEMETRY_INGEST_KEY?.trim();f&&(u["x-pm-telemetry-key"]=f);try{let p=await xw(r,u,JSON.stringify({schema_version:Sa,events:c.map(_=>_.event)}));if(p<200||p>=300)throw new Error(`telemetry_flush_http_${p}`)}catch(p){let _=await xU(e,l,d,n),y=p instanceof Error?ie(p.message,"redacted"):"telemetry_flush_failed";await dt(e,{endpoint:r,queue_entries:_.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:y});return}try{let p=await SU(e,l,n);await dt(e,{endpoint:r,queue_entries:p.length,last_attempted_flush_at:d,last_successful_flush_at:d,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(p){let _=p instanceof Error?ie(p.message,"redacted"):"telemetry_flush_failed",y=await of(e).catch(()=>s);await dt(e,{endpoint:r,queue_entries:y.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:_})}}async function OU(e){let t=Xu(e);await qu(Pe.dirname(t),{recursive:!0});try{return await qu(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await lw(t);return Date.now()-n.mtimeMs<mw?!1:(await Ku(t,{recursive:!0,force:!0}),await qu(t),!0)}catch{return!1}}function IU(e,t){try{return Date.now()-cw(e).mtimeMs<t}catch{return!1}}function qw(e){try{b1(e,{recursive:!0,force:!0})}catch{}}function RU(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function NU(e){try{return zu(e),!0}catch(t){if(RU(t)==="EEXIST"||!de(t))return!1}try{return zu(Pe.dirname(e),{recursive:!0}),zu(e),!0}catch{return!1}}function DU(e){if(IU(Xu(e),mw))return!1;let t=hw(e);try{if(Date.now()-cw(t).mtimeMs<L1)return!1;qw(t)}catch(n){if(!de(n))return!1}return NU(t)}function Wu(e){qw(hw(e))}async function PU(e,t,n){let r=await OU(e);if(Wu(e),!!r)try{await zw(e,t,n)}finally{try{await Ku(Xu(e),{recursive:!0,force:!0})}catch{}}}function sf(e,t,n){if(iU()){let r=nw,o=zw(e,t,n);nw=Promise.allSettled([r,o]).then(()=>{});return}try{if(!DU(e))return;let o=h1(process.execPath,[oU()],{detached:!0,stdio:"ignore",cwd:Yu.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[_w]:"1"}});o.on("error",()=>{Wu(e)}),o.unref()}catch{Wu(e)}}async function r9(e=It(process.cwd())){if(!ef())try{if(!(await ot(e)).telemetry.enabled)return;let{endpoint:n,retentionDays:r}=await tf(e);await PU(e,n,r)}catch{}}async function LU(e){if(ef()||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=It(process.cwd()),n=await ot(t);if(!n.telemetry.enabled)return null;let r=Sw(n.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await tf(t),a=Cw(e.pm_version),c=Iw(e.global),l=we(o,e.pm_root),d=we(o,process.cwd()),u=uU(),f=oe(),p={schema_version:Sa,event_id:ut.randomUUID(),event_type:"command_start",occurred_at:f,installation_id:o,session_id:Ca,command:e.command,payload:_U({captureLevel:r,context:e,pmVersion:a,sourceContext:c,pmRootHash:l,cwdHash:d,installationId:o})};await nf(t,p),sf(t,i,s);let _=Dr(e.command);return{started_at:f,started_at_ms:Date.now(),command:e.command,command_taxonomy:_,pm_version:a,source_context:c.source_context,source_context_source:c.source_context_source,installation_id:o,pm_root_hash:l,cwd_hash:d,endpoint:i,retention_days:s,global_pm_root:t,capture_level:r,otel_traces_endpoint:u??void 0,otel_trace_id:u?ut.randomBytes(16).toString("hex"):void 0,otel_span_id:u?ut.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function MU(e,t){if(e)try{let n=oe(),r=Math.max(0,Date.now()-e.started_at_ms),o=Ju(Mu({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),i=Ow({ok:t.ok,errorCode:o,errorCategory:t.error_category}),s=Qu(t.exit_code,t.ok),a=t.command_resolution??Pr({ok:t.ok,errorCode:o,errorCategory:i}),c=t.resolution_stage??"execute",l={schema_version:Sa,event_id:ut.randomUUID(),event_type:"command_finish",occurred_at:n,installation_id:e.installation_id,session_id:Ca,command:e.command,payload:gU({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:r,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:s,errorCode:o,errorCategory:i,commandResolution:a,resolutionStage:c})};await nf(e.global_pm_root,l);let d=pU(e,{...t,exit_code:s,error_code:o,error_category:i},n,r);d&&await wU(e.global_pm_root,d),sf(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function FU(e){if(!ef())try{let t=It(process.cwd()),n=await ot(t);if(!n.telemetry.enabled)return;let r=Sw(n.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await tf(t),a=Cw(e.pm_version),c=Iw(e.global),l=we(o,e.pm_root),d=we(o,process.cwd()),u=oe(),f=Ju(Mu({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),p=e.error_category??_i(f),_=Qu(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",b=Dr(y),E=e.command_resolution??Pr({ok:!1,errorCode:f,errorCategory:p}),T=e.resolution_stage??"unknown",O={schema_version:Sa,event_id:ut.randomUUID(),event_type:"command_error",occurred_at:u,installation_id:o,session_id:Ca,command:ie(y,"redacted"),payload:yU({captureLevel:r,pmVersion:a,sourceContext:c,command:y,commandTaxonomy:b,commandResolution:E,resolutionStage:T,args:e.args,options:e.options,pmRootHash:l,cwdHash:d,installationId:o,errorCode:f,errorCategory:p,exitCode:_,errorMessage:e.error_message})};await nf(t,O),sf(t,i,s)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d45775e5-6826-521b-80b3-429ed22947d9")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f56c4ef-58e1-5cf6-a10e-dfa29b9ad3e8")}catch{}})();var af=[{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"ids",keys:["ids"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"parent",keys:["parent"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"limit",keys:["limit"]},{target:"offset",keys:["offset"]},{target:"after",keys:["after"]},{target:"fields",keys:["fields"]},{target:"sort",keys:["sort"]},{target:"order",keys:["order"]},{target:"treeDepth",keys:["treeDepth","tree_depth"]}],Ia=[{target:"mode",keys:["mode"]},{target:"matchMode",keys:["matchMode","match_mode"]},{target:"minScore",keys:["minScore","min_score"]},{target:"semanticWeight",keys:["semanticWeight","semantic_weight"]},{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"assignee",keys:["assignee"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"fields",keys:["fields"]},{target:"limit",keys:["limit"]},{target:"after",keys:["after"]}],$U=[{target:"view",keys:["view"]},{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"status",keys:["status"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"include",keys:["include"]},{target:"recurrenceLookaheadDays",keys:["recurrenceLookaheadDays","recurrence_lookahead_days"]},{target:"recurrenceLookbackDays",keys:["recurrenceLookbackDays","recurrence_lookback_days"]},{target:"occurrenceLimit",keys:["occurrenceLimit","occurrence_limit"]},{target:"format",keys:["format"]}],Ra=[{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit","maxItems","max_items"]},{target:"after",keys:["after"]},{target:"format",keys:["format"]},{target:"depth",keys:["depth"]},{target:"fields",keys:["fields"]},{target:"activityLimit",keys:["activityLimit","activity_limit"]},{target:"staleThreshold",keys:["staleThreshold","stale_threshold"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],Na=[{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit"]},{target:"blockedLimit",keys:["blockedLimit","blocked_limit"]},{target:"format",keys:["format"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],cf=[{target:"id",keys:["id"]},{target:"op",keys:["op"]},{target:"author",keys:["author"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]}];function At(e,t){for(let n of t.keys){let r=e[n];if(typeof r=="string")return r}}function Da(e,t){for(let n of t.keys)if(Object.hasOwn(e,n))return e[n]}function Pa(e,t){let n=[];for(let r of t.keys){let o=e[r];Array.isArray(o)&&n.push(...o.filter(i=>typeof i=="string"))}return n.length>0?n: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]="be7e506f-c48f-5dfb-9fed-ba1e74fa60ff")}catch{}})();var lf=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or pass title as the first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit item id (normalized with the configured id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Item type (built-ins plus any configured custom types)"},{target:"template",keys:["template"],option:"--template <value>",description:"Apply named create template defaults before explicit flags"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Create required-option policy mode: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Scheduling preset for Reminder|Meeting|Event: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Close reason when creating directly in a terminal status",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for a terminal imported item",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],df=lf.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),La=lf.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),uf=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by dependency id or exact row signature (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append linked test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0}],ff=uf.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Ma=uf.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88009976-e03f-5a67-b6fc-bf60240dde49")}catch{}})();function jU(e,t){let n=[];for(let{param:r,flag:o}of e){let i=`--${r.replace(/([a-z\d])([A-Z])/gu,"$1-$2").toLowerCase()}`,s=t.find(a=>a.flag===o);if(!s){n.push({code:"missing_cli_flag",parameter:r,flag:o,parameter_flag:i});continue}s.flag!==i&&!s.aliases?.includes(i)&&n.push({code:"missing_parameter_alias",parameter:r,flag:o,parameter_flag:i})}return{ok:n.length===0,parameter_count:e.length,cli_flag_count:t.length,findings:n}}function ce(e){return e.map(t=>({...t}))}var pf=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],Vw=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],UU=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Vw],Gw=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],zU=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],qU=[...pf,...Gw],Bw=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],VU=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Hw=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],mf=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...ce(pf),...ce(UU),{param:"ids",flag:"--ids"},...ce(Gw),...ce(VU),...ce(Bw),...ce(Hw),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],_f=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...ce(qU)],gf=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...ce(pf),...ce(Vw),...ce(zU),...ce(Bw),...ce(Hw),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Ww=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],Fa=ce(Ww),Kw=[{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],yf=ce(Kw),Yw=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],hf=ce(Yw),bf=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],wf=ce(bf),Ef=ce(bf),GU=[{param:"view",flag:"--view"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"status",flag:"--status"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"include",flag:"--include"},{param:"recurrenceLookaheadDays",flag:"--recurrence-lookahead-days"},{param:"recurrenceLookbackDays",flag:"--recurrence-lookback-days"},{param:"occurrenceLimit",flag:"--occurrence-limit"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"}],vf=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],Tf=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}],BU=[{param:"format",flag:"--format"},{param:"maxDepth",flag:"--max-depth"},{param:"collapse",flag:"--collapse"},{param:"summary",flag:"--summary"},{param:"nodeLimit",flag:"--node-limit"},{param:"edgeLimit",flag:"--edge-limit"},{param:"tokenBudget",flag:"--token-budget"},{param:"cursor",flag:"--cursor"},{param:"direction",flag:"--direction"},{param:"kind",flag:"--kind",repeatable:!0}],HU=[{param:"kind",flag:"--kind",repeatable:!0},{param:"maxDepth",flag:"--max-depth"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"direction",flag:"--direction"},{param:"maxPaths",flag:"--max-paths"},{param:"sample",flag:"--sample"},{param:"exemptIsolate",flag:"--exempt-isolate",repeatable:!0},{param:"exemptIsolateType",flag:"--exempt-isolate-type",repeatable:!0},{param:"saveBaseline",flag:"--save-baseline"},{param:"rebuild",flag:"--rebuild"},{param:"clear",flag:"--clear"},{param:"summary",flag:"--summary"}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4efc5934-7d1b-517b-8b5e-eb2fe14379f2")}catch{}})();var eE=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"],WU=["activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function v(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Xw(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var H=v("id","item_id",!0),Qo=v("id","item_id",!1),Zo=v("text","string",!1),ei=v("plan-id","item_id",!0),Jw=v("step","string",!0),KU=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],kf=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],YU={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},Un=[{command:"plan create",parent:"plan",action:"create",slots:[v("title","string",!1,{polymorphic:!0})],accepted_flags:KU,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[ei],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[ei],accepted_flags:kf,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(YU).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[ei,Jw],accepted_flags:kf,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[ei,Jw,v("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(e=>({command:`plan ${e}`,parent:"plan",action:e,slots:[ei],accepted_flags:kf,description:`${Xw(e)} for one Plan item.`,example:`pm plan ${e} pm-a1b2`})),...["list","show","put","remove"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[v("kind","string",!0),...e==="list"?[]:[v("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Xw(e)} assurance declarations by kind.`,example:e==="list"?"pm assurance list measurement":`pm assurance ${e} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[v("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[v("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[v("preset","string",e==="apply")],accepted_flags:["--author","--message","--owner"],description:e==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:e==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[v("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[v("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[v("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[v("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[v("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],XU=[...Un].sort((e,t)=>t.command.length-e.command.length),tE=new Map([["append",[H,Zo]],["assurance",[v("action","action",!0),v("kind","string",!1),v("id","string",!1)]],["beads import",[v("file","string",!1)]],["changelog export",[v("file","string",!1)]],["claim",[Qo]],["close",[H,Zo]],["close-task",[H,v("reason","string",!1)]],["comments",[H,Zo]],["completion",[v("shell","string",!1)]],["config",[v("scope","string",!1,{polymorphic:!0}),v("action","action",!1),v("key","string",!1),v("value","string",!1,{polymorphic:!0})]],["copy",[H]],["create",[v("type-or-title","string",!1,{polymorphic:!0}),v("title","string",!1)]],["delete",[H]],["deps",[H]],["docs",[H]],["event",[v("title","string",!0)]],["files",[H]],["files discover",[H]],["files lookup",[v("paths","string",!0,{variadic:!0})]],["focus",[Qo]],["get",[H]],["graph",[v("subcommand","action",!0),Qo,v("target","item_id",!1)]],["guide",[v("topic","string",!1)]],["history",[H]],["history-compact",[Qo]],["history-redact",[H]],["history-repair",[Qo]],["init",[v("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[H,v("reason","string",!1)]],["item reopen",[H,v("reason","string",!0)]],["learnings",[H,Zo]],["meet",[v("title","string",!0)]],["merge",[v("subcommand","action",!0),v("artifact","string",!1),v("base","string",!1),v("ours","string",!1),v("theirs","string",!1)]],["notes",[H,Zo]],["package",[v("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[v("target","string",!0)]],["package upgrade",[v("target","string",!1)]],["packages",[v("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[v("target","string",!0)]],["packages upgrade",[v("target","string",!1)]],["pause-task",[H]],["plan",[v("subcommand","action",!0),v("id","item_id",!1,{polymorphic:!0}),v("step","string",!1),v("new-order","integer",!1)]],["profile",[v("subcommand","action",!0),v("name","string",!1)]],["release",[H]],["remind",[v("title","string",!0)]],["restore",[H,v("target","string",!0)]],["schema",[v("subcommand","action",!0),v("name","string",!1)]],["search-advanced",[v("keywords","string",!0,{variadic:!0})]],["search",[v("keywords","string",!0,{variadic:!0})]],["start-task",[H]],["telemetry",[v("namespace-or-subcommand","action",!1,{polymorphic:!0}),v("subcommand","action",!1)]],["test",[H]],["update",[H]],["workspace snapshot",[v("action","action",!0),v("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("targets","string",!1,{variadic:!0})]])),["vcs abandon",[H]],["vcs create",[v("title","string",!0)]],["vcs merge",[H]],["vcs propose",[H]],["vcs ref-create",[v("name","string",!0)]],["vcs show",[H]]]);function jn(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function OK(e){let t=jn(e),n=za.find(o=>o.command===t);if(n)return n;let r=Zl(t)?.canonical;if(r)return za.find(o=>o.command===r)}function JU(e){let t=jn(e);return XU.find(n=>n.command===t||t.startsWith(`${n.command} `))}function IK(e){return`Applicable flags: ${e.length>0?e.join(", "):"none"}.`}function V(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var Ua=[...V("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...V("item","item","consolidation","pm-yql1",["append","claim","close","close-many","close-task","comments","copy","create","delete","docs","files","get","learnings","notes","pause-task","release","start-task","test","update","update-many"]),...V("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...V("list","list","target_noun","pm-pfqi",["list"]),...V("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...V("context","context","target_noun","pm-pbyu",["context"]),...V("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...V("search","search","target_noun","pm-pbyu",["search"]),...V("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...V("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...V("graph","graph","target_noun","pm-pbyu",["graph"]),...V("graph","graph show","consolidation","pm-yql1",["deps"]),...V("history","history","target_noun","pm-pbyu",["history"]),...V("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...V("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...V("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...V("workspace","workspace init","consolidation","pm-n7rr",["init"]),...V("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...V("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...V("package","package","package_owned","package:beads",["beads import"]),...V("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...V("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...V("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...V("ops","ops assurance","consolidation","pm-2tan",Un.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...V("plan","plan","target_noun","pm-pbyu",["plan"]),...V("plan","plan","target_noun","pm-2tan",Un.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...V("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...V("help","help","target_noun","pm-pbyu",["help"]),...V("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],za=[...new Set(Ua.map(({command:e})=>e))].map(e=>({command:e,slots:JU(e)?.slots??tE.get(e)??[]})),ja={nouns:eE,shared_verbs:WU,scope_before_verb:!0,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:!0,positional_shape_budget:21};function Qw(e,t){let n=new Set(t);return[...new Set(e)].filter(r=>!n.has(r)).map(r=>({code:"positional_signature_mismatch",command:r,detail:`Positional signature ${r} has no destination declaration.`}))}function QU(e){return e.map(({required:t,variadic:n,value_kind:r,polymorphic:o})=>`${t?"r":"o"}:${n?"v":"s"}:${r}:${o?"p":"m"}`).join("|")}function $a(e){return e.map(({name:t,required:n,variadic:r,value_kind:o,polymorphic:i})=>`${t}:${n?"r":"o"}:${r?"v":"s"}:${o}:${i?"p":"m"}`).join("|")}function Zw(e,t){let n=new Map;for(let{command:r}of e){let o=jn(r);n.set(o,(n.get(o)??0)+1)}return[...n.entries()].filter(([,r])=>r>1).map(([r,o])=>({code:"positional_signature_mismatch",command:r,detail:`${o} ${t} positional signatures exist for ${r}; exactly one is required.`}))}function RK(e,t={}){let n=t.declared??za,r=t.positionalShapeBudget??ja.positional_shape_budget,o=new Map(n.map(c=>[jn(c.command),c])),i=new Map(e.map(c=>[jn(c.command),c])),s=[...Zw(n,"declared"),...Zw(e,"observed"),...t.declared===void 0?[...Qw(tE.keys(),Ua.map(({command:c})=>c)),...Qw(Un.map(({command:c})=>c),Ua.map(({command:c})=>c))]:[]];for(let c of o.values()){let l=jn(c.command),d=i.get(l);d?$a(d.slots)!==$a(c.slots)&&s.push({code:"positional_signature_mismatch",command:c.command,detail:`Observed positional signature for ${c.command} differs from its declared SDK contract: observed=${$a(d.slots)||"<none>"}; declared=${$a(c.slots)||"<none>"}.`}):s.push({code:"missing_observed_signature",command:c.command,detail:`No observed positional signature exists for ${c.command}.`})}for(let c of i.values())o.has(jn(c.command))||s.push({code:"stale_observed_signature",command:c.command,detail:`Observed positional signature ${c.command} has no declaration.`});let a=new Set(n.map(({slots:c})=>QU(c))).size;return a>r&&s.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${a} exceeds budget ${r}.`}),s.sort((c,l)=>c.command!==l.command?c.command.localeCompare(l.command):c.code.localeCompare(l.code)),{ok:s.length===0,declared_command_count:n.length,observed_command_count:e.length,positional_shape_count:a,positional_shape_budget:r,findings:s}}function ZU(e,t,n){return e.flatMap(r=>{let o=t.get(r)??[];if(o.length===0){let s=r.indexOf(" "),a=s===-1?r:r.slice(0,s);return[{code:"missing_destination",spelling:r,message:`Command \`${r}\` has no destination census row.`,nearest_target:n.has(a)?a:`ops ${r}`}]}let i=o.length>1?[{code:"duplicate_destination",spelling:r,message:`Command \`${r}\` has ${o.length} destination rows.`,nearest_target:o[0].target}]:[];return o.reduce((s,a)=>(a.disposition==="keep_as_is"&&(a.reason?.trim().length??0)===0&&s.push({code:"missing_destination",spelling:r,message:`Command \`${r}\` is kept as-is without a documented reason.`,nearest_target:a.target}),n.has(a.noun)||s.push({code:"unknown_noun",spelling:r,message:`Command \`${r}\` names undeclared noun \`${a.noun}\`.`,nearest_target:a.target}),s),i)})}function ez(e,t){return t.filter(n=>n.disposition!=="package_owned"&&!e.has(n.command)).map(n=>({code:"stale_destination",spelling:n.command,message:`Destination row \`${n.command}\` is absent from live contracts.`,nearest_target:n.target}))}function tz(e,t){return e.filter(n=>!t.has(n.canonical)).map(n=>({code:"alias_target_missing",spelling:n.alias,message:`Alias \`${n.alias}\` targets missing canonical command \`${n.canonical}\`.`,nearest_target:n.canonical_argv.join(" ")}))}function NK(e,t=[],n=Ua){let r=[...new Set(e.map(d=>d.trim()))].filter(d=>d.length>0).sort((d,u)=>d.localeCompare(u)),o=new Set(r),i=new Set(eE),s=new Map;for(let d of n){let u=s.get(d.command)??[];u.push(d),s.set(d.command,u)}let a=[...ZU(r,s,i),...ez(o,n),...tz(t,o)],c=new Set(t.filter(d=>d.hidden).map(d=>d.alias)),l=new Set(r.filter(d=>!d.includes(" ")&&!c.has(d)&&!(s.get(d)??[]).some(u=>u.disposition==="package_owned"))).size;return l>ja.visible_top_level_ceiling&&a.push({code:"visible_surface_ceiling_exceeded",spelling:String(l),message:`Visible non-package top-level command count ${l} exceeds ceiling ${ja.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."}),{ok:a.length===0,command_count:r.length,destination_count:n.length,hidden_alias_count:t.filter(d=>d.hidden).length,visible_top_level_count:l,visible_top_level_ceiling:ja.visible_top_level_ceiling,findings: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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function zn(e){return[...new Set(Array.from(e,t=>t.trim()).filter(t=>t.length>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]="789faf62-dfbf-56ff-9412-55adc5c12d3d")}catch{}})();function Va(e){return e.startsWith("--")?`--${e.slice(2).replaceAll("_","-")}`:e}function ti(e){let t=new Map;for(let n of e){let r=Va(n.flag),o=t.get(r)??new Set;n.flag!==r&&o.add(n.flag);for(let i of n.aliases??[])i!==r&&o.add(i);t.set(r,o)}return e.map(n=>{let r=Va(n.flag);if(n.flag!==r)return n;let o=zn([...n.aliases??[],...t.get(r)]).filter(i=>i!==r);return o.length===0?n:{...n,aliases:o}})}function nz(e){let t=ti(e),n=new Set(t.map(r=>r.flag));return t.filter(r=>{let o=Va(r.flag);return r.flag===o||!n.has(o)})}var Ba=qc.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),rz=[...Ba,{flag:"--version"}],nE=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--has-notes"},{flag:"--no-notes"},{flag:"--has-learnings"},{flag:"--no-learnings"},{flag:"--has-files"},{flag:"--no-files"},{flag:"--filter-files-missing"},{flag:"--has-docs"},{flag:"--no-docs"},{flag:"--filter-docs-missing"},{flag:"--has-tests"},{flag:"--no-tests"},{flag:"--has-comments"},{flag:"--no-comments"},{flag:"--has-deps"},{flag:"--no-deps"},{flag:"--has-body"},{flag:"--empty-body"},{flag:"--has-linked-command"},{flag:"--no-linked-command"}],rE=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--filter-has-notes"},{flag:"--filter-no-notes"},{flag:"--filter-has-learnings"},{flag:"--filter-no-learnings"},{flag:"--filter-has-files"},{flag:"--filter-no-files"},{flag:"--filter-has-docs"},{flag:"--filter-no-docs"},{flag:"--filter-has-tests"},{flag:"--filter-no-tests"},{flag:"--filter-has-comments"},{flag:"--filter-no-comments"},{flag:"--filter-has-deps"},{flag:"--filter-no-deps"},{flag:"--filter-has-body"},{flag:"--filter-empty-body"},{flag:"--filter-has-linked-command"},{flag:"--filter-no-linked-command"},{flag:"--ids",list:!0},{flag:"--limit"},{flag:"--offset"}],Ha=If([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--status",list:!0},{flag:"--all",value_type:"boolean"},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--today"},{flag:"--recent"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--ids",list:!0},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...nE,{flag:"--limit"},{flag:"--offset"},{flag:"--after"},{flag:"--no-truncate"},{flag:"--compact"},{flag:"--brief"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--sort"},{flag:"--order"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--include-body"},{flag:"--strict-read"},{flag:"--format"},{flag:"--stream"}],new Set(["--limit","--token-budget","--offset","--after","--no-truncate","--compact","--brief","--full","--fields","--include-body","--strict-read"])),oE=[{flag:"--group-by",list:!0},{flag:"--count"},{flag:"--completion"},{flag:"--sum"},{flag:"--avg"},{flag:"--include-unparented"},{flag:"--include_unparented"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0}],iE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body","--text"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function If(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var sE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note","--text"]},{flag:"--add-json"},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--since"},{flag:"--event-type"},{flag:"--include-meta"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],aE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning","--text"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],cE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--append-stable"},{flag:"--validate-paths"},{flag:"--scope"},{flag:"--limit"},{flag:"--offset"},{flag:"--no-truncate"},{flag:"--strict-read"},{flag:"--explain"},{flag:"--lines",value_name:"start:end"},{flag:"--decision-depth",value_name:"n",value_type:"number"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],lE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--validate-paths"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],dE=[{flag:"--id",value_name:"item-id"},{flag:"--limit"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--diff"},{flag:"--field"},{flag:"--verify"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--format"}],uE=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],fE=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],pE=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],mE=[{flag:"--event",repeatable:!0},{flag:"--all-actionable"},{flag:"--dry-run"},{flag:"--plan-fingerprint"},{flag:"--limit",value_type:"number"},{flag:"--attributed-author",aliases:["--attributed_author"]},{flag:"--reviewer"},{flag:"--reason"}],_E=[{flag:"--id",value_name:"item-id"},{flag:"--before"},{flag:"--ids",list:!0},{flag:"--all-over",value_type:"number"},{flag:"--closed"},{flag:"--all-streams"},{flag:"--min-entries",value_type:"number"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],gE=[{flag:"--description"},{flag:"--default-status",aliases:["--default_status"]},{flag:"--folder"},{flag:"--alias"},{flag:"--role"},{flag:"--order"},{flag:"--type"},{flag:"--commands"},{flag:"--cli-flag"},{flag:"--required"},{flag:"--required-on-create"},{flag:"--no-allow-unset"},{flag:"--required-types"},{flag:"--infer"},{flag:"--min-count"},{flag:"--apply",value_type:"boolean"},{flag:"--to"},{flag:"--migration-id",aliases:["--migration_id"]},{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],yE=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Rf=[{flag:"--title"},{flag:"--description"},{flag:"--scope"},{flag:"--parent"},{flag:"--related"},{flag:"--blocks"},{flag:"--blocked-by",aliases:["--blocked_by"]},{flag:"--harness"},{flag:"--mode"},{flag:"--resume-context",aliases:["--resume_context"]},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--priority"},{flag:"--status",short:"-s"},{flag:"--create-mode",aliases:["--create_mode"]},{flag:"--deadline"},{flag:"--estimate",aliases:["--estimated-minutes","--estimated_minutes"]},{flag:"--acceptance-criteria",aliases:["--acceptance_criteria","--ac"],repeatable:!0},{flag:"--definition-of-ready",aliases:["--definition_of_ready"]},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now",aliases:["--why_now"]},{flag:"--assignee"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-reason",aliases:["--blocked_reason"]},{flag:"--unblock-note",aliases:["--unblock_note"]},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps",aliases:["--repro_steps"]},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--affected-version",aliases:["--affected_version"]},{flag:"--fixed-version",aliases:["--fixed_version"]},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact",aliases:["--customer_impact"]},{flag:"--comment",repeatable:!0},{flag:"--note",repeatable:!0},{flag:"--learning",repeatable:!0},{flag:"--reminder",repeatable:!0},{flag:"--event",repeatable:!0},{flag:"--type-option",aliases:["--type_option"],repeatable:!0},{flag:"--body"},{flag:"--claim"},{flag:"--from-search",aliases:["--from_search"]},{flag:"--template"},{flag:"--step-title",aliases:["--step_title"]},{flag:"--step"},{flag:"--step-body",aliases:["--step_body"]},{flag:"--step-owner",aliases:["--step_owner"]},{flag:"--step-status",aliases:["--step_status"]},{flag:"--step-evidence",aliases:["--step_evidence"]},{flag:"--step-blocked-reason",aliases:["--step_blocked_reason"]},{flag:"--step-replacement",aliases:["--step_replacement"]},{flag:"--depends-on",aliases:["--depends_on"]},{flag:"--link"},{flag:"--link-kind",aliases:["--link_kind"]},{flag:"--link-note",aliases:["--link_note"]},{flag:"--promote-to-item-dep",aliases:["--promote_to_item_dep"]},{flag:"--allow-multiple-active",aliases:["--allow_multiple_active"]},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--decision-text",aliases:["--decision_text","--decision"]},{flag:"--decision-rationale",aliases:["--decision_rationale"]},{flag:"--decision-evidence",aliases:["--decision_evidence"]},{flag:"--discovery-text",aliases:["--discovery_text","--discovery"]},{flag:"--validation-text",aliases:["--validation_text","--validation"]},{flag:"--validation-command",aliases:["--validation_command"]},{flag:"--validation-expected",aliases:["--validation_expected"]},{flag:"--depth"},{flag:"--field"},{flag:"--fields",list:!0},{flag:"--steps"},{flag:"--materialize-type",aliases:["--materialize_type"]},{flag:"--materialize-parent",aliases:["--materialize_parent"]},{flag:"--materialize-tags",aliases:["--materialize_tags"]},{flag:"--author"},{flag:"--message"},{flag:"--force"}],hE=[{flag:"--id-prefix",aliases:["--prefix"]},{flag:"--preset"},{flag:"--type-preset"},{flag:"--defaults",short:"-y",aliases:["--yes"]},{flag:"--author"},{flag:"--agent-guidance"},{flag:"--with-packages"},{flag:"--no-merge-fence"},{flag:"--workspace"},{flag:"--force"},{flag:"--verbose"}],bE=[{flag:"--criterion"},{flag:"--clear-criteria"},{flag:"--format"},{flag:"--policy"},{flag:"--default-depth"},{flag:"--activity-limit"},{flag:"--stale-threshold-days"},{flag:"--section-hierarchy"},{flag:"--section-activity"},{flag:"--section-progress"},{flag:"--section-blockers"},{flag:"--section-files"},{flag:"--section-workload"},{flag:"--section-staleness"},{flag:"--section-tests"}],Nf=[{flag:"--init"},{flag:"--scaffold"},{flag:"--capability"},{flag:"--install"},{flag:"--uninstall"},{flag:"--explore"},{flag:"--list"},{flag:"--manage"},{flag:"--describe"},{flag:"--markdown"},{flag:"--output"},{flag:"--reload"},{flag:"--watch"},{flag:"--doctor"},{flag:"--catalog"},{flag:"--adopt"},{flag:"--adopt-all"},{flag:"--activate"},{flag:"--deactivate"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"},{flag:"--detail"},{flag:"--trace"},{flag:"--runtime-probe"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],Ae=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],Df=[...Ae,{flag:"--capability"}],Af=[...Nf,{flag:"--declarative"}],wE=[...Df,{flag:"--declarative"}],EE=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],vE=Ae,TE=Ae,kE=[...Ae,{flag:"--markdown"},{flag:"--output"}],AE=Ae,SE=Ae,xE=Ae,CE=[...Ae,{flag:"--dry-run"}],OE=[...Ae,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],IE=[...Ae,{flag:"--watch"}],RE=[...Ae,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],Sf=[...Ae,{flag:"--fields",list:!0}],NE=[...Ae,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],DE=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Pf=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}],oz=[{flag:"--mode"},{flag:"--progress"}],PE=[{flag:"--id",value_name:"item-id"},{flag:"--reason",value_name:"value"},{flag:"--close-reason",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--duplicate-of",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",aliases:["--expected_result","--expected"],value_name:"value"},{flag:"--actual-result",aliases:["--actual_result","--actual"],value_name:"value"},{flag:"--force",value_type:"boolean"}],LE=[{flag:"--filter-status",list:!0},{flag:"--filter-type"},{flag:"--filter-tag"},{flag:"--filter-priority"},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee"},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint"},{flag:"--filter-release"},...rE,{flag:"--reason"},{flag:"--completed-at"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--validate-close"},{flag:"--author"},{flag:"--message"},{flag:"--force"},{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"}],ME=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],FE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"},{flag:"--if-available"},{flag:"--next"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee-filter"},{flag:"--parent"},{flag:"--sprint"},{flag:"--release"},{flag:"--max-attempts"},{flag:"--include-decisions"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--explain-ranking",aliases:["--explain_ranking"]}],$E=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],jE=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],UE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],zE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],qE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],VE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],GE=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Lf=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...GE],BE=Lf,HE=[{flag:"--at"},{flag:"--text"},...GE],WE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-json"},{flag:"--remove"},{flag:"--remove-index",repeatable:!0},{flag:"--run"},{flag:"--match"},{flag:"--only-index"},{flag:"--only-last"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--acknowledge-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"},{flag:"--measure",list:!0},{flag:"--metric-below"},{flag:"--metric-diff"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],KE=[{flag:"--status"},{flag:"--limit"},{flag:"--offset"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"}],YE=[{flag:"--limit"}],XE=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],JE=[{flag:"--dry-run"},{flag:"--scope"}],QE=[{flag:"--include-empty"},{flag:"--storage"},{flag:"--metadata-coverage"},{flag:"--field-utilization"},{flag:"--by-assignee"},{flag:"--by-tag"},{flag:"--by-priority"},{flag:"--tag-prefix"},{flag:"--analytics"}],ZE=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],ev=[{flag:"--strict-directories"},{flag:"--require-merge-drivers"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--check-only"},{flag:"--check-telemetry"},{flag:"--no-refresh"},{flag:"--refresh-vectors"},{flag:"--verbose-stale-items"},{flag:"--verbose-author-events"},{flag:"--brief"},{flag:"--summary"},{flag:"--skip-vectors"},{flag:"--skip-integrity"},{flag:"--skip-drift"},{flag:"--full"}],tv=[{flag:"--check-metadata"},{flag:"--metadata-profile"},{flag:"--check-resolution"},{flag:"--check-lifecycle"},{flag:"--check-stale-blockers"},{flag:"--dependency-cycle-severity"},{flag:"--parent-cycle-severity"},{flag:"--check-files"},{flag:"--scan-mode"},{flag:"--include-pm-internals"},{flag:"--verbose-file-lists"},{flag:"--verbose-diagnostics"},{flag:"--all-affected-ids"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--fix-hints"},{flag:"--auto-fix"},{flag:"--dry-run"},{flag:"--fix-scope"},{flag:"--prune-missing"},{flag:"--check-history-drift"},{flag:"--check-command-references"},{flag:"--check-storage-integrity"},{flag:"--counts"},{flag:"--full"}],Mf=[{flag:"--definition",value_name:"json"},{flag:"--trigger",value_name:"value"},{flag:"--tree",value_name:"value"},{flag:"--gate",value_name:"id"},{flag:"--limit",value_name:"number"},{flag:"--dry-run"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--owner",value_name:"item-id"},{flag:"--apply",value_type:"boolean"},{flag:"--enforcement",value_name:"level"}],nv=[{flag:"--assignee"},{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--allow-unresolved-deps"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-by"},{flag:"--blocked-reason"},{flag:"--unblock-note"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--actual-result"},{flag:"--affected-version"},{flag:"--fixed-version"}],rv=[{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"}],ov=[{short:"-p",flag:"--priority"},{flag:"--type"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{flag:"--remove-tags",aliases:["--remove_tags"]},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--add-ac",aliases:["--add_ac"]},{flag:"--remove-ac",aliases:["--remove_ac"]}],xf=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{flag:"--id"},{short:"-d",flag:"--description"},{flag:"--type"},{flag:"--template"},{flag:"--create-mode"},{flag:"--create_mode"},{flag:"--schedule-preset"},{flag:"--schedule_preset"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},{flag:"--completed_at"},{short:"-p",flag:"--priority"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{short:"-b",flag:"--body"},{flag:"--body-file"},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--author"},{flag:"--message"},...nv,...rv,{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--fixed_version"},{flag:"--dep"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--reminder"},{flag:"--event"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--allow-duplicate",value_type:"boolean"}],iv=[{flag:"--transaction-id",value_name:"value"},{flag:"--stdin-json"},{flag:"--dry-run"},{flag:"--create-compensation",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--author",value_name:"value"}],sv=[{flag:"--id",value_name:"item-id"},{flag:"--transaction-id",value_name:"value",required:!0},{flag:"--reason",value_name:"value"},{flag:"--file",value_name:"value",repeatable:!0},{flag:"--doc",value_name:"value",repeatable:!0},{flag:"--test",value_name:"value",repeatable:!0},{flag:"--comment",value_name:"value",repeatable:!0},{flag:"--note",value_name:"value",repeatable:!0},{flag:"--learning",value_name:"value",repeatable:!0},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",value_name:"value"},{flag:"--actual-result",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--dry-run"},{flag:"--force"},{flag:"--author",value_name:"value"}],av=[{flag:"--id",value_name:"item-id"},{flag:"--status",value_name:"open|in_progress"},{flag:"--message",value_name:"value"},{flag:"--force"},{flag:"--author",value_name:"value"}],cv=[{flag:"--id",value_name:"item-id"},{flag:"--title",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--allow-duplicate",value_type:"boolean"}],lv=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],dv=[{flag:"--id",value_name:"item-id"},{flag:"--stdin-json"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},{flag:"--body-file"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},...ov,...nv,{flag:"--fixed_version"},...rv,{flag:"--author"},{flag:"--message"},{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--force"}],uv=[{flag:"--filter-status",list:!0},{flag:"--filter-type",list:!0},{flag:"--filter-tag",list:!0},{flag:"--filter-priority",list:!0},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee",list:!0},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint",list:!0},{flag:"--filter-release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...rE,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...ov,{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--repro_steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--expected_result"},{flag:"--expected"},{flag:"--actual-result"},{flag:"--actual_result"},{flag:"--actual"},{flag:"--affected-version"},{flag:"--affected_version"},{flag:"--fixed-version"},{flag:"--fixed_version"},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--allow-unresolved-deps"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Cf=[{flag:"--view"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--full-period"},{flag:"--full_period"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--status"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--include"},{flag:"--recurrence-lookahead-days"},{flag:"--recurrence-lookback-days"},{flag:"--occurrence-limit"},{flag:"--limit"},{flag:"--format"}],fv=[{flag:"--id"},{flag:"--op"},{flag:"--author"},{flag:"--from"},{flag:"--to"},{flag:"--limit"},{flag:"--unbounded"},{flag:"--compact"},{flag:"--raw"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--stream"}],pv=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{flag:"--cursor-mode",value_name:"batch|row"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--follow"},{flag:"--interval-ms",value_type:"number"}],Of=If([{flag:"--for",value_name:"intent"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit",aliases:["--max-items"]},{flag:"--after"},{flag:"--format"},{flag:"--depth"},{flag:"--fields",list:!0},{flag:"--section"},{flag:"--activity-limit"},{flag:"--stale-threshold"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--no-extension-health"},{flag:"--no-tags"}],new Set(["--limit","--after","--format","--fields","--section","--activity-limit","--stale-threshold","--explain-ranking","--explain_ranking","--no-extension-health","--no-tags"])),mv=[{flag:"--id",value_name:"item-id"},{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--depth"},{flag:"--full",value_type:"boolean"},{flag:"--fields",list:!0},{flag:"--at"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--format"}],_v=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],gv=[{flag:"--id",value_name:"item-id"},{flag:"--format"},{flag:"--max-depth"},{flag:"--collapse"},{flag:"--summary"},{flag:"--full"},{flag:"--node-limit"},{flag:"--edge-limit"},{flag:"--token-budget"},{flag:"--cursor"},{flag:"--direction"},{flag:"--kind",list:!0}],yv=[{flag:"--kind",list:!0},{flag:"--max-depth"},{flag:"--limit"},{flag:"--after"},{flag:"--direction"},{flag:"--max-paths"},{flag:"--sample"},{flag:"--exempt-isolate",list:!0},{flag:"--exempt-isolate-type",list:!0},{flag:"--save-baseline"},{flag:"--rebuild"},{flag:"--clear"},{flag:"--summary"},{flag:"--full"}],hv=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],St=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],bv=[],wv=[{flag:"--for",value_name:"intent"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit"},{flag:"--blocked-limit"},{flag:"--blocked_limit"},{flag:"--ready-only"},{flag:"--ready_only"},{flag:"--format"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]}],Ev=If([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--mode"},{flag:"--semantic"},{flag:"--hybrid"},{flag:"--match-mode"},{flag:"--min-score"},{flag:"--count"},{flag:"--semantic-weight"},{flag:"--include-linked"},{flag:"--title-exact"},{flag:"--phrase-exact"},{flag:"--highlight"},{flag:"--compact"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--format"},{flag:"--limit"},{flag:"--after"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--assignee",list:!0},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--parent"},...nE],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),vv=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Tv=[{flag:"--eager-tags"}];function qa(e){let t=new Map;for(let n of[...Ba,...e]){let r=Va(n.flag),o=t.get(r),{aliases:i,...s}=n,a=zn([...i??[],...n.flag===r?[]:[n.flag]]).filter(d=>d!==r),c={...s,flag:r,...a.length>0?{aliases:a}:{}},l=zn([...o?.aliases??[],...c.aliases??[]]);t.set(r,o===void 0?c:{...o,...c,...l.length>0?{aliases:l}:{}})}return ti([...t.values()])}var iz=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],sz=Ha.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),az=Ha.filter(e=>e.flag!=="--status");function Ga(e){let t=new Map;for(let n of e)for(let r of[n.flag,...n.aliases??[]]){let o=t.get(r)??[];o.push(n),t.set(r,o)}return t}var cz=Ga(Rf),lz=Ga(Mf),dz=new Map([["assurance",lz],["plan",cz],["workspace",Ga(bv)],["workspace snapshot",Ga(St)]]);function kv(e=Un){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=dz.get(n);if(!o)throw new Error(`Positional action ${t} has no flag-contract index for ${n}.`);let i=r.map(s=>{let a=o.get(s)??[];if(a.length!==1)throw new Error(`Positional action ${t} accepted flag ${s} does not resolve to exactly one ${n} flag contract.`);return a[0]});return[t,i]})}var uz=kv(),Av=new Map([["list",Ha],["list-all",az],...iz.map(e=>[e,sz]),["templates",xf],["cal",Cf],["ctx",Of],["test-runs-worker",XE],["init",hE],["config",bE],["extension",Nf],["package",Af],["packages",Af],["install",DE],["upgrade",Pf],["create",xf],["item mutate",iv],["item complete",sv],["item reopen",av],["copy",cv],["focus",lv],["aggregate",oE],["calendar",Cf],["context",Of],["get",mv],["guide",_v],["search",Ev],["next",wv],["eval",hv],["workspace",St],["workspace position",bv],["workspace snapshot",St],["workspace snapshot create",St],["workspace snapshot list",St],["workspace snapshot inspect",St],["workspace snapshot restore",St],["workspace snapshot delete",St],["history",dE],["history-redact",fE],["history-repair",pE],["history-author-acknowledge",mE],["history-compact",_E],["merge",uE],["schema",gE],["profile",yE],["plan",Rf],["activity",fv],["events",pv],["restore",$E],["update",dv],["update-many",uv],["close",PE],["close-many",LE],["delete",jE],["append",ME],["comments",iE],["notes",sE],["learnings",aE],["files",cE],["docs",lE],["deps",gv],["graph",yv],["test",WE],["test-all",KE],["telemetry",YE],["health",ev],["assurance",Mf],...uz,["validate",tv],["gc",JE],["stats",QE],["duplicates",ZE],["contracts",vv],["completion",Tv],["claim",FE],["release",UE],["start-task",zE],["pause-task",qE],["close-task",VE],["meet",Lf],["event",BE],["remind",HE]]),Sv=new Map([["install",EE],["uninstall",vE],["explore",TE],["manage",OE],["describe",kE],["reload",IE],["doctor",RE],["catalog",Sf],["list",Sf],["adopt",NE],["adopt-all",AE],["activate",SE],["deactivate",xE],["migrate",CE]]);function xv(e){return typeof e!="string"?"":e.trim().toLowerCase()}function fz(e){let t=xv(e);if(Av.has(t))return!0;let[n,r,...o]=t.split(/\s+/);return(n==="extension"||n==="package"||n==="packages")&&r!==void 0&&o.length===0&&(r==="init"||r==="scaffold"||Sv.has(r))}function pz(e,t){return t==="init"||t==="scaffold"?e==="extension"?Df:wE:Sv.get(t)??[]}function Ff(e){let t=xv(e);if(t.length===0)return qa([]);let[n,r,...o]=t.split(/\s+/);if((n==="extension"||n==="package"||n==="packages")&&r!==void 0&&o.length===0)return qa((n==="package"||n==="packages")&&r==="upgrade"?Pf:pz(n,r));let i=Av.get(t)??[];return qa(i)}function mz(e,t=!0){let r=ti(e).flatMap(i=>[i.short,i.flag,...i.aliases??[]]).filter(i=>!!i),o=t?[...r,...Ba.flatMap(i=>[i.short,i.flag,...i.aliases??[]]).filter(i=>!!i)]:r;return zn(o).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19a97f60-3b6e-5653-a652-02aebaf5afdd")}catch{}})();var Cv={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Ov={if:{required:["field"]}};Reflect.set(Ov,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var Iv={oneOf:[{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[Ov],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:Cv,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:Cv,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6968f481-8384-5e3b-8ac0-b0972d08eeb1")}catch{}})();var ni={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:Ao,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},ifAbsent:{type:"boolean"},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},Rv={assurance:{definition:Iv,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},_z=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],$f={subcommand:{type:"string",enum:[..._z]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...fp]},mode:{type:"string",enum:[...up]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Ai]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...pp]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},jf={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},ri={action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read linked commands).",examples:["schema","tracker","auto"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Return non-zero exit when health/validate/extension-doctor warnings are present."},failOnWarn:{description:"Alias for strictExit in health/validate/extension-doctor action payloads."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, or context outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Continuation cursor resuming a bounded listing or traversal after this previously returned id.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},Nv={assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, or risk.",examples:["list","run","derive","promote","risk"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{name:{description:"Custom item type name (add-type/remove-type/show), custom status id (show-status/add-status/remove-status), or custom field key (add-field/remove-field/show-field). Required for those subcommands.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b81a68c1-565d-56f6-a0eb-35d2c737bdb7")}catch{}})();var gz=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],yz=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],$v=new Set(["action","cwd","options",...Object.keys(ni).filter(e=>e!=="severity")]);function hz(e){let t=e.trim().toLowerCase(),n="";for(let r=0;r<t.length;r+=1){let o=t[r];if(o!=="-"&&o!=="_"){n+=o;continue}let i=r+1;for(;t[i]==="-"||t[i]==="_";)i+=1;let s=t[i];if(s!==void 0&&(s>="a"&&s<="z"||s>="0"&&s<="9")){n+=s.toUpperCase(),r=i;continue}n+=t.slice(r,i),r=i-1}return $v.has(n)?{field:e,property:n,owner:"mcp_tool_input",nested_path:`options.${n}`}:void 0}var bz={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},jv=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],JK=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(Ye.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Le(e){return zn(e)}var wz=Le([...yf.map(e=>e.param),...Fa.map(e=>e.param),"assignee","closeReason","completedAt"]),Uv=Le([...hf.map(e=>e.param),...Fa.map(e=>e.param),"force"]),Ez=Le([...wf.map(e=>e.param),...Uv.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),vz=Le([...Ef.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),Dv=Le([...Tf.map(e=>e.param),"past","section"]),Tz=Le([...vf.map(e=>e.param),"stream"]),Uf=Le([...mf.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),Mr=Uf.filter(e=>e!=="all"&&e!=="status"),kz=Uf.filter(e=>e!=="status"),en=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],Az=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],Sz=Le([..._f.map(e=>e.param),"count","completion","includeUnparented"]),xz=Le(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...gf.map(e=>e.param)]),Pv=Le(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),Se=["author","message","force"],zv=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],oi=["author","assignee","message","force"],Cz=["target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function Lv(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:Cz}}}var Mv={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},Fv={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Wa={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...Lv("extension"),...Lv("package"),"package-upgrade":Fv,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:Fv,create:{required:["title","description","type","status","priority","message"],optional:wz},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Uf,mutuallyExclusiveWhen:en},"list-all":{optional:kz,mutuallyExclusiveWhen:en},"list-draft":{optional:Mr,mutuallyExclusiveWhen:en},"list-open":{optional:Mr,mutuallyExclusiveWhen:en},"list-in-progress":{optional:Mr,mutuallyExclusiveWhen:en},"list-blocked":{optional:Mr,mutuallyExclusiveWhen:en},"list-closed":{optional:Mr,mutuallyExclusiveWhen:en},"list-canceled":{optional:Mr,mutuallyExclusiveWhen:en},aggregate:{optional:Sz},guide:{optional:["list","format","depth"]},context:{optional:Dv},ctx:{optional:Dv},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:xz,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:Mv,event:Mv,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...Pv,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...Se],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...Se],oneOfRequired:[["id"],["all"]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...Se]},schema:{required:["subcommand"],optional:["name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...jv,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...Se]},activity:{optional:Tz},restore:{required:["id","target"],optional:Se},update:{required:["id"],optional:Uv,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:Ez,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...zv,...Se]},"close-many":{optional:vz},delete:{required:["id"],optional:["dryRun",...Se]},append:{required:["id","body"],optional:Se},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...Se],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...Se],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...Se],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...Se],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...Se],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["add","addJson","remove","removeIndex","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...Se],mutuallyExclusive:[["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:Az},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...Pv,...oi],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:oi},"start-task":{required:["id"],optional:oi},"pause-task":{required:["id"],optional:oi},"close-task":{required:["id"],optional:["text","validateClose",...oi]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},Oz=Object.freeze(Object.fromEntries(Ye.map(e=>[e,Wa[e]])));function qv(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function Iz(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=ri[e];return{...n,description:r?.description??qv(e),...r?.examples?{examples:r.examples}:{}}}function Rz(e,t){if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(jf,t))return jf[t];let n=Nv[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:ri[t]}function Nz(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=Rz(e,t);return{...r,description:o?.description??qv(t),...o?.examples?{examples:o.examples}:{}}}function Dz(e,t){let n=Rv[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call($f,t)?$f[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:ni[t]}function Pz(e,t){let n={action:{const:e,description:ri.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=Dz(e,r);o&&(n[r]=Nz(e,r,o))}return n}function Lz(e,t){let n=t.flat();return t.map(r=>{let o=n.filter(i=>!r.includes(i));return{required:[...r],...o.length>0?{not:{anyOf:o.map(i=>({required:[i]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function Mz(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:{properties:{[n.property]:{const:n.value}},required:[n.property]},then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:{required:[n.property]},then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:Le(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function zf(e){if(!Object.prototype.hasOwnProperty.call(Wa,e))return;let t=Wa[e],n=bz[e]??[];return Le(["action",...gz,...rt(e)!==void 0?yz:[],...n,...t.required??[],...t.optional??[]])}function Vv(e){let t=Wa[e],n=Le(t.required??[]),r=zf(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:Pz(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=Lz(e,t.oneOfRequired));let i=Mz(t);return i.length>0&&(o.allOf=i),o}function Fz(e,t={}){let n=Vv(e),r={...n.properties};delete r.action;let o=[...n.anyOf??[],...n.oneOf??[]],i=(t.required??n.required.map(String)).filter(a=>a==="action"?!1:t.required===void 0?!0:!o.some(c=>c.required?.map(String).includes(a))),s={type:"object",additionalProperties:t.additionalProperties??!0,properties:{...r,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...t.properties},required:i};return n.anyOf!==void 0&&(s.anyOf=n.anyOf),n.oneOf!==void 0&&(s.oneOf=n.oneOf),n.allOf!==void 0&&(s.allOf=n.allOf),s}function Gv(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,o)=>n()[o],has:(r,o)=>o in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,o)=>{let i=Reflect.getOwnPropertyDescriptor(n(),o);return i&&(i.configurable=!0),i}})}var qf="4.10.1",Bv=qf.split(".")[0],Hv="1.4.0",$z=Gv(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Bv}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":qf,type:"object",oneOf:Ye.map(e=>Vv(e))}));function jz(e,t){let n=Iz(e,t);if(typeof n.type=="string")return n;let o=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(o){let{anyOf:a,...c}=n;return{...o,...c}}let{anyOf:i,...s}=n;return{...s,type:"string"}}function Uz(){let e={action:{type:"string",description:ri.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(ni).sort())e[t]=jz(t,ni[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Hv,type:"object",additionalProperties:!1,required:["action"],properties:e}}var zz=Gv(Uz);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4e5eed5-94c2-536a-8685-e20b735de480")}catch{}})();var qz=new Set(["--author","--follow","--help","--lean","--token-accounting","--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor","--output-row-contract","--no-changed-fields","--no-extensions","--no-pager","--pm-path","--profile","--quiet","--interval-ms"]),Vz=new Set([...$g,...jg]),Gz=new Set(["--brief","--format","--full","--full-changed-fields","--id-only","--no-truncate","--stream"]),Bz=new Set(["--body-file","--file","--stdin-json"]),Hz=new Set(["--global","--local","--project"]),Wz=new Set(["--activity-limit","--default-depth","--section-activity","--section-blockers","--section-files","--section-hierarchy","--section-progress","--section-staleness","--section-tests","--section-workload","--stale-threshold-days"]),Kz=new Set(["action","fullChangedFields","idOnly","path","pmExecutable","timeoutMs"]),Yz=new Set(["configAction","id","name","query","reason","subcommand","target","text"]),Xz={assurance:{id:"<id>",kind:"<kind>",preset:"[kind]|[id]",subcommand:"<action>"},event:{title:"<title>"},files:{lookupPath:"lookup <path...>"},meet:{title:"<title>"},"item-reopen":{id:"<id>",reason:"<reason>"},merge:{subcommand:"<subcommand>"},remind:{title:"<title>"},workspace:{name:"<name>",subcommand:"snapshot",snapshotAction:"<snapshot-action>",target:"<target>"}},Jz={assurance:{"--tree":"treeId","--owner":"owner","--apply":"apply","--enforcement":"enforcement"},init:{"--id-prefix":"idPrefix","--no-merge-fence":"mergeFence","--workspace":"workspace"},create:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},update:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},"update-many":{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},files:{"--note":"addNote"},docs:{"--note":"addNote"},comments:{"--full-history":"full"},notes:{"--file":"text","--full-history":"full"},learnings:{"--full-history":"full"},gc:{"--scope":"gcScope"},contracts:{"--action":"contractAction"},schema:{"--no-allow-unset":"allowUnset","--type":"fieldTypeScope"},"history-author-acknowledge":{"--event":"historyEvent","--all-actionable":"allActionable"},"extension-init":{"--capability":"capability"},"package-init":{"--capability":"capability"},"extension-install":{"--gh":"github"},"package-install":{"--gh":"github"},"extension-adopt":{"--gh":"github"},"package-adopt":{"--gh":"github"},extension:{"--gh":"github","--scaffold":"init"},package:{"--gh":"github","--scaffold":"init"},install:{"--gh":"github"}},Qz={"--pm-path":"path"},Kv={stats:{"--analytics":["measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]}};function Zz(e){return e.startsWith("extension-")?`extension ${e.slice(10)}`:e.startsWith("package-")?`package ${e.slice(8)}`:e.startsWith("item-")?`item ${e.slice(5)}`:e}function Wv(e,t){let n=Jz[e]?.[t]??Qz[t];return n!==void 0?n:t.replace(/^--/,"").replaceAll("_","-").replace(/-([a-z])/g,(r,o)=>o.toUpperCase())}function eq(e){let t=new Set;return e.filter(({flag:n})=>!n.startsWith("--")||t.has(n)?!1:(t.add(n),!0))}function tq(e,t){return t.find(({aliases:n})=>n?.includes(e))?.flag}function nq(e,t,n,r){let o=Kv[e]?.[t.flag];if(o!==void 0&&o.every(a=>r.has(a)))return{surface:"cli",input:t.flag,counterpart:o[0],disposition:"shared",reason:"The validated CLI JSON object fans out across strict SDK parameters."};let i=Wv(e,t.flag);if(r.has(i))return{surface:"cli",input:t.flag,counterpart:i,disposition:"shared",reason:"The CLI flag maps directly to a strict SDK action parameter."};let s=tq(t.flag,n);if(s!==void 0){let a=Wv(e,s);if(r.has(a))return{surface:"cli",input:t.flag,counterpart:a,disposition:"compatibility_alias",reason:`Compatibility spelling for ${s}.`}}return qz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_transport",reason:"CLI process transport is supplied by the in-process SDK host."}:Gz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_presentation",reason:"CLI rendering or mutation projection does not alter the SDK result envelope."}:Bz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_adapter",reason:"Local file or stdin adaptation is a CLI boundary concern."}:Wz.has(t.flag)?{surface:"cli",input:t.flag,counterpart:"key",disposition:"compatibility_alias",reason:"CLI config shorthand normalizes to the SDK configAction/key/value contract."}:Hz.has(t.flag)?{surface:"cli",input:t.flag,counterpart:"scope",disposition:"cli_scope_selector",reason:"Mutually exclusive CLI scope switches normalize to the SDK scope parameter."}:{surface:"cli",input:t.flag,counterpart:i,disposition:"unclassified",reason:"The CLI flag has no strict SDK parameter or approved boundary classification."}}function rq(e,t,n){let r=Object.entries(Kv[e]??{}).find(([s,a])=>a.includes(t)&&n.some(({input:c,disposition:l})=>c===s&&l==="shared"));if(r!==void 0)return{surface:"sdk",input:t,counterpart:r[0],disposition:"shared",reason:"The strict SDK parameter is reachable through the validated CLI JSON object."};let o=n.find(({counterpart:s,disposition:a})=>s===t&&(a==="shared"||a==="compatibility_alias"||a==="cli_scope_selector"));if(o!==void 0)return{surface:"sdk",input:t,counterpart:o.input,disposition:"shared",reason:"The strict SDK parameter is reachable from the CLI contract."};let i=Xz[e]?.[t];return i!==void 0?{surface:"sdk",input:t,counterpart:i,disposition:"shared",reason:"The strict SDK parameter maps to a canonical CLI positional argument."}:Kz.has(t)?{surface:"sdk",input:t,disposition:"sdk_transport",reason:"The SDK host supplies in-process transport and workspace selection."}:Yz.has(t)?{surface:"sdk",input:t,disposition:"cli_positional",reason:"The CLI accepts this SDK parameter as a positional command argument."}:{surface:"sdk",input:t,disposition:"sdk_native",reason:"The typed SDK exposes this structured input without a canonical CLI long flag."}}function oq(e={}){let t=e.actions??Ye,n=e.resolveFlags??Ff,r=e.resolveParameters??zf;return t.map(o=>{let i=Zz(o),s=eq(n(i)).filter(({flag:d})=>rt(o)!==void 0||!Vz.has(d)),a=new Set(r(o)??[]),c=s.map(d=>nq(o,d,s,a)),l=[...a].sort((d,u)=>d.localeCompare(u)).map(d=>rq(o,d,c));return{action:o,command:i,cli:c,sdk:l,unclassified:[...c,...l].filter(({disposition:d})=>d==="unclassified")}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="167b98d4-a5b5-581d-ac0a-17e8e3bfc490")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{Option as iq}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();async function EY(e,t,n,r,o){let i=Br(process.cwd(),r.path),s=await $e("command_result",{command:e,args:t,options:n,global:r,pm_root:i,result:o});return s.handled?s.result:o}function vY(e,t){for(let[n,r]of Object.entries(t))e.setOptionValueWithSource(n,r,"cli")}function Yv(e,t){let n=[],r=new Set;for(let o of t.keys){if(!Object.hasOwn(e,o))continue;let i=e[o];if(i!=null){if(typeof i=="string"){n.push(i);continue}if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))return;r.has(i)||(r.add(i),n.push(...i))}}return n.length>0?n.join("; "):void 0}var Vf=Symbol("pm.resolvedGlobalOptions");function sq(e){return typeof e=="object"&&e!==null?e:{}}function xe(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function TY(e,t){e[Vf]={...t}}function kY(e){delete e[Vf]}function qn(e,t){return typeof e[t]=="string"?e[t]:void 0}function AY(e){let t=aq(e),n=e[Vf];if(n)return{...n,...t.length>0?{command:t}:{}};let r=sq(e),o=typeof r.optsWithGlobals=="function"?r.optsWithGlobals():typeof r.opts=="function"?r.opts():{};return{json:o.json===!0?!0:void 0,quiet:!!o.quiet,noChangedFields:o.changedFields===!1,...o.fullChangedFields===!0?{fullChangedFields:!0}:{},idOnly:o.idOnly===!0,...o.lean===!0?{lean:!0}:{},...o.tokenAccounting===!0?{tokenAccounting:!0}:{},outputInclude:qn(o,"outputInclude"),outputLimit:qn(o,"outputLimit"),outputBudget:qn(o,"outputBudget"),outputSession:qn(o,"outputSession"),outputCursor:qn(o,"outputCursor"),...o.outputRowContract===!0?{outputRowContract:!0}:{},...o.outputFormat==="toon"||o.outputFormat==="json"?{outputFormat:o.outputFormat}:{},path:qn(o,"pmPath")??qn(o,"path"),noExtensions:o.extensions===!1,noPager:!!o.noPager,profile:!!o.profile,...t.length>0?{command:t}:{},...typeof o.author=="string"?{author:o.author}:{}}}function aq(e){let t=[],n=e;for(;n?.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}async function SY(e){if(e.json===!0)return e;let t=Br(process.cwd(),e.path);if(!await ee(ge(t)))return e;let n=await ot(t);return{...e,defaultOutputFormat:n.output.default_format}}function cq(e,t){let n=t??[];return n.push(e),n}function Ge(e,t,n){if(typeof n!="string")return;let r=n.trim();r.length!==0&&e.push(t,r)}function Ve(e,t,n){n===!0&&e.push(t)}function Vn(e,t,n){if(Array.isArray(n))for(let r of n){if(typeof r!="string")continue;let o=r.trim();o.length!==0&&e.push(t,o)}}function k(e,t){return e[t]===!0?!0:void 0}function xt(e,t){return e[t]===!1?!0:void 0}function xY(e,t){return typeof e[t]=="string"?e[t]:void 0}function lq(e,t,n,r=!1,o=void 0){let i=new iq(t,n).hideHelp();r&&i.argParser(o??cq),e.addOption(i)}function CY(e,t,n){for(let[r,o]of t)lq(e,r,o,n)}function Ka(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Xv(e,t){let n=Da(e,t);return typeof n=="string"||typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ya(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function OY(e,t){let n=["test",e,"--run","--json","--progress"];return Vn(n,"--add",t.add),Vn(n,"--add-json",t.addJson),Vn(n,"--remove",t.remove),Vn(n,"--remove-index",t.removeIndex),Ge(n,"--match",t.match),Ge(n,"--only-index",t.onlyIndex),Ve(n,"--only-last",t.onlyLast),Vn(n,"--measure",t.measure),Ge(n,"--metric-below",t.metricBelow),Ge(n,"--metric-diff",t.metricDiff),Jv(n,t),Ge(n,"--author",t.author),Ge(n,"--message",t.message),Ve(n,"--force",t.force),n}function Jv(e,t){Ge(e,"--timeout",t.timeout),Vn(e,"--env-set",t.envSet),Vn(e,"--env-clear",t.envClear),Ve(e,"--shared-host-safe",t.sharedHostSafe),Ge(e,"--pm-context",t.pmContext),Ve(e,"--override-linked-pm-context",t.overrideLinkedPmContext),Ge(e,"--workspace-context",t.workspaceContext),Ve(e,"--override-linked-workspace-context",t.overrideLinkedWorkspaceContext),Ve(e,"--allow-untrusted-linked-tests",t.allowUntrustedLinkedTests),Ve(e,"--fail-on-context-mismatch",t.failOnContextMismatch),Ve(e,"--fail-on-skipped",t.failOnSkipped),Ve(e,"--fail-on-empty-test-run",t.failOnEmptyTestRun),Ve(e,"--require-assertions-for-pm",t.requireAssertionsForPm),Ve(e,"--check-context",t.checkContext),Ve(e,"--auto-pm-context",t.autoPmContext)}function IY(e){let t=["test-all","--json","--progress"];return Ge(t,"--status",e.status),Ge(t,"--limit",e.limit),Ge(t,"--offset",e.offset),Jv(t,e),t}function dq(e){return e.join(",")}function RY(e,t={}){let n=s=>At(e,xe(df,s)),r=s=>Pa(e,xe(La,s)),o=n("type");if(t.requireType!==!1&&o===void 0)throw new h("Missing required option --type <value>. Why required: create resolves runtime schema fields/workflow from item type. Retry: add --type <built-in or configured custom type> (example: --type Task).",g.USAGE);let i={title:n("title"),description:n("description"),type:o,template:n("template"),createMode:n("createMode"),schedulePreset:n("schedulePreset"),status:n("status"),closeReason:n("closeReason"),completedAt:n("completedAt"),priority:n("priority"),tags:n("tags"),addTags:r("addTags"),body:n("body"),deadline:n("deadline"),estimatedMinutes:n("estimatedMinutes"),acceptanceCriteria:Yv(e,xe(La,"acceptanceCriteria")),definitionOfReady:n("definitionOfReady"),order:n("order"),rank:n("rank"),goal:n("goal"),objective:n("objective"),value:n("value"),impact:n("impact"),outcome:n("outcome"),whyNow:n("whyNow"),author:n("author"),message:n("message"),assignee:n("assignee"),parent:n("parent"),allowMissingParent:Ka(e,["allowMissingParent","allow_missing_parent"])===!0,allowUnresolvedDeps:Ka(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,allowDuplicate:k(e,"allowDuplicate")===!0,reviewer:n("reviewer"),risk:n("risk"),confidence:n("confidence"),sprint:n("sprint"),release:n("release"),blockedBy:n("blockedBy"),blockedReason:n("blockedReason"),unblockNote:n("unblockNote"),reporter:n("reporter"),severity:n("severity"),environment:n("environment"),reproSteps:n("reproSteps"),resolution:n("resolution"),expectedResult:n("expectedResult"),actualResult:n("actualResult"),affectedVersion:n("affectedVersion"),fixedVersion:n("fixedVersion"),component:n("component"),regression:e.regression===!0?"true":n("regression"),customerImpact:n("customerImpact"),dep:r("dep"),comment:r("comment"),note:r("note"),learning:r("learning"),file:r("file"),test:r("test"),doc:r("doc"),reminder:r("reminder"),event:r("event"),typeOption:r("typeOption"),field:r("field"),unset:r("unset"),clearDeps:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Ya(i,e),i}function NY(e){let t=o=>At(e,xe(ff,o)),n=o=>Pa(e,xe(Ma,o)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Yv(e,xe(Ma,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:Ka(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:k(e,"replaceDeps"),replaceTests:k(e,"replaceTests"),replaceFiles:k(e,"replaceFiles"),replaceDocs:k(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Ya(r,e),r}var uq=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","filterAcMissing","filterEstimatesMissing","filterEstimateMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","filterHasNotes","filterNoNotes","filterHasLearnings","filterNoLearnings","filterHasFiles","filterNoFiles","filterHasDocs","filterNoDocs","filterHasTests","filterNoTests","filterHasComments","filterNoComments","filterHasDeps","filterNoDeps","filterHasBody","filterEmptyBody","filterHasLinkedCommand","filterNoLinkedCommand","ids","limit","offset","dryRun","rollback","checkpoint"]);function DY(e){let t={};for(let[n,r]of Object.entries(e))uq.has(n)||(t[n]=r);return t}function L(e,t){let n=xe(af,t),r=At(e,n);if(r!==void 0)return r;for(let o of n.keys){let i=e[o];if(Array.isArray(i)){let s=i.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof i=="string")return i;if(typeof i=="number"&&Number.isFinite(i))return String(i)}}function Qv(e){let t=k(e,"filterFilesMissing"),n=k(e,"filterDocsMissing");return{filterReviewerMissing:k(e,"filterReviewerMissing"),filterRiskMissing:k(e,"filterRiskMissing"),filterConfidenceMissing:k(e,"filterConfidenceMissing"),filterSprintMissing:k(e,"filterSprintMissing"),filterReleaseMissing:k(e,"filterReleaseMissing"),hasNotes:k(e,"hasNotes"),hasLearnings:k(e,"hasLearnings"),hasFiles:k(e,"hasFiles"),hasDocs:k(e,"hasDocs"),hasTests:k(e,"hasTests"),hasComments:k(e,"hasComments"),hasDeps:k(e,"hasDeps"),hasBody:k(e,"hasBody"),hasLinkedCommand:k(e,"hasLinkedCommand"),noNotes:xt(e,"notes"),noLearnings:xt(e,"learnings"),noFiles:xt(e,"files")??t,filterFilesMissing:t,noDocs:xt(e,"docs")??n,filterDocsMissing:n,noTests:xt(e,"tests"),noComments:xt(e,"comments"),noDeps:xt(e,"deps"),emptyBody:k(e,"emptyBody"),noLinkedCommand:xt(e,"linkedCommand")}}function PY(e){let t={status:L(e,"status"),type:L(e,"type"),tag:L(e,"tag"),priority:L(e,"priority"),deadlineBefore:L(e,"deadlineBefore"),deadlineAfter:L(e,"deadlineAfter"),updatedAfter:L(e,"updatedAfter"),updatedBefore:L(e,"updatedBefore"),createdAfter:L(e,"createdAfter"),createdBefore:L(e,"createdBefore"),today:k(e,"today"),recent:k(e,"recent"),ids:L(e,"ids"),assignee:L(e,"assignee"),assigneeFilter:L(e,"assigneeFilter"),parent:L(e,"parent"),sprint:L(e,"sprint"),release:L(e,"release"),limit:L(e,"limit"),offset:L(e,"offset"),noTruncate:xt(e,"truncate"),includeBody:k(e,"includeBody"),strictRead:k(e,"strictRead"),compact:k(e,"compact"),brief:k(e,"brief"),full:k(e,"full"),fields:L(e,"fields"),sort:L(e,"sort"),order:L(e,"order"),tree:k(e,"tree"),treeDepth:L(e,"treeDepth"),filterAcMissing:k(e,"filterAcMissing"),filterEstimatesMissing:Ka(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:k(e,"filterResolutionMissing"),filterMetadataMissing:k(e,"filterMetadataMissing"),...Qv(e)};return Ya(t,e),t}function LY(e){return{groupBy:typeof e.groupBy=="string"?e.groupBy:void 0,count:e.count===!0?!0:void 0,completion:e.completion===!0?!0:void 0,sum:typeof e.sum=="string"?e.sum:void 0,avg:typeof e.avg=="string"?e.avg:void 0,includeUnparented:e.includeUnparented===!0||e.include_unparented===!0,status:typeof e.status=="string"?e.status:void 0,type:L(e,"type"),tag:L(e,"tag"),priority:L(e,"priority"),deadlineBefore:L(e,"deadlineBefore"),deadlineAfter:L(e,"deadlineAfter"),assignee:L(e,"assignee"),assigneeFilter:L(e,"assigneeFilter"),parent:L(e,"parent"),sprint:L(e,"sprint"),release:L(e,"release")}}function MY(e,t,n){if(rr(t),n.quiet)return;let r=Array.isArray(t.warnings)?t.warnings:[],o={type:"meta",command:e,count:t.count,now:t.now,filters:t.filters};if(r.length>0&&(o.warnings=r),!!bt(`${JSON.stringify(o)}
199
- `)){for(let i of t.items)if(!bt(`${JSON.stringify({type:"item",command:e,item:i})}
200
- `))return;bt(`${JSON.stringify({type:"end",command:e,count:t.count})}
201
- `)}}function FY(e,t,n){if(rr(e),n.quiet)return;let r={type:"meta",command:"activity",count:e.count,filters:{id:t.id??null,op:t.op??null,author:t.author??null,from:t.from??null,to:t.to??null,limit:t.limit??null}};if(!bt(`${JSON.stringify(r)}
202
- `))return;let o=e.compact&&e.compact_activity?e.compact_activity:e.activity??[];for(let i of o)if(!bt(`${JSON.stringify({type:"entry",command:"activity",entry:i})}
203
- `))return;bt(`${JSON.stringify({type:"end",command:"activity",count:e.count})}
204
- `)}function $Y(e){let t=l=>At(e,xe(Ia,l)),n=l=>{let d=Da(e,xe(Ia,l));if(typeof d=="string"||typeof d=="number"&&Number.isFinite(d))return d},r=t("fields"),o=e.compact===!0,i=e.full===!0,s=!o&&!i&&r===void 0,c={mode:e.semantic===!0?"semantic":e.hybrid===!0?"hybrid":t("mode"),matchMode:t("matchMode"),minScore:n("minScore"),count:k(e,"count"),semanticWeight:n("semanticWeight"),includeLinked:k(e,"includeLinked"),titleExact:k(e,"titleExact"),phraseExact:k(e,"phraseExact"),highlight:k(e,"highlight"),status:t("status"),type:t("type"),tag:t("tag"),priority:t("priority"),deadlineBefore:t("deadlineBefore"),deadlineAfter:t("deadlineAfter"),updatedAfter:t("updatedAfter"),updatedBefore:t("updatedBefore"),createdAfter:t("createdAfter"),createdBefore:t("createdBefore"),assignee:t("assignee"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),fields:r,compact:o||s?!0:void 0,full:k(e,"full"),...Qv(e)};return Ya(c,e),c}function jY(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0).join(" ");if(t.length===0)throw new h("Search query must not be empty",g.USAGE);return t}function UY(e){let t=r=>At(e,xe(cf,r)),n={id:t("id"),op:t("op"),author:t("author"),from:t("from"),to:t("to"),limit:t("limit"),compact:e.full===!0||e.provenance===!0?!1:e.compact===!0||e.raw===!0?!0:void 0,...e.raw===!0||e.compact===!0||e.full===!0?{raw:!0}:{},unbounded:k(e,"unbounded"),provenance:k(e,"provenance"),provenanceSummary:k(e,"provenanceSummary"),harness:Array.isArray(e.harness)?e.harness:void 0,agentInstance:Array.isArray(e.agentInstance)?e.agentInstance:void 0,provenanceFilter:Array.isArray(e.provenanceFilter)?e.provenanceFilter:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}var fq=new Set(["","rows","ndjson","jsonl","true","1","yes","on"]),pq=new Set(["false","off","none","0"]);function zY(e){if(e===!0)return!0;if(e===!1||e===void 0||e===null)return!1;if(typeof e=="string"){let t=e.trim().toLowerCase();if(fq.has(t))return!0;if(pq.has(t))return!1}throw new h("Activity --stream accepts rows|ndjson|jsonl (or no value)",g.USAGE)}function qY(e){let t=s=>At(e,xe(Ra,s)),n=s=>Xv(e,xe(Ra,s)),r=e.section,o=Array.isArray(r)?r.filter(s=>typeof s=="string"&&s.trim().length>0):typeof r=="string"&&r.trim().length>0?[r]:void 0,i={date:t("date"),from:t("from"),to:t("to"),past:e.past===!0?!0:void 0,type:t("type"),tag:t("tag"),priority:t("priority"),assignee:t("assignee"),assigneeFilter:t("assigneeFilter"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),format:t("format"),depth:t("depth"),fields:t("fields"),section:o&&o.length>0?o:void 0,activityLimit:t("activityLimit"),staleThreshold:t("staleThreshold"),tokenBudget:n("tokenBudget"),noExtensionHealth:e.extensionHealth===!1?!0:void 0,noTags:e.tags===!1?!0:void 0};for(let[s,a]of Object.entries(e))Object.hasOwn(i,s)||(i[s]=a);return i}function VY(e){let t=o=>At(e,xe(Na,o)),n=o=>Xv(e,xe(Na,o)),r={type:t("type"),tag:t("tag"),priority:n("priority"),assignee:t("assignee"),assigneeFilter:t("assigneeFilter"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),blockedLimit:t("blockedLimit"),readyOnly:e.readyOnly===!0||e.ready_only===!0?!0:void 0,format:t("format"),tokenBudget:n("tokenBudget")};for(let[o,i]of Object.entries(e))Object.hasOwn(r,o)||(r[o]=i);return r}function mq(e){if(!e||typeof e!="object")return[];let t=e,n=new Set,r=a=>{if(typeof a!="string")return;let c=a.trim();c.length!==0&&n.add(c)};r(t.id);let o=t.item;o&&typeof o=="object"&&r(o.id);let i=t.ids;if(Array.isArray(i))for(let a of i)r(a);let s=t.items;if(Array.isArray(s))for(let a of s)!a||typeof a!="object"||r(a.id);return[...n].sort((a,c)=>a.localeCompare(c))}async function GY(e,t){let n=Br(process.cwd(),e.path),r=await Nu(n,mq(t),{background:!Zd()});e.profile&&r.warnings.length>0&&Td(`profile:search_refresh_warnings=${dq(r.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]="13c02696-29a7-598e-888a-3502fd88bfbe")}catch{}})();export{_q as a,si as b,ee as c,Bf as d,de as e,Y as f,P as g,$r as h,Qe as i,ai as j,Ja as k,wq as l,ci as m,li as n,di as o,ui as p,fi as q,Wf as r,Me as s,pi as t,oT as u,iT as v,kq as w,_e as x,tc as y,aT as z,Qa as A,x as B,g as C,_i as D,h as E,F,lT as G,z as H,Xf as I,Cq as J,dT as K,Yf as L,Jf as M,uT as N,mT as O,_T as P,Dq as Q,oe as R,ft as S,np as T,ue as U,jq as V,PT as W,$T as X,jT as Y,zT as Z,qT as _,sc as $,ac as aa,Be as ba,e2 as ca,BT as da,jc as ea,cc as fa,cp as ga,hi as ha,mt as ia,lc as ja,JT as ka,Yn as la,lp as ma,Xn as na,bi as oa,Jn as pa,wi as qa,a2 as ra,c2 as sa,l2 as ta,vi as ua,Ti as va,d2 as wa,u2 as xa,f2 as ya,p2 as za,ki as Aa,Ur as Ba,dc as Ca,up as Da,Ai as Ea,fp as Fa,pp as Ga,m2 as Ha,_2 as Ia,pc as Ja,mc as Ka,mk as La,qr as Ma,xi as Na,Vr as Oa,Ep as Pa,vp as Qa,Nk as Ra,Lk as Sa,Ci as Ta,kp as Ua,I2 as Va,Br as Wa,Gk as Xa,It as Ya,ge as Za,Qn as _a,Hr as $a,Zn as ab,Ap as bb,_c as cb,Oi as db,Hk as eb,R2 as fb,Wk as gb,Kk as hb,N2 as ib,D2 as jb,Yk as kb,P2 as lb,X as mb,Qp as nb,Zp as ob,tm as pb,nm as qb,gc as rb,bc as sb,wc as tb,$2 as ub,j2 as vb,U2 as wb,oA as xb,Sp as yb,z2 as zb,xp as Ab,Ec as Bb,cA as Cb,lA as Db,Yr as Eb,vc as Fb,Tc as Gb,kc as Hb,Ac as Ib,Sc as Jb,Di as Kb,xc as Lb,X2 as Mb,yA as Nb,hA as Ob,K as Pb,fe as Qb,an as Rb,Pp as Sb,Cc as Tb,Lp as Ub,Oc as Vb,Ic as Wb,Rc as Xb,Nc as Yb,Dc as Zb,Pc as _b,Mc as $b,Fc as ac,$c as bc,aS as cc,gS as dc,hS as ec,Dm as fc,Pm as gc,IS as hc,_G as ic,nx as jc,rx as kc,TG as lc,jm as mc,ox as nc,Zc as oc,ax as pc,cx as qc,RG as rc,Wi as sc,fx as tc,px as uc,mx as vc,_x as wc,gx as xc,yx as yc,hx as zc,Pt as Ac,bx as Bc,wx as Cc,rr as Dc,Ex as Ec,Ki as Fc,co as Gc,vx as Hc,Tx as Ic,ye as Jc,Yi as Kc,He as Lc,el as Mc,kx as Nc,Ax as Oc,Sx as Pc,xx as Qc,$e as Rc,Xi as Sc,lo as Tc,Dx as Uc,Mx as Vc,zG as Wc,Fx as Xc,$x as Yc,qG as Zc,HG as _c,e_ as $c,jx as ad,Ux as bd,zx as cd,qx as dd,Kx as ed,Jx as fd,WG as gd,Qx as hd,i_ as id,eC as jd,tC as kd,KG as ld,nC as md,Ji as nd,YG as od,or as pd,oC as qd,iC as rd,ol as sd,s_ as td,dC as ud,Ie as vd,he as wd,sl as xd,Ze as yd,Te as zd,zC as Ad,__ as Bd,al as Cd,ts as Dd,cl as Ed,y_ as Fd,GC as Gd,ZC as Hd,eO as Id,ir as Jd,E_ as Kd,gB as Ld,v_ as Md,tO as Nd,yB as Od,hn as Pd,T_ as Qd,rO as Rd,os as Sd,yo as Td,mI as Ud,bn as Vd,ho as Wd,je as Xd,wl as Yd,Ft as Zd,cs as _d,vI as $d,TI as ae,ls as be,Sl as ce,KB as de,YB as ee,XB as fe,CI as ge,OI as he,II as ie,Ll as je,Ml as ke,Fl as le,i5 as me,eR as ne,tR as oe,nR as pe,rR as qe,oR as re,bo as se,zl as te,ql as ue,sR as ve,s5 as we,aR as xe,Vl as ye,wo as ze,Ke as Ae,jH as Be,UH as Ce,zH as De,gs as Ee,yR as Fe,hR as Ge,Bl as He,_5 as Ie,b5 as Je,Q_ as Ke,wR as Le,ER as Me,w5 as Ne,nt as Oe,E5 as Pe,SR as Qe,OR as Re,LR as Se,ng as Te,x5 as Ue,C5 as Ve,Eo as We,Wl as Xe,Kl as Ye,O5 as Ze,jR as _e,I5 as $e,R5 as af,sg as bf,ys as cf,zR as df,fr as ef,pr as ff,hs as gf,bs as hf,vo as if,ag as jf,Jl as kf,To as lf,KR as mf,Zl as nf,YR as of,dg as pf,ug as qf,fg as rf,XR as sf,JR as tf,pg as uf,ko as vf,j5 as wf,QR as xf,mg as yf,_g as zf,gg as Af,ed as Bf,Ye as Cf,yg as Df,ZR as Ef,eN as Ff,tN as Gf,nN as Hf,rN as If,oN as Jf,iN as Kf,hg as Lf,sN as Mf,td as Nf,bg as Of,wg as Pf,Eg as Qf,nd as Rf,vg as Sf,Tg as Tf,rd as Uf,zt as Vf,od as Wf,AN as Xf,SN as Yf,Dg as Zf,Ts as _f,ld as $f,dd as ag,sd as bg,Ao as cg,vs as dg,Sg as eg,ad as fg,xg as gg,kn as hg,Mg as ig,$g as jg,jg as kg,PN as lg,rt as mg,tH as ng,pd as og,UN as pg,nH as qg,Bg as rg,Wg as sg,Yg as tg,Xg as ug,Jg as vg,ey as wg,f0 as xg,wH as yg,m0 as zg,ny as Ag,EH as Bg,oy as Cg,g0 as Dg,w0 as Eg,iy as Fg,cy as Gg,bt as Hg,uy as Ig,gy as Jg,Td as Kg,iD as Lg,Ro as Mg,Gt as Ng,wr as Og,uD as Pg,Ms as Qg,fD as Rg,vt as Sg,Tt as Tg,mD as Ug,Er as Vg,Fs as Wg,No as Xg,_D as Yg,gD as Zg,Od as _g,xn as $g,Id as ah,Cn as bh,vD as ch,fW as dh,pW as eh,Rd as fh,TD as gh,js as hh,Ny as ih,ke as jh,Bt as kh,On as lh,XD as mh,JD as nh,QD as oh,ZD as ph,Fd as qh,eP as rh,tP as sh,oP as th,Ky as uh,Us as vh,In as wh,lP as xh,a6 as yh,uP as zh,Xy as Ah,fP as Bh,pP as Ch,gP as Dh,m6 as Eh,bP as Fh,w6 as Gh,TP as Hh,AP as Ih,SP as Jh,xP as Kh,CP as Lh,Ud as Mh,RP as Nh,O6 as Oh,I6 as Ph,R6 as Qh,N6 as Rh,D6 as Sh,P6 as Th,L6 as Uh,PP as Vh,LP as Wh,MP as Xh,FP as Yh,$P as Zh,jP as _h,UP as $h,B6 as ai,Ws as bi,pL as ci,Yt as di,ot as ei,Fo as fi,Ar as gi,jh as hi,Zd as ii,E8 as ji,xM as ki,CM as li,OM as mi,ru as ni,FM as oi,aa as pi,lF as qi,ca as ri,Go as si,uu as ti,Cr as ui,yF as vi,Bo as wi,Ho as xi,lb as yi,vF as zi,p3 as Ai,fu as Bi,db as Ci,CF as Di,m3 as Ei,OF as Fi,IF as Gi,w3 as Hi,fa as Ii,_b as Ji,mu as Ki,qF as Li,VF as Mi,T3 as Ni,gb as Oi,Ir as Pi,gu as Qi,hu as Ri,ya as Si,P3 as Ti,Su as Ui,ba as Vi,Tb as Wi,wa as Xi,xu as Yi,Cu as Zi,Ou as _i,Iu as $i,Ob as aj,Ib as bj,Ab as cj,Nu as dj,lj as ej,Pr as fj,wj as gj,Ej as hj,vj as ij,Sj as jj,xj as kj,Oj as lj,Lj as mj,Vb as nj,Fj as oj,$j as pj,jj as qj,p4 as rj,_4 as sj,va as tj,ju as uj,Bb as vj,Gb as wj,qj as xj,Vj as yj,Hb as zj,Hj as Aj,Xj as Bj,Qj as Cj,e1 as Dj,t1 as Ej,o1 as Fj,s1 as Gj,a1 as Hj,y1 as Ij,Sa as Jj,fw as Kj,W1 as Lj,r9 as Mj,LU as Nj,MU as Oj,FU as Pj,af as Qj,Ia as Rj,$U as Sj,Ra as Tj,Na as Uj,cf as Vj,At as Wj,Da as Xj,Pa as Yj,lf as Zj,df as _j,La as $j,uf as ak,ff as bk,Ma as ck,jU as dk,mf as ek,_f as fk,gf as gk,Ww as hk,Fa as ik,Kw as jk,yf as kk,Yw as lk,hf as mk,bf as nk,wf as ok,Ef as pk,GU as qk,vf as rk,Tf as sk,BU as tk,HU as uk,eE as vk,WU as wk,Un as xk,OK as yk,JU as zk,IK as Ak,Ua as Bk,za as Ck,ja as Dk,Qw as Ek,QU as Fk,$a as Gk,RK as Hk,NK as Ik,ti as Jk,nz as Kk,Ba as Lk,rz as Mk,Ha as Nk,oE as Ok,iE as Pk,sE as Qk,aE as Rk,cE as Sk,lE as Tk,dE as Uk,uE as Vk,fE as Wk,pE as Xk,mE as Yk,_E as Zk,gE as _k,yE as $k,Rf as al,hE as bl,bE as cl,Nf as dl,Ae as el,Df as fl,Af as gl,wE as hl,EE as il,vE as jl,TE as kl,kE as ll,AE as ml,SE as nl,xE as ol,CE as pl,OE as ql,IE as rl,RE as sl,Sf as tl,NE as ul,DE as vl,Pf as wl,oz as xl,PE as yl,LE as zl,ME as Al,FE as Bl,$E as Cl,jE as Dl,UE as El,zE as Fl,qE as Gl,VE as Hl,Lf as Il,BE as Jl,HE as Kl,WE as Ll,KE as Ml,YE as Nl,XE as Ol,JE as Pl,QE as Ql,ZE as Rl,ev as Sl,tv as Tl,Mf as Ul,xf as Vl,iv as Wl,sv as Xl,av as Yl,cv as Zl,lv as _l,dv as $l,uv as am,Cf as bm,fv as cm,pv as dm,Of as em,mv as fm,_v as gm,gv as hm,yv as im,hv as jm,St as km,wv as lm,Ev as mm,vv as nm,Tv as om,kv as pm,uz as qm,fz as rm,Ff as sm,mz as tm,$v as um,hz as vm,jv as wm,zv as xm,Oz as ym,Fz as zm,qf as Am,Bv as Bm,Hv as Cm,$z as Dm,zz as Em,oq as Fm,EY as Gm,vY as Hm,TY as Im,kY as Jm,AY as Km,aq as Lm,SY as Mm,cq as Nm,xY as Om,lq as Pm,CY as Qm,OY as Rm,IY as Sm,dq as Tm,RY as Um,NY as Vm,DY as Wm,PY as Xm,LY as Ym,MY as Zm,FY as _m,$Y as $m,jY as an,UY as bn,zY as cn,qY as dn,VY as en,GY as fn};
205
- //# sourceMappingURL=chunk-NW6LV3TU.js.map
198
+ `:"";for(let o=0;;o+=1)try{await L(Ca(e),r);return}catch(i){let s=_w[o];if(s===void 0||!jw(i))throw i;await Uw(s)}}async function lw(e,t,n,r){return Jo(async()=>{let o=await Y(Ca(e)),i=o===null?[]:zw(o),s=[];for(let c of i){if(n.has(c.id))continue;let l=r.get(c.id);s.push(l?{...c,attempts:l.attempts,next_attempt_after:l.next_attempt_after}:c)}let{entries:a}=qw(s,t);return await AU(e,a),a.length})}async function SU(e,t){let n=await Y(Ca(e));if(n===null||n.trim().length===0){await pt(e,{pending_otel_spans:0});return}let r=zw(n),{entries:o,prunedCount:i}=qw(r,t),s=o.filter(_=>Fw(_.next_attempt_after)).slice(0,C1);if(s.length===0){let _=i>0?await lw(e,t,new Set,new Map):o.length;await pt(e,{pending_otel_spans:_});return}let a=oe(),c=new Set,l=new Map,d=0,u;await Promise.all(s.map(async _=>{try{let y=await Ow(_.endpoint,{"content-type":"application/json"},JSON.stringify(_.payload));if(y<200||y>=300)throw new Error(`local_otel_export_http_${y}`);c.add(_.id),d+=1}catch(y){u=y instanceof Error?ie(y.message,"redacted"):"local_otel_export_failed";let b=_.attempts+1;l.set(_.id,{attempts:b,next_attempt_after:Mw(b)})}}));let f=await lw(e,t,c,l),p={pending_otel_spans:f,last_otel_attempt_at:a};d>0&&(p.last_otel_success_at=a),u!==void 0?(p.last_otel_failure_at=a,p.last_otel_failure_error=u):f===0&&(p.last_otel_failure_at=void 0,p.last_otel_failure_error=void 0),await pt(e,p)}async function Vw(e,t,n){try{await IU(e,t,n)}catch{}try{await SU(e,n)}catch{}}async function xU(e,t=M1){try{let n=iU(e),r=await v1(n,{withFileTypes:!0}),o=Date.now()-Math.max(0,t);await Promise.all(r.filter(i=>i.isFile()&&/^\.events\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(i.name)).map(async i=>{let s=Pe.join(n,i.name);(await uw(s)).mtimeMs<o&&await Ku(s,{force:!0})}))}catch{}}async function Jo(e){let t=iw.catch(()=>{}).then(e);return iw=t.catch(()=>{}),t}async function of(e){let t=await Y(Xo(e));return t===null||t.trim().length===0?[]:Lw(t)}async function CU(e,t,n){return Jo(async()=>{let r=await of(e),{entries:o}=rf(r,n),i=o.filter(s=>!t.has(s.event.event_id));return await ka(e,i),i})}async function OU(e,t,n,r){return Jo(async()=>{let o=await of(e),{entries:i}=rf(o,r),s=i.map(a=>{if(!t.has(a.event.event_id))return a;let c=a.attempts+1;return{...a,attempts:c,last_attempt_at:n,next_attempt_after:Mw(c)}});return await ka(e,s),s})}async function IU(e,t,n){await xU(e);let r=t.trim();if(r.length===0)return;let o=await Y(Xo(e));if(o===null||o.trim().length===0){await pt(e,{endpoint:r,queue_entries:0});return}let i=Lw(o);if(i.length===0){await pt(e,{endpoint:r,queue_entries:0});return}let{entries:s,prunedCount:a}=rf(i,n);if(s.length===0){await ka(e,[]),await pt(e,{endpoint:r,queue_entries:0});return}let c=s.filter(p=>wU(p)).slice(0,O1);if(c.length===0){a>0&&await ka(e,s),await pt(e,{endpoint:r,queue_entries:s.length});return}let l=new Set(c.map(p=>p.event.event_id)),d=oe(),u={"content-type":"application/json"},f=process.env.PM_TELEMETRY_INGEST_KEY?.trim();f&&(u["x-pm-telemetry-key"]=f);try{let p=await Ow(r,u,JSON.stringify({schema_version:Aa,events:c.map(_=>_.event)}));if(p<200||p>=300)throw new Error(`telemetry_flush_http_${p}`)}catch(p){let _=await OU(e,l,d,n),y=p instanceof Error?ie(p.message,"redacted"):"telemetry_flush_failed";await pt(e,{endpoint:r,queue_entries:_.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:y});return}try{let p=await CU(e,l,n);await pt(e,{endpoint:r,queue_entries:p.length,last_attempted_flush_at:d,last_successful_flush_at:d,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(p){let _=p instanceof Error?ie(p.message,"redacted"):"telemetry_flush_failed",y=await of(e).catch(()=>s);await pt(e,{endpoint:r,queue_entries:y.length,last_attempted_flush_at:d,last_failed_flush_at:d,last_failed_flush_error:_})}}async function RU(e){let t=Xu(e);await qu(Pe.dirname(t),{recursive:!0});try{return await qu(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await uw(t);return Date.now()-n.mtimeMs<gw?!1:(await Ku(t,{recursive:!0,force:!0}),await qu(t),!0)}catch{return!1}}function NU(e,t){try{return Date.now()-dw(e).mtimeMs<t}catch{return!1}}function Gw(e){try{E1(e,{recursive:!0,force:!0})}catch{}}function DU(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function PU(e){try{return zu(e),!0}catch(t){if(DU(t)==="EEXIST"||!le(t))return!1}try{return zu(Pe.dirname(e),{recursive:!0}),zu(e),!0}catch{return!1}}function LU(e){if(NU(Xu(e),gw))return!1;let t=ww(e);try{if(Date.now()-dw(t).mtimeMs<F1)return!1;Gw(t)}catch(n){if(!le(n))return!1}return PU(t)}function Wu(e){Gw(ww(e))}async function MU(e,t,n){let r=await RU(e);if(Wu(e),!!r)try{await Vw(e,t,n)}finally{try{await Ku(Xu(e),{recursive:!0,force:!0})}catch{}}}function sf(e,t,n){if(aU()){let r=ow,o=Vw(e,t,n);ow=Promise.allSettled([r,o]).then(()=>{});return}try{if(!LU(e))return;let o=w1(process.execPath,[sU()],{detached:!0,stdio:"ignore",cwd:Yu.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[yw]:"1"}});o.on("error",()=>{Wu(e)}),o.unref()}catch{Wu(e)}}async function s4(e=Dt(process.cwd())){if(!ef())try{if(!(await at(e)).telemetry.enabled)return;let{endpoint:n,retentionDays:r}=await tf(e);await MU(e,n,r)}catch{}}async function FU(e){if(ef()||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=Dt(process.cwd()),n=await at(t);if(!n.telemetry.enabled)return null;let r=Cw(n.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await tf(t),a=Iw(e.pm_version),c=Nw(e.global),l=we(o,e.pm_root),d=we(o,process.cwd()),u=pU(),f=oe(),p={schema_version:Aa,event_id:mt.randomUUID(),event_type:"command_start",occurred_at:f,installation_id:o,session_id:xa,command:e.command,payload:yU({captureLevel:r,context:e,pmVersion:a,sourceContext:c,pmRootHash:l,cwdHash:d,installationId:o})};await nf(t,p),sf(t,i,s);let _=Pr(e.command);return{started_at:f,started_at_ms:Date.now(),command:e.command,command_taxonomy:_,pm_version:a,source_context:c.source_context,source_context_source:c.source_context_source,installation_id:o,pm_root_hash:l,cwd_hash:d,endpoint:i,retention_days:s,global_pm_root:t,capture_level:r,otel_traces_endpoint:u??void 0,otel_trace_id:u?mt.randomBytes(16).toString("hex"):void 0,otel_span_id:u?mt.randomBytes(8).toString("hex"):void 0}}catch{return null}}async function $U(e,t){if(e)try{let n=oe(),r=Math.max(0,Date.now()-e.started_at_ms),o=Ju(Mu({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),i=Rw({ok:t.ok,errorCode:o,errorCategory:t.error_category}),s=Qu(t.exit_code,t.ok),a=t.command_resolution??Lr({ok:t.ok,errorCode:o,errorCategory:i}),c=t.resolution_stage??"execute",l={schema_version:Aa,event_id:mt.randomUUID(),event_type:"command_finish",occurred_at:n,installation_id:e.installation_id,session_id:xa,command:e.command,payload:hU({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:r,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:s,errorCode:o,errorCategory:i,commandResolution:a,resolutionStage:c})};await nf(e.global_pm_root,l);let d=_U(e,{...t,exit_code:s,error_code:o,error_category:i},n,r);d&&await vU(e.global_pm_root,d),sf(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function jU(e){if(!ef())try{let t=Dt(process.cwd()),n=await at(t);if(!n.telemetry.enabled)return;let r=Cw(n.telemetry.capture_level),{installationId:o,endpoint:i,retentionDays:s}=await tf(t),a=Iw(e.pm_version),c=Nw(e.global),l=we(o,e.pm_root),d=we(o,process.cwd()),u=oe(),f=Ju(Mu({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),p=e.error_category??_i(f),_=Qu(e.exit_code,!1),y=e.command.trim().length>0?e.command:"<unknown>",b=Pr(y),E=e.command_resolution??Lr({ok:!1,errorCode:f,errorCategory:p}),T=e.resolution_stage??"unknown",O={schema_version:Aa,event_id:mt.randomUUID(),event_type:"command_error",occurred_at:u,installation_id:o,session_id:xa,command:ie(y,"redacted"),payload:bU({captureLevel:r,pmVersion:a,sourceContext:c,command:y,commandTaxonomy:b,commandResolution:E,resolutionStage:T,args:e.args,options:e.options,pmRootHash:l,cwdHash:d,installationId:o,errorCode:f,errorCategory:p,exitCode:_,errorMessage:e.error_message})};await nf(t,O),sf(t,i,s)}catch{}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d45775e5-6826-521b-80b3-429ed22947d9")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5f56c4ef-58e1-5cf6-a10e-dfa29b9ad3e8")}catch{}})();var af=[{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"ids",keys:["ids"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"parent",keys:["parent"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"limit",keys:["limit"]},{target:"offset",keys:["offset"]},{target:"after",keys:["after"]},{target:"fields",keys:["fields"]},{target:"sort",keys:["sort"]},{target:"order",keys:["order"]},{target:"treeDepth",keys:["treeDepth","tree_depth"]}],Oa=[{target:"mode",keys:["mode"]},{target:"matchMode",keys:["matchMode","match_mode"]},{target:"minScore",keys:["minScore","min_score"]},{target:"semanticWeight",keys:["semanticWeight","semantic_weight"]},{target:"status",keys:["status"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag","tags"]},{target:"priority",keys:["priority"]},{target:"deadlineBefore",keys:["deadlineBefore"]},{target:"deadlineAfter",keys:["deadlineAfter"]},{target:"updatedAfter",keys:["updatedAfter"]},{target:"updatedBefore",keys:["updatedBefore"]},{target:"createdAfter",keys:["createdAfter"]},{target:"createdBefore",keys:["createdBefore"]},{target:"assignee",keys:["assignee"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"fields",keys:["fields"]},{target:"limit",keys:["limit"]},{target:"after",keys:["after"]}],UU=[{target:"view",keys:["view"]},{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"status",keys:["status"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"include",keys:["include"]},{target:"recurrenceLookaheadDays",keys:["recurrenceLookaheadDays","recurrence_lookahead_days"]},{target:"recurrenceLookbackDays",keys:["recurrenceLookbackDays","recurrence_lookback_days"]},{target:"occurrenceLimit",keys:["occurrenceLimit","occurrence_limit"]},{target:"format",keys:["format"]}],Ia=[{target:"date",keys:["date"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit","maxItems","max_items"]},{target:"after",keys:["after"]},{target:"format",keys:["format"]},{target:"depth",keys:["depth"]},{target:"fields",keys:["fields"]},{target:"activityLimit",keys:["activityLimit","activity_limit"]},{target:"staleThreshold",keys:["staleThreshold","stale_threshold"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],Ra=[{target:"type",keys:["type"]},{target:"tag",keys:["tag"]},{target:"priority",keys:["priority"]},{target:"assignee",keys:["assignee"]},{target:"assigneeFilter",keys:["assigneeFilter","assignee_filter"]},{target:"sprint",keys:["sprint"]},{target:"release",keys:["release"]},{target:"parent",keys:["parent"]},{target:"limit",keys:["limit"]},{target:"blockedLimit",keys:["blockedLimit","blocked_limit"]},{target:"format",keys:["format"]},{target:"tokenBudget",keys:["tokenBudget","token_budget"]}],cf=[{target:"id",keys:["id"]},{target:"op",keys:["op"]},{target:"author",keys:["author"]},{target:"from",keys:["from"]},{target:"to",keys:["to"]},{target:"limit",keys:["limit"]}];function Ct(e,t){for(let n of t.keys){let r=e[n];if(typeof r=="string")return r}}function Na(e,t){for(let n of t.keys)if(Object.hasOwn(e,n))return e[n]}function Da(e,t){let n=[];for(let r of t.keys){let o=e[r];Array.isArray(o)&&n.push(...o.filter(i=>typeof i=="string"))}return n.length>0?n: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]="be7e506f-c48f-5dfb-9fed-ba1e74fa60ff")}catch{}})();var lf=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Item title [required] (or pass title as the first positional argument)"},{target:"id",keys:["id"],option:"--id <value>",description:"Explicit item id (normalized with the configured id_prefix)"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Item description (allow empty string)"},{target:"type",keys:["type"],option:"--type <value>",description:"Item type (built-ins plus any configured custom types)"},{target:"template",keys:["template"],option:"--template <value>",description:"Apply named create template defaults before explicit flags"},{target:"createMode",keys:["createMode","create_mode"],option:"--create-mode <value>",description:"Create required-option policy mode: strict|progressive",aliasOptions:[{option:"--create_mode <value>",description:"Alias for --create-mode"}]},{target:"schedulePreset",keys:["schedulePreset","schedule_preset"],option:"--schedule-preset <value>",description:"Scheduling preset for Reminder|Meeting|Event: lightweight",aliasOptions:[{option:"--schedule_preset <value>",description:"Alias for --schedule-preset"}]},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Item status"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Close reason when creating directly in a terminal status",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Actual completion time for a terminal imported item",aliasOptions:[{option:"--completed_at <value>",description:"Alias for --completed-at"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Priority 0..4"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Comma-separated tags"},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags additively on top of --tags (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Item markdown body (allow empty string)"},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Deadline (ISO/date string or relative +6h/+1d/+2w/+6m)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Acceptance criteria (repeatable; values join with '; '; allow empty string)",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Definition of ready (allow empty string)",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"History message (allow empty string)"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Item assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow creating with an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Seed dependency entry (key=value CSV, markdown key:value lines, or - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Type option key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Seed reminder entry at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Seed event entry start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Seed comment entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Seed note entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Seed learning entry (text=<value> CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Seed linked file entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Seed linked test entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Seed linked doc entry (CSV/markdown pairs or - for stdin; repeatable)",repeatable:!0}],df=lf.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Pa=lf.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),uf=[{target:"title",keys:["title"],option:"--title, -t <value>",description:"Set title"},{target:"description",keys:["description"],option:"--description, -d <value>",description:"Set description"},{target:"body",keys:["body"],option:"--body, -b <value>",description:"Set body (allow empty string)"},{target:"status",keys:["status"],option:"--status, -s <value>",description:"Set status (use close command for closed)"},{target:"closeReason",keys:["closeReason","close_reason"],option:"--close-reason <value>",description:"Set close reason",aliasOptions:[{option:"--close_reason <value>",description:"Alias for --close-reason"}]},{target:"priority",keys:["priority"],option:"--priority, -p <value>",description:"Set priority"},{target:"type",keys:["type"],option:"--type <value>",description:"Set type"},{target:"tags",keys:["tags"],option:"--tags <value>",description:"Set comma-separated tags (replaces existing). Use --add-tags / --remove-tags to mutate additively."},{target:"addTags",keys:["addTags","add_tags"],option:"--add-tags <value>",description:"Add tags to the existing list without replacing it (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--add_tags <value>",description:"Alias for --add-tags"}]},{target:"removeTags",keys:["removeTags","remove_tags"],option:"--remove-tags <value>",description:"Remove tags from the existing list (repeatable; CSV accepted)",repeatable:!0,aliasOptions:[{option:"--remove_tags <value>",description:"Alias for --remove-tags"}]},{target:"deadline",keys:["deadline"],option:"--deadline <value>",description:"Set deadline (ISO/date string or relative)"},{target:"estimatedMinutes",keys:["estimate","estimatedMinutes","estimated_minutes"],option:"--estimate, --estimated-minutes <value>",description:"Set estimated minutes",aliasOptions:[{option:"--estimated_minutes <value>",description:"Alias for --estimated-minutes"}]},{target:"acceptanceCriteria",keys:["acceptanceCriteria","acceptance_criteria","ac"],option:"--acceptance-criteria <value>",description:"Replace the complete acceptance-criteria list (repeatable values join with '; '); use --remove-ac plus --add-ac for one-entry repair",repeatable:!0,aliasOptions:[{option:"--acceptance_criteria <value>",description:"Alias for --acceptance-criteria"},{option:"--ac <value>",description:"Alias for --acceptance-criteria"}]},{target:"addAc",keys:["addAc","add_ac"],option:"--add-ac <value>",description:"Add one semicolon-free acceptance criterion without replacing the existing list (repeatable)",repeatable:!0,aliasOptions:[{option:"--add_ac <value>",description:"Alias for --add-ac"}]},{target:"removeAc",keys:["removeAc","remove_ac"],option:"--remove-ac <value>",description:"Remove one semicolon-free acceptance criterion by exact text match; fails if any selector is unmatched (repeatable)",repeatable:!0,aliasOptions:[{option:"--remove_ac <value>",description:"Alias for --remove-ac"}]},{target:"definitionOfReady",keys:["definitionOfReady","definition_of_ready"],option:"--definition-of-ready <value>",description:"Set definition of ready",aliasOptions:[{option:"--definition_of_ready <value>",description:"Alias for --definition-of-ready"}]},{target:"order",keys:["order"],option:"--order <value>",description:"Set planning order/rank integer"},{target:"rank",keys:["rank"],option:"--rank <value>",description:"Alias for --order"},{target:"goal",keys:["goal"],option:"--goal <value>",description:"Set goal identifier"},{target:"objective",keys:["objective"],option:"--objective <value>",description:"Set objective identifier"},{target:"value",keys:["value"],option:"--value <value>",description:"Set business value summary"},{target:"impact",keys:["impact"],option:"--impact <value>",description:"Set business impact summary"},{target:"outcome",keys:["outcome"],option:"--outcome <value>",description:"Set expected outcome summary"},{target:"whyNow",keys:["whyNow","why_now"],option:"--why-now <value>",description:"Set why-now rationale",aliasOptions:[{option:"--why_now <value>",description:"Alias for --why-now"}]},{target:"author",keys:["author"],option:"--author <value>",description:"Mutation author"},{target:"message",keys:["message"],option:"--message <value>",description:"Mutation message"},{target:"assignee",keys:["assignee"],option:"--assignee <value>",description:"Set assignee"},{target:"parent",keys:["parent"],option:"--parent <value>",description:"Set parent item ID"},{target:"allowMissingParent",keys:["allowMissingParent","allow_missing_parent"],option:"--allow-missing-parent",description:"Allow updating to an unresolved parent reference and emit a validation warning"},{target:"allowUnresolvedDeps",keys:["allowUnresolvedDeps","allow_unresolved_deps"],option:"--allow-unresolved-deps",description:"Allow unresolved local dependency targets and emit explicit warning receipts"},{target:"completedAt",keys:["completedAt","completed_at"],option:"--completed-at <value>",description:"Correct the actual completion timestamp on a terminal item"},{target:"reviewer",keys:["reviewer"],option:"--reviewer <value>",description:"Set reviewer"},{target:"risk",keys:["risk"],option:"--risk <value>",description:"Set risk level: low|med|medium|high|critical (med persists as medium)"},{target:"confidence",keys:["confidence"],option:"--confidence <value>",description:"Set confidence level: 0..100|low|med|medium|high (med persists as medium)"},{target:"sprint",keys:["sprint"],option:"--sprint <value>",description:"Set sprint identifier"},{target:"release",keys:["release"],option:"--release <value>",description:"Set release identifier"},{target:"blockedBy",keys:["blockedBy","blocked_by"],option:"--blocked-by <value>",description:"Set latest blocked-by item ID or reason; resolved item IDs append a blocked_by dependency edge",aliasOptions:[{option:"--blocked_by <value>",description:"Alias for --blocked-by"}]},{target:"blockedReason",keys:["blockedReason","blocked_reason"],option:"--blocked-reason <value>",description:"Set blocked reason",aliasOptions:[{option:"--blocked_reason <value>",description:"Alias for --blocked-reason"}]},{target:"unblockNote",keys:["unblockNote","unblock_note"],option:"--unblock-note <value>",description:"Set unblock rationale note",aliasOptions:[{option:"--unblock_note <value>",description:"Alias for --unblock-note"}]},{target:"reporter",keys:["reporter"],option:"--reporter <value>",description:"Set issue reporter"},{target:"severity",keys:["severity"],option:"--severity <value>",description:"Set issue severity: low|med|medium|high|critical (med persists as medium)"},{target:"environment",keys:["environment"],option:"--environment <value>",description:"Set issue environment context"},{target:"reproSteps",keys:["reproSteps","repro_steps"],option:"--repro-steps <value>",description:"Set issue reproduction steps",aliasOptions:[{option:"--repro_steps <value>",description:"Alias for --repro-steps"}]},{target:"resolution",keys:["resolution"],option:"--resolution <value>",description:"Set issue resolution summary"},{target:"expectedResult",keys:["expectedResult","expected_result","expected"],option:"--expected-result <value>",description:"Set issue expected behavior",aliasOptions:[{option:"--expected_result <value>",description:"Alias for --expected-result"},{option:"--expected <value>",description:"Short alias for --expected-result"}]},{target:"actualResult",keys:["actualResult","actual_result","actual"],option:"--actual-result <value>",description:"Set issue observed behavior",aliasOptions:[{option:"--actual_result <value>",description:"Alias for --actual-result"},{option:"--actual <value>",description:"Short alias for --actual-result"}]},{target:"affectedVersion",keys:["affectedVersion","affected_version"],option:"--affected-version <value>",description:"Set affected version identifier",aliasOptions:[{option:"--affected_version <value>",description:"Alias for --affected-version"}]},{target:"fixedVersion",keys:["fixedVersion","fixed_version"],option:"--fixed-version <value>",description:"Set fixed version identifier",aliasOptions:[{option:"--fixed_version <value>",description:"Alias for --fixed-version"}]},{target:"component",keys:["component"],option:"--component <value>",description:"Set issue component ownership"},{target:"regression",keys:["regression"],option:"--regression [value]",description:"Set regression marker; bare flag means true, or pass true|false|1|0"},{target:"customerImpact",keys:["customerImpact","customer_impact"],option:"--customer-impact <value>",description:"Set customer impact summary",aliasOptions:[{option:"--customer_impact <value>",description:"Alias for --customer-impact"}]},{target:"dep",keys:["dep"],option:"--dep <value>",description:"Add dependency entries id=<id>,kind=<value>,author=<value>,created_at=<iso|now>,source_kind=<value> (repeatable)",repeatable:!0},{target:"depRemove",keys:["depRemove","dep_remove"],option:"--dep-remove <value>",description:"Remove by dependency id or exact row signature (repeatable)",repeatable:!0,aliasOptions:[{option:"--dep_remove <value>",description:"Alias for --dep-remove"}]},{target:"comment",keys:["comment"],option:"--comment <value>",description:"Append comment seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"note",keys:["note"],option:"--note <value>",description:"Append note seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"learning",keys:["learning"],option:"--learning <value>",description:"Append learning seed author=<value>,created_at=<iso|now>,text=<value> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"file",keys:["file","linkedFile"],option:"--file <value>",description:"Append linked file path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-file <value>",description:"Alias for --file (cross-surface name)"}]},{target:"test",keys:["test","linkedTest"],option:"--test <value>",description:"Append linked test command=<value>,path=<value>,scope=<project|global>,timeout_seconds=<n>,pm_context_mode=<schema|tracker|auto> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--linked-test <value>",description:"Alias for --test (cross-surface name)"}]},{target:"doc",keys:["doc"],option:"--doc <value>",description:"Append linked doc path=<value>,scope=<project|global>,note=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"reminder",keys:["reminder"],option:"--reminder <value>",description:"Set reminders at=<iso|relative>,text=<text> (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"event",keys:["event"],option:"--event <value>",description:"Set events start=<iso|relative>,end=<iso|relative>,duration=<relative|30min|PT30M>,title=<text>,all_day=<true|false>,recur_* fields (also accepts markdown pairs and - for stdin; repeatable)",repeatable:!0},{target:"typeOption",keys:["typeOption","type_option"],option:"--type-option <value>",description:"Set type options key=value or key=<name>,value=<value> (also accepts key:value and markdown pairs; use - for stdin; repeatable)",repeatable:!0,aliasOptions:[{option:"--type_option <value>",description:"Alias for --type-option"}]},{target:"field",keys:["field"],option:"--field <name=value>",description:"Set a field declared by an active extension registerItemFields registration (repeatable)",repeatable:!0},{target:"unset",keys:["unset"],option:"--unset <field>",description:"Clear scalar metadata field by name (repeatable)",repeatable:!0}],ff=uf.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),La=uf.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys}));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="88009976-e03f-5a67-b6fc-bf60240dde49")}catch{}})();function zU(e,t){let n=[];for(let{param:r,flag:o}of e){let i=`--${r.replace(/([a-z\d])([A-Z])/gu,"$1-$2").toLowerCase()}`,s=t.find(a=>a.flag===o);if(!s){n.push({code:"missing_cli_flag",parameter:r,flag:o,parameter_flag:i});continue}s.flag!==i&&!s.aliases?.includes(i)&&n.push({code:"missing_parameter_alias",parameter:r,flag:o,parameter_flag:i})}return{ok:n.length===0,parameter_count:e.length,cli_flag_count:t.length,findings:n}}function ce(e){return e.map(t=>({...t}))}var pf=[{param:"status",flag:"--status"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"deadlineBefore",flag:"--deadline-before"},{param:"deadlineAfter",flag:"--deadline-after"}],Bw=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],qU=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...Bw],Hw=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],VU=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],GU=[...pf,...Hw],Ww=[{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"}],BU=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Kw=[{param:"hasNotes",flag:"--has-notes"},{param:"noNotes",flag:"--no-notes"},{param:"hasLearnings",flag:"--has-learnings"},{param:"noLearnings",flag:"--no-learnings"},{param:"hasFiles",flag:"--has-files"},{param:"noFiles",flag:"--no-files"},{param:"filterFilesMissing",flag:"--filter-files-missing"},{param:"hasDocs",flag:"--has-docs"},{param:"noDocs",flag:"--no-docs"},{param:"filterDocsMissing",flag:"--filter-docs-missing"},{param:"hasTests",flag:"--has-tests"},{param:"noTests",flag:"--no-tests"},{param:"hasComments",flag:"--has-comments"},{param:"noComments",flag:"--no-comments"},{param:"hasDeps",flag:"--has-deps"},{param:"noDeps",flag:"--no-deps"},{param:"hasBody",flag:"--has-body"},{param:"emptyBody",flag:"--empty-body"},{param:"hasLinkedCommand",flag:"--has-linked-command"},{param:"noLinkedCommand",flag:"--no-linked-command"}],mf=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...ce(pf),...ce(qU),{param:"ids",flag:"--ids"},...ce(Hw),...ce(BU),...ce(Ww),...ce(Kw),{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"},{param:"after",flag:"--after"},{param:"fields",flag:"--fields"},{param:"sort",flag:"--sort"},{param:"order",flag:"--order"},{param:"tree",flag:"--tree"},{param:"treeDepth",flag:"--tree-depth"}],_f=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...ce(GU)],gf=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},{param:"matchMode",flag:"--match-mode"},{param:"minScore",flag:"--min-score"},{param:"count",flag:"--count",booleanish:!0},{param:"semanticWeight",flag:"--semantic-weight"},...ce(pf),...ce(Bw),...ce(VU),...ce(Ww),...ce(Kw),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Yw=[{param:"parent",flag:"--parent"},{param:"reviewer",flag:"--reviewer"},{param:"risk",flag:"--risk"},{param:"confidence",flag:"--confidence"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"blockedBy",flag:"--blocked-by"},{param:"blockedReason",flag:"--blocked-reason"},{param:"unblockNote",flag:"--unblock-note"},{param:"reporter",flag:"--reporter"},{param:"severity",flag:"--severity"},{param:"environment",flag:"--environment"},{param:"reproSteps",flag:"--repro-steps"},{param:"resolution",flag:"--resolution"},{param:"expectedResult",flag:"--expected-result"},{param:"actualResult",flag:"--actual-result"},{param:"affectedVersion",flag:"--affected-version"},{param:"fixedVersion",flag:"--fixed-version"},{param:"component",flag:"--component"},{param:"regression",flag:"--regression",booleanish:!0},{param:"customerImpact",flag:"--customer-impact"},{param:"definitionOfReady",flag:"--definition-of-ready",allowEmpty:!0},{param:"order",flag:"--order"},{param:"rank",flag:"--rank"},{param:"goal",flag:"--goal"},{param:"objective",flag:"--objective"},{param:"value",flag:"--value"},{param:"impact",flag:"--impact"},{param:"outcome",flag:"--outcome"},{param:"whyNow",flag:"--why-now"}],Ma=ce(Yw),Xw=[{param:"id",flag:"--id"},{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"type",flag:"--type"},{param:"template",flag:"--template"},{param:"createMode",flag:"--create-mode"},{param:"schedulePreset",flag:"--schedule-preset"},{param:"status",flag:"--status"},{param:"priority",flag:"--priority"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"allowDuplicate",flag:"--allow-duplicate",booleanish:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"dep",flag:"--dep",repeatable:!0},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],yf=ce(Xw),Jw=[{param:"title",flag:"--title"},{param:"description",flag:"--description",allowEmpty:!0},{param:"body",flag:"--body",allowEmpty:!0},{param:"status",flag:"--status"},{param:"closeReason",flag:"--close-reason"},{param:"completedAt",flag:"--completed-at"},{param:"priority",flag:"--priority"},{param:"type",flag:"--type"},{param:"tags",flag:"--tags",allowEmpty:!0},{param:"addTags",flag:"--add-tags",repeatable:!0},{param:"removeTags",flag:"--remove-tags",repeatable:!0},{param:"deadline",flag:"--deadline"},{param:"estimate",flag:"--estimate"},{param:"acceptanceCriteria",flag:"--acceptance-criteria",allowEmpty:!0},{param:"addAc",flag:"--add-ac",repeatable:!0},{param:"removeAc",flag:"--remove-ac",repeatable:!0},{param:"author",flag:"--author"},{param:"message",flag:"--message",allowEmpty:!0},{param:"assignee",flag:"--assignee"},{param:"allowMissingParent",flag:"--allow-missing-parent"},{param:"allowUnresolvedDeps",flag:"--allow-unresolved-deps"},{param:"dep",flag:"--dep",repeatable:!0},{param:"depRemove",flag:"--dep-remove",repeatable:!0},{param:"replaceDeps",flag:"--replace-deps"},{param:"replaceTests",flag:"--replace-tests"},{param:"replaceFiles",flag:"--replace-files"},{param:"replaceDocs",flag:"--replace-docs"},{param:"comment",flag:"--comment",repeatable:!0},{param:"note",flag:"--note",repeatable:!0},{param:"learning",flag:"--learning",repeatable:!0},{param:"linkedFile",flag:"--file",repeatable:!0},{param:"linkedTest",flag:"--test",repeatable:!0},{param:"doc",flag:"--doc",repeatable:!0},{param:"reminder",flag:"--reminder",repeatable:!0},{param:"event",flag:"--event",repeatable:!0},{param:"typeOption",flag:"--type-option",repeatable:!0},{param:"field",flag:"--field",repeatable:!0},{param:"unset",flag:"--unset",repeatable:!0},{param:"clearDeps",flag:"--clear-deps"},{param:"clearComments",flag:"--clear-comments"},{param:"clearNotes",flag:"--clear-notes"},{param:"clearLearnings",flag:"--clear-learnings"},{param:"clearFiles",flag:"--clear-files"},{param:"clearTests",flag:"--clear-tests"},{param:"clearDocs",flag:"--clear-docs"},{param:"clearReminders",flag:"--clear-reminders"},{param:"clearEvents",flag:"--clear-events"},{param:"clearTypeOptions",flag:"--clear-type-options"}],hf=ce(Jw),bf=[{param:"filterStatus",flag:"--filter-status"},{param:"filterType",flag:"--filter-type"},{param:"filterTag",flag:"--filter-tag"},{param:"filterPriority",flag:"--filter-priority"},{param:"filterDeadlineBefore",flag:"--filter-deadline-before"},{param:"filterDeadlineAfter",flag:"--filter-deadline-after"},{param:"filterUpdatedAfter",flag:"--filter-updated-after"},{param:"filterUpdatedBefore",flag:"--filter-updated-before"},{param:"filterCreatedAfter",flag:"--filter-created-after"},{param:"filterCreatedBefore",flag:"--filter-created-before"},{param:"filterAssignee",flag:"--filter-assignee"},{param:"filterAssigneeFilter",flag:"--filter-assignee-filter"},{param:"filterParent",flag:"--filter-parent"},{param:"filterSprint",flag:"--filter-sprint"},{param:"filterRelease",flag:"--filter-release"},{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"},{param:"filterReviewerMissing",flag:"--filter-reviewer-missing"},{param:"filterRiskMissing",flag:"--filter-risk-missing"},{param:"filterConfidenceMissing",flag:"--filter-confidence-missing"},{param:"filterSprintMissing",flag:"--filter-sprint-missing"},{param:"filterReleaseMissing",flag:"--filter-release-missing"},{param:"filterHasNotes",flag:"--filter-has-notes"},{param:"filterNoNotes",flag:"--filter-no-notes"},{param:"filterHasLearnings",flag:"--filter-has-learnings"},{param:"filterNoLearnings",flag:"--filter-no-learnings"},{param:"filterHasFiles",flag:"--filter-has-files"},{param:"filterNoFiles",flag:"--filter-no-files"},{param:"filterHasDocs",flag:"--filter-has-docs"},{param:"filterNoDocs",flag:"--filter-no-docs"},{param:"filterHasTests",flag:"--filter-has-tests"},{param:"filterNoTests",flag:"--filter-no-tests"},{param:"filterHasComments",flag:"--filter-has-comments"},{param:"filterNoComments",flag:"--filter-no-comments"},{param:"filterHasDeps",flag:"--filter-has-deps"},{param:"filterNoDeps",flag:"--filter-no-deps"},{param:"filterHasBody",flag:"--filter-has-body"},{param:"filterEmptyBody",flag:"--filter-empty-body"},{param:"filterHasLinkedCommand",flag:"--filter-has-linked-command"},{param:"filterNoLinkedCommand",flag:"--filter-no-linked-command"},{param:"ids",flag:"--ids"},{param:"limit",flag:"--limit"},{param:"offset",flag:"--offset"}],wf=ce(bf),Ef=ce(bf),HU=[{param:"view",flag:"--view"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"status",flag:"--status"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"include",flag:"--include"},{param:"recurrenceLookaheadDays",flag:"--recurrence-lookahead-days"},{param:"recurrenceLookbackDays",flag:"--recurrence-lookback-days"},{param:"occurrenceLimit",flag:"--occurrence-limit"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"}],vf=[{param:"id",flag:"--id"},{param:"op",flag:"--op"},{param:"author",flag:"--author"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"limit",flag:"--limit"},{param:"unbounded",flag:"--unbounded"},{param:"compact",flag:"--compact"},{param:"raw",flag:"--raw"},{param:"full",flag:"--full"},{param:"provenance",flag:"--provenance"},{param:"provenanceSummary",flag:"--provenance-summary"},{param:"harness",flag:"--harness",repeatable:!0},{param:"agentInstance",flag:"--agent-instance",repeatable:!0},{param:"provenanceFilter",flag:"--provenance-filter",repeatable:!0}],Tf=[{param:"for",flag:"--for"},{param:"date",flag:"--date"},{param:"from",flag:"--from"},{param:"to",flag:"--to"},{param:"type",flag:"--type"},{param:"tag",flag:"--tag"},{param:"priority",flag:"--priority"},{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"format",flag:"--format"},{param:"depth",flag:"--depth"},{param:"fields",flag:"--fields"},{param:"section",flag:"--section",repeatable:!0},{param:"activityLimit",flag:"--activity-limit"},{param:"staleThreshold",flag:"--stale-threshold"},{param:"tokenBudget",flag:"--token-budget"},{param:"explainRanking",flag:"--explain-ranking"},{param:"noTags",flag:"--no-tags"},{param:"noExtensionHealth",flag:"--no-extension-health"}],WU=[{param:"format",flag:"--format"},{param:"maxDepth",flag:"--max-depth"},{param:"collapse",flag:"--collapse"},{param:"summary",flag:"--summary"},{param:"nodeLimit",flag:"--node-limit"},{param:"edgeLimit",flag:"--edge-limit"},{param:"tokenBudget",flag:"--token-budget"},{param:"cursor",flag:"--cursor"},{param:"direction",flag:"--direction"},{param:"kind",flag:"--kind",repeatable:!0}],KU=[{param:"kind",flag:"--kind",repeatable:!0},{param:"maxDepth",flag:"--max-depth"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"},{param:"direction",flag:"--direction"},{param:"maxPaths",flag:"--max-paths"},{param:"sample",flag:"--sample"},{param:"exemptIsolate",flag:"--exempt-isolate",repeatable:!0},{param:"exemptIsolateType",flag:"--exempt-isolate-type",repeatable:!0},{param:"saveBaseline",flag:"--save-baseline"},{param:"rebuild",flag:"--rebuild"},{param:"clear",flag:"--clear"},{param:"summary",flag:"--summary"}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4efc5934-7d1b-517b-8b5e-eb2fe14379f2")}catch{}})();var nE=["item","list","context","search","graph","history","workspace","package","ops","plan","contracts","help"],YU=["activate","add","adopt","adopt-all","catalog","compact","complete","create","deactivate","delete","describe","doctor","edit","explore","import","init","inspect","install","list","manage","migrate","mutate","read","redact","reload","remove","reopen","repair","restore","run","show","uninstall","upgrade","verify"];function v(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Qw(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var K=v("id","item_id",!0),Qo=v("id","item_id",!1),Zo=v("text","string",!1),ei=v("plan-id","item_id",!0),Zw=v("step","string",!0),XU=["--acceptance-criteria","--actual-result","--affected-version","--assignee","--blocked-by","--blocked-reason","--blocks","--body","--claim","--comment","--component","--confidence","--create-mode","--customer-impact","--deadline","--definition-of-ready","--description","--doc","--environment","--estimate","--event","--expected-result","--fixed-version","--file","--from-search","--goal","--harness","--impact","--learning","--message","--mode","--note","--objective","--order","--outcome","--parent","--priority","--rank","--related","--release","--reminder","--reporter","--repro-steps","--resolution","--resume-context","--reviewer","--risk","--scope","--severity","--sprint","--status","--step","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-replacement","--step-status","--step-title","--tags","--template","--test","--title","--type-option","--unblock-note","--value","--why-now"],kf=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],JU={"update-step":"Update one declared Plan step.","complete-step":"Complete one declared Plan step.","block-step":"Block one declared Plan step.","remove-step":"Remove one declared Plan step.",link:"Link one dependency to a declared Plan step.",unlink:"Unlink one dependency from a declared Plan step."},Un=[{command:"plan create",parent:"plan",action:"create",slots:[v("title","string",!1,{polymorphic:!0})],accepted_flags:XU,description:"Create a Plan item and optionally seed its ordered steps.",example:'pm plan create --title "Refactor lock retry"'},{command:"plan show",parent:"plan",action:"show",slots:[ei],accepted_flags:["--depth","--fields"],description:"Read one Plan item with a bounded plan projection.",example:"pm plan show pm-a1b2 --depth standard"},{command:"plan add-step",parent:"plan",action:"add-step",slots:[ei],accepted_flags:kf,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(JU).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[ei,Zw],accepted_flags:kf,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[ei,Zw,v("new-order","integer",!0)],accepted_flags:["--force","--message"],description:"Move one Plan step to a declared integer order.",example:"pm plan reorder-step pm-a1b2 plan-step-001 2"},...["decision","discovery","validation","resume","approve","materialize"].map(e=>({command:`plan ${e}`,parent:"plan",action:e,slots:[ei],accepted_flags:kf,description:`${Qw(e)} for one Plan item.`,example:`pm plan ${e} pm-a1b2`})),...["list","show","put","remove"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[v("kind","string",!0),...e==="list"?[]:[v("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Qw(e)} assurance declarations by kind.`,example:e==="list"?"pm assurance list measurement":`pm assurance ${e} measurement example-id`})),{command:"assurance run",parent:"assurance",action:"run",slots:[v("gate-id","string",!0)],accepted_flags:["--dry-run","--trigger","--tree"],description:"Evaluate one assurance gate for a lifecycle trigger.",example:"pm assurance run tracker-context-quality --trigger ci --dry-run"},{command:"assurance verdicts",parent:"assurance",action:"verdicts",slots:[v("gate-id","string",!1)],accepted_flags:["--gate","--limit"],description:"List bounded assurance verdict history.",example:"pm assurance verdicts --limit 20"},...["presets","apply"].map(e=>({command:`assurance ${e}`,parent:"assurance",action:e,slots:[v("preset","string",e==="apply")],accepted_flags:["--author","--message","--owner"],description:e==="apply"?"Apply one assurance adoption preset.":"List available assurance adoption presets.",example:e==="apply"?"pm assurance apply software-delivery --owner <pm-item-id>":"pm assurance presets"})),{command:"assurance derive",parent:"assurance",action:"derive",slots:[],accepted_flags:["--apply","--author","--message","--owner"],description:"Derive assurance proposals from current project context.",example:"pm assurance derive --owner pm-a1b2"},{command:"assurance promote",parent:"assurance",action:"promote",slots:[v("assertion-id","string",!0)],accepted_flags:["--author","--enforcement","--message"],description:"Promote one assertion into a warning or blocking gate.",example:"pm assurance promote assertion-id --enforcement warn"},{command:"assurance risk",parent:"assurance",action:"risk",slots:[],accepted_flags:["--definition"],description:"Analyze bounded defect-recurrence risk for a proposed change.",example:`pm assurance risk --definition '{"change":{"files":[]}}'`},{command:"workspace position",parent:"workspace",action:"position",slots:[],accepted_flags:[],description:"Read bounded merge-fence, receipt, history-drift, and next-action readiness.",example:"pm workspace position"},{command:"workspace snapshot create",parent:"workspace snapshot",action:"create",slots:[v("name","string",!1)],accepted_flags:[],description:"Capture authoritative tracker state as an immutable snapshot.",example:"pm workspace snapshot create before-migration"},{command:"workspace snapshot list",parent:"workspace snapshot",action:"list",slots:[],accepted_flags:[],description:"List immutable workspace snapshots and named references.",example:"pm workspace snapshot list"},{command:"workspace snapshot inspect",parent:"workspace snapshot",action:"inspect",slots:[v("target","string",!0)],accepted_flags:[],description:"Inspect one workspace snapshot target.",example:"pm workspace snapshot inspect before-migration"},{command:"workspace snapshot restore",parent:"workspace snapshot",action:"restore",slots:[v("target","string",!0)],accepted_flags:["--author","--dry-run","--force","--message"],description:"Restore an immutable workspace snapshot with explicit recovery controls.",example:"pm workspace snapshot restore before-migration --dry-run"},{command:"workspace snapshot delete",parent:"workspace snapshot",action:"delete",slots:[v("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],QU=[...Un].sort((e,t)=>t.command.length-e.command.length),rE=new Map([["append",[K,Zo]],["assurance",[v("action","action",!0),v("kind","string",!1),v("id","string",!1)]],["beads import",[v("file","string",!1)]],["changelog export",[v("file","string",!1)]],["claim",[Qo]],["close",[K,Zo]],["close-task",[K,v("reason","string",!1)]],["comments",[K,Zo]],["completion",[v("shell","string",!1)]],["config",[v("scope","string",!1,{polymorphic:!0}),v("action","action",!1),v("key","string",!1),v("value","string",!1,{polymorphic:!0})]],["copy",[K]],["create",[v("type-or-title","string",!1,{polymorphic:!0}),v("title","string",!1)]],["delete",[K]],["deps",[K]],["docs",[K]],["event",[v("title","string",!0)]],["files",[K]],["files discover",[K]],["files lookup",[v("paths","string",!0,{variadic:!0})]],["focus",[Qo]],["get",[K]],["graph",[v("subcommand","action",!0),Qo,v("target","item_id",!1)]],["guide",[v("topic","string",!1)]],["history",[K]],["history-compact",[Qo]],["history-redact",[K]],["history-repair",[Qo]],["init",[v("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[K,v("reason","string",!1)]],["item reopen",[K,v("reason","string",!0)]],["learnings",[K,Zo]],["meet",[v("title","string",!0)]],["merge",[v("subcommand","action",!0),v("artifact","string",!1),v("base","string",!1),v("ours","string",!1),v("theirs","string",!1)]],["notes",[K,Zo]],["package",[v("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[v("target","string",!0)]],["package upgrade",[v("target","string",!1)]],["packages",[v("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[v("target","string",!0)]],["packages upgrade",[v("target","string",!1)]],["pause-task",[K]],["plan",[v("subcommand","action",!0),v("id","item_id",!1,{polymorphic:!0}),v("step","string",!1),v("new-order","integer",!1)]],["profile",[v("subcommand","action",!0),v("name","string",!1)]],["release",[K]],["remind",[v("title","string",!0)]],["restore",[K,v("target","string",!0)]],["schema",[v("subcommand","action",!0),v("name","string",!1)]],["search-advanced",[v("keywords","string",!0,{variadic:!0})]],["search",[v("keywords","string",!0,{variadic:!0})]],["start-task",[K]],["telemetry",[v("namespace-or-subcommand","action",!1,{polymorphic:!0}),v("subcommand","action",!1)]],["test",[K]],["update",[K]],["workspace snapshot",[v("action","action",!0),v("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[v("targets","string",!1,{variadic:!0})]])),["vcs abandon",[K]],["vcs create",[v("title","string",!0)]],["vcs merge",[K]],["vcs propose",[K]],["vcs ref-create",[v("name","string",!0)]],["vcs show",[K]]]);function jn(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function NK(e){let t=jn(e),n=Ua.find(o=>o.command===t);if(n)return n;let r=Ql(t)?.canonical;if(r)return Ua.find(o=>o.command===r)}function ZU(e){let t=jn(e);return QU.find(n=>n.command===t||t.startsWith(`${n.command} `))}function DK(e){return`Applicable flags: ${e.length>0?e.join(", "):"none"}.`}function G(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var ja=[...G("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...G("item","item","consolidation","pm-yql1",["append","claim","close","close-many","close-task","comments","copy","create","delete","docs","files","get","learnings","notes","pause-task","release","start-task","test","update","update-many"]),...G("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...G("list","list","target_noun","pm-pfqi",["list"]),...G("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...G("context","context","target_noun","pm-pbyu",["context"]),...G("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...G("search","search","target_noun","pm-pbyu",["search"]),...G("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...G("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...G("graph","graph","target_noun","pm-pbyu",["graph"]),...G("graph","graph show","consolidation","pm-yql1",["deps"]),...G("history","history","target_noun","pm-pbyu",["history"]),...G("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...G("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...G("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace position","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...G("workspace","workspace init","consolidation","pm-n7rr",["init"]),...G("package","package","target_noun","pm-pbyu",["package","package activate","package adopt","package adopt-all","package catalog","package deactivate","package describe","package doctor","package explore","package init","package install","package list","package manage","package migrate","package reload","package scaffold","package uninstall","package upgrade"]),...G("package","package","consolidation","pm-tnud",["extension activate","extension adopt","extension adopt-all","extension catalog","extension deactivate","extension describe","extension doctor","extension explore","extension init","extension install","extension manage","extension migrate","extension reload","extension uninstall","packages","packages activate","packages adopt","packages adopt-all","packages catalog","packages deactivate","packages describe","packages doctor","packages explore","packages init","packages install","packages list","packages manage","packages migrate","packages reload","packages scaffold","packages uninstall","packages upgrade"]),...G("package","package","package_owned","package:beads",["beads import"]),...G("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...G("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...G("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...G("ops","ops assurance","consolidation","pm-2tan",Un.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...G("plan","plan","target_noun","pm-pbyu",["plan"]),...G("plan","plan","target_noun","pm-2tan",Un.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...G("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...G("help","help","target_noun","pm-pbyu",["help"]),...G("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],Ua=[...new Set(ja.map(({command:e})=>e))].map(e=>({command:e,slots:ZU(e)?.slots??rE.get(e)??[]})),$a={nouns:nE,shared_verbs:YU,scope_before_verb:!0,visible_top_level_ceiling:69,ceiling_raise_requires_pm_item:!0,positional_shape_budget:21};function eE(e,t){let n=new Set(t);return[...new Set(e)].filter(r=>!n.has(r)).map(r=>({code:"positional_signature_mismatch",command:r,detail:`Positional signature ${r} has no destination declaration.`}))}function ez(e){return e.map(({required:t,variadic:n,value_kind:r,polymorphic:o})=>`${t?"r":"o"}:${n?"v":"s"}:${r}:${o?"p":"m"}`).join("|")}function Fa(e){return e.map(({name:t,required:n,variadic:r,value_kind:o,polymorphic:i})=>`${t}:${n?"r":"o"}:${r?"v":"s"}:${o}:${i?"p":"m"}`).join("|")}function tE(e,t){let n=new Map;for(let{command:r}of e){let o=jn(r);n.set(o,(n.get(o)??0)+1)}return[...n.entries()].filter(([,r])=>r>1).map(([r,o])=>({code:"positional_signature_mismatch",command:r,detail:`${o} ${t} positional signatures exist for ${r}; exactly one is required.`}))}function PK(e,t={}){let n=t.declared??Ua,r=t.positionalShapeBudget??$a.positional_shape_budget,o=new Map(n.map(c=>[jn(c.command),c])),i=new Map(e.map(c=>[jn(c.command),c])),s=[...tE(n,"declared"),...tE(e,"observed"),...t.declared===void 0?[...eE(rE.keys(),ja.map(({command:c})=>c)),...eE(Un.map(({command:c})=>c),ja.map(({command:c})=>c))]:[]];for(let c of o.values()){let l=jn(c.command),d=i.get(l);d?Fa(d.slots)!==Fa(c.slots)&&s.push({code:"positional_signature_mismatch",command:c.command,detail:`Observed positional signature for ${c.command} differs from its declared SDK contract: observed=${Fa(d.slots)||"<none>"}; declared=${Fa(c.slots)||"<none>"}.`}):s.push({code:"missing_observed_signature",command:c.command,detail:`No observed positional signature exists for ${c.command}.`})}for(let c of i.values())o.has(jn(c.command))||s.push({code:"stale_observed_signature",command:c.command,detail:`Observed positional signature ${c.command} has no declaration.`});let a=new Set(n.map(({slots:c})=>ez(c))).size;return a>r&&s.push({code:"positional_shape_budget_exceeded",command:"*",detail:`Distinct positional shape count ${a} exceeds budget ${r}.`}),s.sort((c,l)=>c.command!==l.command?c.command.localeCompare(l.command):c.code.localeCompare(l.code)),{ok:s.length===0,declared_command_count:n.length,observed_command_count:e.length,positional_shape_count:a,positional_shape_budget:r,findings:s}}function tz(e,t,n){return e.flatMap(r=>{let o=t.get(r)??[];if(o.length===0){let s=r.indexOf(" "),a=s===-1?r:r.slice(0,s);return[{code:"missing_destination",spelling:r,message:`Command \`${r}\` has no destination census row.`,nearest_target:n.has(a)?a:`ops ${r}`}]}let i=o.length>1?[{code:"duplicate_destination",spelling:r,message:`Command \`${r}\` has ${o.length} destination rows.`,nearest_target:o[0].target}]:[];return o.reduce((s,a)=>(a.disposition==="keep_as_is"&&(a.reason?.trim().length??0)===0&&s.push({code:"missing_destination",spelling:r,message:`Command \`${r}\` is kept as-is without a documented reason.`,nearest_target:a.target}),n.has(a.noun)||s.push({code:"unknown_noun",spelling:r,message:`Command \`${r}\` names undeclared noun \`${a.noun}\`.`,nearest_target:a.target}),s),i)})}function nz(e,t){return t.filter(n=>n.disposition!=="package_owned"&&!e.has(n.command)).map(n=>({code:"stale_destination",spelling:n.command,message:`Destination row \`${n.command}\` is absent from live contracts.`,nearest_target:n.target}))}function rz(e,t){return e.filter(n=>!t.has(n.canonical)).map(n=>({code:"alias_target_missing",spelling:n.alias,message:`Alias \`${n.alias}\` targets missing canonical command \`${n.canonical}\`.`,nearest_target:n.canonical_argv.join(" ")}))}function LK(e,t=[],n=ja){let r=[...new Set(e.map(d=>d.trim()))].filter(d=>d.length>0).sort((d,u)=>d.localeCompare(u)),o=new Set(r),i=new Set(nE),s=new Map;for(let d of n){let u=s.get(d.command)??[];u.push(d),s.set(d.command,u)}let a=[...tz(r,s,i),...nz(o,n),...rz(t,o)],c=new Set(t.filter(d=>d.hidden).map(d=>d.alias)),l=new Set(r.filter(d=>!d.includes(" ")&&!c.has(d)&&!(s.get(d)??[]).some(u=>u.disposition==="package_owned"))).size;return l>$a.visible_top_level_ceiling&&a.push({code:"visible_surface_ceiling_exceeded",spelling:String(l),message:`Visible non-package top-level command count ${l} exceeds ceiling ${$a.visible_top_level_ceiling}.`,nearest_target:"Declare the noun placement and tracked waiver before raising the ceiling."}),{ok:a.length===0,command_count:r.length,destination_count:n.length,hidden_alias_count:t.filter(d=>d.hidden).length,visible_top_level_count:l,visible_top_level_ceiling:$a.visible_top_level_ceiling,findings: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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function zn(e){return[...new Set(Array.from(e,t=>t.trim()).filter(t=>t.length>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]="789faf62-dfbf-56ff-9412-55adc5c12d3d")}catch{}})();function qa(e){return e.startsWith("--")?`--${e.slice(2).replaceAll("_","-")}`:e}function ti(e){let t=new Map;for(let n of e){let r=qa(n.flag),o=t.get(r)??new Set;n.flag!==r&&o.add(n.flag);for(let i of n.aliases??[])i!==r&&o.add(i);t.set(r,o)}return e.map(n=>{let r=qa(n.flag);if(n.flag!==r)return n;let o=zn([...n.aliases??[],...t.get(r)]).filter(i=>i!==r);return o.length===0?n:{...n,aliases:o}})}function oz(e){let t=ti(e),n=new Set(t.map(r=>r.flag));return t.filter(r=>{let o=qa(r.flag);return r.flag===o||!n.has(o)})}var Ga=zc.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),iz=[...Ga,{flag:"--version"}],oE=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--has-notes"},{flag:"--no-notes"},{flag:"--has-learnings"},{flag:"--no-learnings"},{flag:"--has-files"},{flag:"--no-files"},{flag:"--filter-files-missing"},{flag:"--has-docs"},{flag:"--no-docs"},{flag:"--filter-docs-missing"},{flag:"--has-tests"},{flag:"--no-tests"},{flag:"--has-comments"},{flag:"--no-comments"},{flag:"--has-deps"},{flag:"--no-deps"},{flag:"--has-body"},{flag:"--empty-body"},{flag:"--has-linked-command"},{flag:"--no-linked-command"}],iE=[{flag:"--filter-reviewer-missing"},{flag:"--filter-risk-missing"},{flag:"--filter-confidence-missing"},{flag:"--filter-sprint-missing"},{flag:"--filter-release-missing"},{flag:"--filter-has-notes"},{flag:"--filter-no-notes"},{flag:"--filter-has-learnings"},{flag:"--filter-no-learnings"},{flag:"--filter-has-files"},{flag:"--filter-no-files"},{flag:"--filter-has-docs"},{flag:"--filter-no-docs"},{flag:"--filter-has-tests"},{flag:"--filter-no-tests"},{flag:"--filter-has-comments"},{flag:"--filter-no-comments"},{flag:"--filter-has-deps"},{flag:"--filter-no-deps"},{flag:"--filter-has-body"},{flag:"--filter-empty-body"},{flag:"--filter-has-linked-command"},{flag:"--filter-no-linked-command"},{flag:"--ids",list:!0},{flag:"--limit"},{flag:"--offset"}],Ba=If([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--status",list:!0},{flag:"--all",value_type:"boolean"},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--today"},{flag:"--recent"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--ids",list:!0},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...oE,{flag:"--limit"},{flag:"--offset"},{flag:"--after"},{flag:"--no-truncate"},{flag:"--compact"},{flag:"--brief"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--sort"},{flag:"--order"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--include-body"},{flag:"--strict-read"},{flag:"--format"},{flag:"--stream"}],new Set(["--limit","--token-budget","--offset","--after","--no-truncate","--compact","--brief","--full","--fields","--include-body","--strict-read"])),sE=[{flag:"--group-by",list:!0},{flag:"--count"},{flag:"--completion"},{flag:"--sum"},{flag:"--avg"},{flag:"--include-unparented"},{flag:"--include_unparented"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--assignee",list:!0},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--parent"},{flag:"--sprint",list:!0},{flag:"--release",list:!0}],aE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--comment","--body","--text"]},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}];function If(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var cE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--note","--text"]},{flag:"--add-json"},{flag:"--stdin"},{flag:"--file"},{flag:"--edit"},{flag:"--delete"},{flag:"--limit"},{flag:"--since"},{flag:"--event-type"},{flag:"--include-meta"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],lE=[{flag:"--id",value_name:"item-id"},{flag:"--add",aliases:["--learning","--text"]},{flag:"--limit"},{flag:"--full-history"},{flag:"--if-absent",value_type:"boolean"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],dE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--append-stable"},{flag:"--validate-paths"},{flag:"--scope"},{flag:"--limit"},{flag:"--offset"},{flag:"--no-truncate"},{flag:"--strict-read"},{flag:"--explain"},{flag:"--lines",value_name:"start:end"},{flag:"--decision-depth",value_name:"n",value_type:"number"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],uE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-glob"},{flag:"--remove"},{flag:"--migrate"},{flag:"--note"},{flag:"--list"},{flag:"--validate-paths"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],fE=[{flag:"--id",value_name:"item-id"},{flag:"--limit"},{flag:"--compact"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--diff"},{flag:"--field"},{flag:"--verify"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--format"}],pE=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],mE=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],_E=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],gE=[{flag:"--event",repeatable:!0},{flag:"--all-actionable"},{flag:"--dry-run"},{flag:"--plan-fingerprint"},{flag:"--limit",value_type:"number"},{flag:"--attributed-author",aliases:["--attributed_author"]},{flag:"--reviewer"},{flag:"--reason"}],yE=[{flag:"--id",value_name:"item-id"},{flag:"--before"},{flag:"--ids",list:!0},{flag:"--all-over",value_type:"number"},{flag:"--closed"},{flag:"--all-streams"},{flag:"--min-entries",value_type:"number"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],hE=[{flag:"--description"},{flag:"--default-status",aliases:["--default_status"]},{flag:"--folder"},{flag:"--alias"},{flag:"--role"},{flag:"--order"},{flag:"--type"},{flag:"--commands"},{flag:"--cli-flag"},{flag:"--required"},{flag:"--required-on-create"},{flag:"--no-allow-unset"},{flag:"--required-types"},{flag:"--infer"},{flag:"--min-count"},{flag:"--apply",value_type:"boolean"},{flag:"--to"},{flag:"--migration-id",aliases:["--migration_id"]},{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],bE=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Rf=[{flag:"--title"},{flag:"--description"},{flag:"--scope"},{flag:"--parent"},{flag:"--related"},{flag:"--blocks"},{flag:"--blocked-by",aliases:["--blocked_by"]},{flag:"--harness"},{flag:"--mode"},{flag:"--resume-context",aliases:["--resume_context"]},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--priority"},{flag:"--status",short:"-s"},{flag:"--create-mode",aliases:["--create_mode"]},{flag:"--deadline"},{flag:"--estimate",aliases:["--estimated-minutes","--estimated_minutes"]},{flag:"--acceptance-criteria",aliases:["--acceptance_criteria","--ac"],repeatable:!0},{flag:"--definition-of-ready",aliases:["--definition_of_ready"]},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now",aliases:["--why_now"]},{flag:"--assignee"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-reason",aliases:["--blocked_reason"]},{flag:"--unblock-note",aliases:["--unblock_note"]},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps",aliases:["--repro_steps"]},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--affected-version",aliases:["--affected_version"]},{flag:"--fixed-version",aliases:["--fixed_version"]},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact",aliases:["--customer_impact"]},{flag:"--comment",repeatable:!0},{flag:"--note",repeatable:!0},{flag:"--learning",repeatable:!0},{flag:"--reminder",repeatable:!0},{flag:"--event",repeatable:!0},{flag:"--type-option",aliases:["--type_option"],repeatable:!0},{flag:"--body"},{flag:"--claim"},{flag:"--from-search",aliases:["--from_search"]},{flag:"--template"},{flag:"--step-title",aliases:["--step_title"]},{flag:"--step"},{flag:"--step-body",aliases:["--step_body"]},{flag:"--step-owner",aliases:["--step_owner"]},{flag:"--step-status",aliases:["--step_status"]},{flag:"--step-evidence",aliases:["--step_evidence"]},{flag:"--step-blocked-reason",aliases:["--step_blocked_reason"]},{flag:"--step-replacement",aliases:["--step_replacement"]},{flag:"--depends-on",aliases:["--depends_on"]},{flag:"--link"},{flag:"--link-kind",aliases:["--link_kind"]},{flag:"--link-note",aliases:["--link_note"]},{flag:"--promote-to-item-dep",aliases:["--promote_to_item_dep"]},{flag:"--allow-multiple-active",aliases:["--allow_multiple_active"]},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--decision-text",aliases:["--decision_text","--decision"]},{flag:"--decision-rationale",aliases:["--decision_rationale"]},{flag:"--decision-evidence",aliases:["--decision_evidence"]},{flag:"--discovery-text",aliases:["--discovery_text","--discovery"]},{flag:"--validation-text",aliases:["--validation_text","--validation"]},{flag:"--validation-command",aliases:["--validation_command"]},{flag:"--validation-expected",aliases:["--validation_expected"]},{flag:"--depth"},{flag:"--field"},{flag:"--fields",list:!0},{flag:"--steps"},{flag:"--materialize-type",aliases:["--materialize_type"]},{flag:"--materialize-parent",aliases:["--materialize_parent"]},{flag:"--materialize-tags",aliases:["--materialize_tags"]},{flag:"--author"},{flag:"--message"},{flag:"--force"}],wE=[{flag:"--id-prefix",aliases:["--prefix"]},{flag:"--preset"},{flag:"--type-preset"},{flag:"--defaults",short:"-y",aliases:["--yes"]},{flag:"--author"},{flag:"--agent-guidance"},{flag:"--with-packages"},{flag:"--no-merge-fence"},{flag:"--workspace"},{flag:"--force"},{flag:"--verbose"}],EE=[{flag:"--criterion"},{flag:"--clear-criteria"},{flag:"--format"},{flag:"--policy"},{flag:"--default-depth"},{flag:"--activity-limit"},{flag:"--stale-threshold-days"},{flag:"--section-hierarchy"},{flag:"--section-activity"},{flag:"--section-progress"},{flag:"--section-blockers"},{flag:"--section-files"},{flag:"--section-workload"},{flag:"--section-staleness"},{flag:"--section-tests"}],Nf=[{flag:"--init"},{flag:"--scaffold"},{flag:"--capability"},{flag:"--install"},{flag:"--uninstall"},{flag:"--explore"},{flag:"--list"},{flag:"--manage"},{flag:"--describe"},{flag:"--markdown"},{flag:"--output"},{flag:"--reload"},{flag:"--watch"},{flag:"--doctor"},{flag:"--catalog"},{flag:"--adopt"},{flag:"--adopt-all"},{flag:"--activate"},{flag:"--deactivate"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"},{flag:"--detail"},{flag:"--trace"},{flag:"--runtime-probe"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],ke=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],Df=[...ke,{flag:"--capability"}],Af=[...Nf,{flag:"--declarative"}],vE=[...Df,{flag:"--declarative"}],TE=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],kE=ke,AE=ke,SE=[...ke,{flag:"--markdown"},{flag:"--output"}],xE=ke,CE=ke,OE=ke,IE=[...ke,{flag:"--dry-run"}],RE=[...ke,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],NE=[...ke,{flag:"--watch"}],DE=[...ke,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],Sf=[...ke,{flag:"--fields",list:!0}],PE=[...ke,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],LE=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],Pf=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}],sz=[{flag:"--mode"},{flag:"--progress"}],ME=[{flag:"--id",value_name:"item-id"},{flag:"--reason",value_name:"value"},{flag:"--close-reason",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--duplicate-of",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",aliases:["--expected_result","--expected"],value_name:"value"},{flag:"--actual-result",aliases:["--actual_result","--actual"],value_name:"value"},{flag:"--force",value_type:"boolean"}],FE=[{flag:"--filter-status",list:!0},{flag:"--filter-type"},{flag:"--filter-tag"},{flag:"--filter-priority"},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee"},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint"},{flag:"--filter-release"},...iE,{flag:"--reason"},{flag:"--completed-at"},{flag:"--resolution"},{flag:"--expected-result",aliases:["--expected_result","--expected"]},{flag:"--actual-result",aliases:["--actual_result","--actual"]},{flag:"--validate-close"},{flag:"--author"},{flag:"--message"},{flag:"--force"},{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"}],$E=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],jE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"},{flag:"--if-available"},{flag:"--next"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee-filter"},{flag:"--parent"},{flag:"--sprint"},{flag:"--release"},{flag:"--max-attempts"},{flag:"--include-decisions"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--explain-ranking",aliases:["--explain_ranking"]}],UE=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],zE=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],qE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],VE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],GE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],BE=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],HE=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Lf=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...HE],WE=Lf,KE=[{flag:"--at"},{flag:"--text"},...HE],YE=[{flag:"--id",value_name:"item-id"},{flag:"--add"},{flag:"--add-json"},{flag:"--remove"},{flag:"--remove-index",repeatable:!0},{flag:"--run"},{flag:"--match"},{flag:"--only-index"},{flag:"--only-last"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--acknowledge-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"},{flag:"--measure",list:!0},{flag:"--metric-below"},{flag:"--metric-diff"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],XE=[{flag:"--status"},{flag:"--limit"},{flag:"--offset"},{flag:"--background"},{flag:"--timeout"},{flag:"--progress"},{flag:"--env-set"},{flag:"--env-clear"},{flag:"--shared-host-safe"},{flag:"--pm-context"},{flag:"--override-linked-pm-context"},{flag:"--workspace-context"},{flag:"--override-linked-workspace-context"},{flag:"--allow-untrusted-linked-tests"},{flag:"--fail-on-context-mismatch"},{flag:"--fail-on-skipped"},{flag:"--fail-on-empty-test-run"},{flag:"--require-assertions-for-pm"},{flag:"--check-context"},{flag:"--auto-pm-context"}],JE=[{flag:"--limit"}],QE=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],ZE=[{flag:"--dry-run"},{flag:"--scope"}],ev=[{flag:"--include-empty"},{flag:"--storage"},{flag:"--metadata-coverage"},{flag:"--field-utilization"},{flag:"--by-assignee"},{flag:"--by-tag"},{flag:"--by-priority"},{flag:"--tag-prefix"},{flag:"--analytics"}],tv=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],nv=[{flag:"--strict-directories"},{flag:"--require-merge-drivers"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--check-only"},{flag:"--check-telemetry"},{flag:"--no-refresh"},{flag:"--refresh-vectors"},{flag:"--verbose-stale-items"},{flag:"--verbose-author-events"},{flag:"--brief"},{flag:"--summary"},{flag:"--skip-vectors"},{flag:"--skip-integrity"},{flag:"--skip-drift"},{flag:"--full"}],rv=[{flag:"--check-metadata"},{flag:"--metadata-profile"},{flag:"--check-resolution"},{flag:"--check-lifecycle"},{flag:"--check-stale-blockers"},{flag:"--dependency-cycle-severity"},{flag:"--parent-cycle-severity"},{flag:"--check-files"},{flag:"--scan-mode"},{flag:"--include-pm-internals"},{flag:"--verbose-file-lists"},{flag:"--verbose-diagnostics"},{flag:"--all-affected-ids"},{flag:"--strict-exit"},{flag:"--fail-on-warn"},{flag:"--fix-hints"},{flag:"--auto-fix"},{flag:"--dry-run"},{flag:"--fix-scope"},{flag:"--prune-missing"},{flag:"--check-history-drift"},{flag:"--check-command-references"},{flag:"--check-storage-integrity"},{flag:"--counts"},{flag:"--full"}],Mf=[{flag:"--definition",value_name:"json"},{flag:"--trigger",value_name:"value"},{flag:"--tree",value_name:"value"},{flag:"--gate",value_name:"id"},{flag:"--limit",value_name:"number"},{flag:"--dry-run"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--owner",value_name:"item-id"},{flag:"--apply",value_type:"boolean"},{flag:"--enforcement",value_name:"level"}],ov=[{flag:"--assignee"},{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--allow-unresolved-deps"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--blocked-by"},{flag:"--blocked-reason"},{flag:"--unblock-note"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--actual-result"},{flag:"--affected-version"},{flag:"--fixed-version"}],iv=[{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"}],sv=[{short:"-p",flag:"--priority"},{flag:"--type"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{flag:"--remove-tags",aliases:["--remove_tags"]},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--add-ac",aliases:["--add_ac"]},{flag:"--remove-ac",aliases:["--remove_ac"]}],xf=[{flag:"--stdin-json"},{short:"-t",flag:"--title"},{flag:"--id"},{short:"-d",flag:"--description"},{flag:"--type"},{flag:"--template"},{flag:"--create-mode"},{flag:"--create_mode"},{flag:"--schedule-preset"},{flag:"--schedule_preset"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},{flag:"--completed_at"},{short:"-p",flag:"--priority"},{flag:"--tags",aliases:["--tag"],list:!0},{flag:"--add-tags",aliases:["--add_tags"]},{short:"-b",flag:"--body"},{flag:"--body-file"},{flag:"--deadline"},{flag:"--estimate"},{flag:"--estimated-minutes"},{flag:"--estimated_minutes"},{flag:"--acceptance-criteria"},{flag:"--acceptance_criteria"},{flag:"--ac"},{flag:"--author"},{flag:"--message"},...ov,...iv,{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--fixed_version"},{flag:"--dep"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--reminder"},{flag:"--event"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--allow-duplicate",value_type:"boolean"}],av=[{flag:"--transaction-id",value_name:"value"},{flag:"--stdin-json"},{flag:"--dry-run"},{flag:"--create-compensation",value_name:"mode"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--author",value_name:"value"}],cv=[{flag:"--id",value_name:"item-id"},{flag:"--transaction-id",value_name:"value",required:!0},{flag:"--reason",value_name:"value"},{flag:"--file",value_name:"value",repeatable:!0},{flag:"--doc",value_name:"value",repeatable:!0},{flag:"--test",value_name:"value",repeatable:!0},{flag:"--comment",value_name:"value",repeatable:!0},{flag:"--note",value_name:"value",repeatable:!0},{flag:"--learning",value_name:"value",repeatable:!0},{flag:"--resolution",value_name:"value"},{flag:"--expected-result",value_name:"value"},{flag:"--actual-result",value_name:"value"},{flag:"--completed-at",value_name:"value"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--lock-ttl-seconds",value_name:"n"},{flag:"--lock-wait-ms",value_name:"n"},{flag:"--dry-run"},{flag:"--force"},{flag:"--author",value_name:"value"}],lv=[{flag:"--id",value_name:"item-id"},{flag:"--status",value_name:"open|in_progress"},{flag:"--message",value_name:"value"},{flag:"--force"},{flag:"--author",value_name:"value"}],dv=[{flag:"--id",value_name:"item-id"},{flag:"--title",value_name:"value"},{flag:"--author",value_name:"value"},{flag:"--message",value_name:"value"},{flag:"--allow-duplicate",value_type:"boolean"}],uv=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],fv=[{flag:"--id",value_name:"item-id"},{flag:"--stdin-json"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},{flag:"--body-file"},{short:"-s",flag:"--status"},{flag:"--close-reason"},{flag:"--close_reason"},{flag:"--completed-at"},...sv,...ov,{flag:"--fixed_version"},...iv,{flag:"--author"},{flag:"--message"},{flag:"--blocked_by"},{flag:"--blocked_reason"},{flag:"--unblock_note"},{flag:"--repro_steps"},{flag:"--expected_result"},{flag:"--actual_result"},{flag:"--expected"},{flag:"--actual"},{flag:"--affected_version"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file",aliases:["--linked-file"]},{flag:"--test",aliases:["--linked-test"]},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--field"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--force"}],pv=[{flag:"--filter-status",list:!0},{flag:"--filter-type",list:!0},{flag:"--filter-tag",list:!0},{flag:"--filter-priority",list:!0},{flag:"--filter-deadline-before"},{flag:"--filter-deadline-after"},{flag:"--filter-updated-after"},{flag:"--filter-updated-before"},{flag:"--filter-created-after"},{flag:"--filter-created-before"},{flag:"--filter-assignee",list:!0},{flag:"--filter-assignee-filter"},{flag:"--filter-assignee_filter"},{flag:"--filter-parent"},{flag:"--filter-sprint",list:!0},{flag:"--filter-release",list:!0},{flag:"--filter-ac-missing"},{flag:"--filter-estimates-missing",aliases:["--filter-estimate-missing"]},{flag:"--filter-resolution-missing"},{flag:"--filter-metadata-missing"},...iE,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...sv,{flag:"--definition-of-ready"},{flag:"--definition_of_ready"},{flag:"--order"},{flag:"--rank"},{flag:"--goal"},{flag:"--objective"},{flag:"--value"},{flag:"--impact"},{flag:"--outcome"},{flag:"--why-now"},{flag:"--why_now"},{flag:"--reviewer"},{flag:"--risk"},{flag:"--confidence"},{flag:"--sprint"},{flag:"--release"},{flag:"--reporter"},{flag:"--severity"},{flag:"--environment"},{flag:"--repro-steps"},{flag:"--repro_steps"},{flag:"--resolution"},{flag:"--expected-result"},{flag:"--expected_result"},{flag:"--expected"},{flag:"--actual-result"},{flag:"--actual_result"},{flag:"--actual"},{flag:"--affected-version"},{flag:"--affected_version"},{flag:"--fixed-version"},{flag:"--fixed_version"},{flag:"--component"},{flag:"--regression"},{flag:"--customer-impact"},{flag:"--customer_impact"},{flag:"--allow-unresolved-deps"},{flag:"--dep"},{flag:"--dep-remove"},{flag:"--dep_remove"},{flag:"--replace-deps"},{flag:"--replace-tests"},{flag:"--replace-files"},{flag:"--replace-docs"},{flag:"--comment"},{flag:"--note"},{flag:"--learning"},{flag:"--file"},{flag:"--test"},{flag:"--doc"},{flag:"--reminder"},{flag:"--event"},{flag:"--type-option"},{flag:"--type_option"},{flag:"--unset"},{flag:"--clear-deps"},{flag:"--clear-comments"},{flag:"--clear-notes"},{flag:"--clear-learnings"},{flag:"--clear-files"},{flag:"--clear-tests"},{flag:"--clear-docs"},{flag:"--clear-reminders"},{flag:"--clear-events"},{flag:"--clear-type-options"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Cf=[{flag:"--view"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--full-period"},{flag:"--full_period"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--status"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--include"},{flag:"--recurrence-lookahead-days"},{flag:"--recurrence-lookback-days"},{flag:"--occurrence-limit"},{flag:"--limit"},{flag:"--format"}],mv=[{flag:"--id"},{flag:"--op"},{flag:"--author"},{flag:"--from"},{flag:"--to"},{flag:"--limit"},{flag:"--unbounded"},{flag:"--compact"},{flag:"--raw"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--stream"}],_v=[{flag:"--since"},{flag:"--type",repeatable:!0},{flag:"--author",repeatable:!0},{flag:"--item",repeatable:!0},{flag:"--limit",value_type:"number"},{flag:"--cursor-mode",value_name:"batch|row"},{flag:"--full"},{flag:"--provenance"},{flag:"--provenance-summary"},{flag:"--harness",repeatable:!0},{flag:"--agent-instance",repeatable:!0},{flag:"--provenance-filter",repeatable:!0},{flag:"--follow"},{flag:"--interval-ms",value_type:"number"}],Of=If([{flag:"--for",value_name:"intent"},{flag:"--date"},{flag:"--from"},{flag:"--to"},{flag:"--past"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit",aliases:["--max-items"]},{flag:"--after"},{flag:"--format"},{flag:"--depth"},{flag:"--fields",list:!0},{flag:"--section"},{flag:"--activity-limit"},{flag:"--stale-threshold"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--no-extension-health"},{flag:"--no-tags"}],new Set(["--limit","--after","--format","--fields","--section","--activity-limit","--stale-threshold","--explain-ranking","--explain_ranking","--no-extension-health","--no-tags"])),gv=[{flag:"--id",value_name:"item-id"},{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--depth"},{flag:"--full",value_type:"boolean"},{flag:"--fields",list:!0},{flag:"--at"},{flag:"--tree"},{flag:"--tree-depth"},{flag:"--tree_depth"},{flag:"--format"}],yv=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],hv=[{flag:"--id",value_name:"item-id"},{flag:"--format"},{flag:"--max-depth"},{flag:"--collapse"},{flag:"--summary"},{flag:"--full"},{flag:"--node-limit"},{flag:"--edge-limit"},{flag:"--token-budget"},{flag:"--cursor"},{flag:"--direction"},{flag:"--kind",list:!0}],bv=[{flag:"--kind",list:!0},{flag:"--max-depth"},{flag:"--limit"},{flag:"--after"},{flag:"--direction"},{flag:"--max-paths"},{flag:"--sample"},{flag:"--exempt-isolate",list:!0},{flag:"--exempt-isolate-type",list:!0},{flag:"--save-baseline"},{flag:"--rebuild"},{flag:"--clear"},{flag:"--summary"},{flag:"--full"}],wv=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],Ot=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],Ev=[],vv=[{flag:"--for",value_name:"intent"},{flag:"--type"},{flag:"--tag"},{flag:"--priority"},{flag:"--assignee"},{flag:"--assignee-filter"},{flag:"--assignee_filter"},{flag:"--sprint"},{flag:"--release"},{flag:"--parent"},{flag:"--limit"},{flag:"--blocked-limit"},{flag:"--blocked_limit"},{flag:"--ready-only"},{flag:"--ready_only"},{flag:"--format"},{flag:"--explain-ranking"},{flag:"--explain_ranking"},{flag:"--token-budget",aliases:["--token_budget"]}],Tv=If([{flag:"--for",value_name:"intent"},{flag:"--token-budget",aliases:["--token_budget"]},{flag:"--mode"},{flag:"--semantic"},{flag:"--hybrid"},{flag:"--match-mode"},{flag:"--min-score"},{flag:"--count"},{flag:"--semantic-weight"},{flag:"--include-linked"},{flag:"--title-exact"},{flag:"--phrase-exact"},{flag:"--highlight"},{flag:"--compact"},{flag:"--full"},{flag:"--fields",list:!0},{flag:"--format"},{flag:"--limit"},{flag:"--after"},{flag:"--status",list:!0},{flag:"--type",list:!0},{flag:"--tag",aliases:["--tags"],list:!0},{flag:"--priority",list:!0},{flag:"--deadline-before"},{flag:"--deadline-after"},{flag:"--updated-after"},{flag:"--updated-before"},{flag:"--created-after"},{flag:"--created-before"},{flag:"--assignee",list:!0},{flag:"--sprint",list:!0},{flag:"--release",list:!0},{flag:"--parent"},...oE],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),kv=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],Av=[{flag:"--eager-tags"}];function za(e){let t=new Map;for(let n of[...Ga,...e]){let r=qa(n.flag),o=t.get(r),{aliases:i,...s}=n,a=zn([...i??[],...n.flag===r?[]:[n.flag]]).filter(d=>d!==r),c={...s,flag:r,...a.length>0?{aliases:a}:{}},l=zn([...o?.aliases??[],...c.aliases??[]]);t.set(r,o===void 0?c:{...o,...c,...l.length>0?{aliases:l}:{}})}return ti([...t.values()])}var az=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],cz=Ba.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),lz=Ba.filter(e=>e.flag!=="--status");function Va(e){let t=new Map;for(let n of e)for(let r of[n.flag,...n.aliases??[]]){let o=t.get(r)??[];o.push(n),t.set(r,o)}return t}var dz=Va(Rf),uz=Va(Mf),fz=new Map([["assurance",uz],["plan",dz],["workspace",Va(Ev)],["workspace snapshot",Va(Ot)]]);function Sv(e=Un){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=fz.get(n);if(!o)throw new Error(`Positional action ${t} has no flag-contract index for ${n}.`);let i=r.map(s=>{let a=o.get(s)??[];if(a.length!==1)throw new Error(`Positional action ${t} accepted flag ${s} does not resolve to exactly one ${n} flag contract.`);return a[0]});return[t,i]})}var pz=Sv(),xv=new Map([["list",Ba],["list-all",lz],...az.map(e=>[e,cz]),["templates",xf],["cal",Cf],["ctx",Of],["test-runs-worker",QE],["init",wE],["config",EE],["extension",Nf],["package",Af],["packages",Af],["install",LE],["upgrade",Pf],["create",xf],["item mutate",av],["item complete",cv],["item reopen",lv],["copy",dv],["focus",uv],["aggregate",sE],["calendar",Cf],["context",Of],["get",gv],["guide",yv],["search",Tv],["next",vv],["eval",wv],["workspace",Ot],["workspace position",Ev],["workspace snapshot",Ot],["workspace snapshot create",Ot],["workspace snapshot list",Ot],["workspace snapshot inspect",Ot],["workspace snapshot restore",Ot],["workspace snapshot delete",Ot],["history",fE],["history-redact",mE],["history-repair",_E],["history-author-acknowledge",gE],["history-compact",yE],["merge",pE],["schema",hE],["profile",bE],["plan",Rf],["activity",mv],["events",_v],["restore",UE],["update",fv],["update-many",pv],["close",ME],["close-many",FE],["delete",zE],["append",$E],["comments",aE],["notes",cE],["learnings",lE],["files",dE],["docs",uE],["deps",hv],["graph",bv],["test",YE],["test-all",XE],["telemetry",JE],["health",nv],["assurance",Mf],...pz,["validate",rv],["gc",ZE],["stats",ev],["duplicates",tv],["contracts",kv],["completion",Av],["claim",jE],["release",qE],["start-task",VE],["pause-task",GE],["close-task",BE],["meet",Lf],["event",WE],["remind",KE]]),Cv=new Map([["install",TE],["uninstall",kE],["explore",AE],["manage",RE],["describe",SE],["reload",NE],["doctor",DE],["catalog",Sf],["list",Sf],["adopt",PE],["adopt-all",xE],["activate",CE],["deactivate",OE],["migrate",IE]]);function Ov(e){return typeof e!="string"?"":e.trim().toLowerCase()}function mz(e){let t=Ov(e);if(xv.has(t))return!0;let[n,r,...o]=t.split(/\s+/);return(n==="extension"||n==="package"||n==="packages")&&r!==void 0&&o.length===0&&(r==="init"||r==="scaffold"||Cv.has(r))}function _z(e,t){return t==="init"||t==="scaffold"?e==="extension"?Df:vE:Cv.get(t)??[]}function Ff(e){let t=Ov(e);if(t.length===0)return za([]);let[n,r,...o]=t.split(/\s+/);if((n==="extension"||n==="package"||n==="packages")&&r!==void 0&&o.length===0)return za((n==="package"||n==="packages")&&r==="upgrade"?Pf:_z(n,r));let i=xv.get(t)??[];return za(i)}function gz(e,t=!0){let r=ti(e).flatMap(i=>[i.short,i.flag,...i.aliases??[]]).filter(i=>!!i),o=t?[...r,...Ga.flatMap(i=>[i.short,i.flag,...i.aliases??[]]).filter(i=>!!i)]:r;return zn(o).join(" ")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="19a97f60-3b6e-5653-a652-02aebaf5afdd")}catch{}})();var Iv={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},Rv={if:{required:["field"]}};Reflect.set(Rv,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var Nv={oneOf:[{type:"object",additionalProperties:!1,required:["id","source"],properties:{id:{type:"string",minLength:1},description:{type:"string"},max_cost:{type:"number",minimum:0},source:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],allOf:[Rv],properties:{kind:{const:"items"},statuses:{type:"array",items:{type:"string"}},types:{type:"array",items:{type:"string"}},tags:{type:"array",items:{type:"string"}},field:{type:"string"},equals:{type:["string","number","boolean","null"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","dependency_kind"],properties:{kind:{const:"dependency_kind"},dependency_kind:{type:"string",minLength:1}}},{type:"object",required:["kind","operation","field"],properties:{kind:{const:"graph"},operation:{type:"string",minLength:1},field:{type:"string",minLength:1},parameters:{type:"object"}},additionalProperties:!1},...["validate","health"].map(e=>({type:"object",required:["kind","check","field"],properties:{kind:{const:e},check:{type:"string",minLength:1},field:{type:"string",minLength:1}},additionalProperties:!1})),{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{const:"history"},op:{type:"string"},author:{type:"string"},harness:{type:"string"},model:{type:"string"}}},{type:"object",additionalProperties:!1,required:["kind","link","state"],properties:{kind:{const:"links"},link:{enum:["files","tests","docs"]},state:{enum:["present","missing"]}}},{type:"object",additionalProperties:!1,required:["kind","provider","key"],properties:{kind:{const:"provider"},provider:{type:"string",minLength:1},key:{type:"string",minLength:1},parameters:{type:"object"}}},{type:"object",additionalProperties:!1,required:["kind","expression"],properties:{kind:{const:"derived"},expression:{type:"object",minProperties:1}}}]}}},{type:"object",additionalProperties:!1,required:["id","measurement_id","owner_item_id","scope","enforcement","negative_control"],oneOf:[{required:["ceiling"]},{required:["floor"]},{required:["equals"]},{required:["zero"]},{required:["monotone_nondecreasing"]},{required:["monotone_nonincreasing"]},{required:["subset_of"]}],allOf:[{oneOf:[{not:{required:["lifetime"],properties:{lifetime:{const:"retire"}}}},{required:["lifetime","retire_reason"],properties:{lifetime:{const:"retire"},retire_reason:{type:"string",minLength:1}}}]}],properties:{id:{type:"string",minLength:1},measurement_id:{type:"string",minLength:1},owner_item_id:{type:"string",minLength:1},scope:{oneOf:[{type:"object",additionalProperties:!1,required:["kind"],properties:{kind:{enum:["all","active"]}}},{type:"object",additionalProperties:!1,required:["kind","measurement_id"],properties:{kind:{const:"filter"},measurement_id:{type:"string",minLength:1}}}]},ceiling:{type:"number"},floor:{type:"number"},equals:Iv,zero:{const:!0},monotone_nondecreasing:{type:"number"},monotone_nonincreasing:{type:"number"},subset_of:{type:"array",items:{type:"string"}},lifetime:{enum:["hold","retire"]},retire_reason:{type:"string",minLength:1},enforcement:{enum:["block","warn","observe"]},authorization_decision:{type:"string",minLength:1},negative_control:{type:"object",additionalProperties:!1,required:["cases"],properties:{cases:{type:"array",minItems:2,items:{type:"object",additionalProperties:!1,required:["observed","expected"],properties:{observed:Iv,expected:{enum:["pass","fail"]}}}}}}}},{type:"object",additionalProperties:!1,required:["id","assertion_ids","triggers"],properties:{id:{type:"string",minLength:1},description:{type:"string"},assertion_ids:{type:"array",minItems:1,items:{type:"string",minLength:1}},triggers:{type:"array",minItems:1,items:{enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]}},provider_policy:{type:"object",additionalProperties:!1,required:["allowed_providers","triggers"],properties:{allowed_providers:{type:"array",items:{type:"string",minLength:1}},triggers:{type:"object",additionalProperties:{type:"object",additionalProperties:!1,required:["max_cost_class","allow_network"],properties:{max_cost_class:{enum:["low","medium","high"]},allow_network:{type:"boolean"}}}}}}}}]};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6968f481-8384-5e3b-8ac0-b0972d08eeb1")}catch{}})();var ni={json:{type:"boolean",default:!0},quiet:{type:"boolean"},profile:{type:"boolean"},noExtensions:{type:"boolean"},noPager:{type:"boolean"},tokenAccounting:{type:"boolean"},outputInclude:{type:"string",minLength:1},outputLimit:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputBudget:{anyOf:[{type:"integer",minimum:1},{const:"unbounded"}]},outputFormat:{type:"string",enum:["json","toon"]},outputSession:{anyOf:[{type:"string",minLength:1},{type:"object",additionalProperties:!1,required:["version","id","token_budget","spent_tokens","seen_item_ids"],properties:{version:{const:1},id:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$"},token_budget:{type:"integer",minimum:256},spent_tokens:{type:"integer",minimum:0},seen_item_ids:{type:"array",maxItems:Ao,items:{type:"string",pattern:"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$"}}}}]},outputCursor:{type:"string",minLength:1},outputRowContract:{type:"boolean"},path:{type:"string"},pmExecutable:{type:"string"},timeoutMs:{type:"number"},id:{type:"string"},target:{type:"string"},snapshotAction:{type:"string",enum:["create","list","inspect","restore","delete"]},artifact:{type:"string",enum:["item","history","relationship","json"]},basePath:{type:"string"},oursPath:{type:"string"},theirsPath:{type:"string"},outputPath:{type:"string"},itemPath:{type:"string"},prefer:{type:"string",enum:["ours","theirs"]},includeReconciled:{type:"boolean"},lockTtlSeconds:{type:"number"},lockWaitMs:{type:"number"},capability:{type:"string",minLength:1},declarative:{type:"boolean"},output:{type:"string",minLength:1},markdown:{type:"boolean"},init:{type:"boolean"},install:{type:"boolean"},uninstall:{type:"boolean"},explore:{type:"boolean"},manage:{type:"boolean"},describe:{type:"boolean"},doctor:{type:"boolean"},catalog:{type:"boolean"},adopt:{type:"boolean"},adoptAll:{type:"boolean"},activate:{type:"boolean"},deactivate:{type:"boolean"},filterFilesMissing:{type:"boolean"},filterDocsMissing:{type:"boolean"},matchMode:{type:"string",enum:["all","any","phrase"]},minScore:{anyOf:[{type:"number"},{type:"string",pattern:"^\\d+(\\.\\d+)?$"}]},rank:{anyOf:[{type:"number"},{type:"string",pattern:"^-?\\d+$"}]},exemptIsolateType:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},saveBaseline:{type:"boolean"},rebuild:{type:"boolean"},github:{type:"string"},ref:{type:"string"},query:{type:"string"},queries:{type:"string"},k:{anyOf:[{type:"number"},{type:"string"}]},failUnder:{anyOf:[{type:"number"},{type:"string"}]},for:{type:"string",minLength:1},keywords:{type:"string"},fields:{type:"string"},sort:{type:"string",enum:["priority","deadline","updated_at","created_at","title","parent"]},prefix:{type:"string"},idPrefix:{type:"string"},workspace:{type:"string"},preset:{type:"string",enum:["minimal","default","strict","custom"]},typePreset:{type:"string",enum:["agile","ops","research"]},defaults:{type:"boolean"},verbose:{type:"boolean"},agentGuidance:{type:"string",enum:["ask","add","skip","status"]},withPackages:{type:"boolean"},mergeFence:{type:"boolean"},scope:{type:"string",enum:["project","global"]},allOver:{type:"number"},minEntries:{type:"number"},closed:{type:"boolean"},allStreams:{type:"boolean"},contractAction:{type:"string"},command:{type:"string"},summary:{type:"boolean"},schemaOnly:{type:"boolean"},flagsOnly:{type:"boolean"},availabilityOnly:{type:"boolean"},runtimeOnly:{type:"boolean"},activeOnly:{type:"boolean"},eagerTags:{type:"boolean"},fullChangedFields:{type:"boolean"},provenance:{type:"boolean"},provenanceSummary:{type:"boolean"},agentInstance:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},provenanceFilter:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},idOnly:{type:"boolean"},allowMissingParent:{type:"boolean"},allowUnresolvedDeps:{type:"boolean"},allowDuplicate:{type:"boolean"},duplicateOf:{type:"string"},configAction:{type:"string",enum:["get","set","list","export"]},key:{type:"string"},title:{type:"string"},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},start:{type:"string"},duration:{type:"string"},end:{type:"string"},location:{type:"string"},timezone:{type:"string"},allDay:{type:"boolean"},description:{type:"string"},type:{type:"string"},template:{type:"string"},createMode:{type:"string",enum:["strict","progressive"]},schedulePreset:{type:"string",enum:["lightweight"]},status:{type:"string"},since:{type:"string",format:"date-time"},cursorMode:{type:"string",enum:["batch","row"]},threshold:{type:"number",minimum:0,maximum:1},filterStatus:{type:"string"},filterType:{type:"string"},filterTag:{type:"string"},filterPriority:{anyOf:[{type:"string"},{type:"number"}]},filterDeadlineBefore:{type:"string"},filterDeadlineAfter:{type:"string"},filterUpdatedAfter:{type:"string"},filterUpdatedBefore:{type:"string"},filterCreatedAfter:{type:"string"},filterCreatedBefore:{type:"string"},filterAssignee:{type:"string"},filterAssigneeFilter:{type:"string",enum:["assigned","unassigned"]},filterParent:{type:"string"},filterSprint:{type:"string"},filterRelease:{type:"string"},closeReason:{type:"string"},completedAt:{type:"string",format:"date-time"},reason:{type:"string"},priority:{anyOf:[{type:"string"},{type:"number"}]},tags:{type:"string"},addTags:{type:"array",items:{type:"string"}},removeTags:{type:"array",items:{type:"string"}},addAc:{type:"array",items:{type:"string"}},removeAc:{type:"array",items:{type:"string"}},body:{type:"string"},deadline:{type:"string"},estimate:{anyOf:[{type:"string"},{type:"number"}]},acceptanceCriteria:{type:"string"},author:{type:"string"},message:{type:"string"},owner:{type:"string"},enforcement:{type:"string"},assignee:{type:"string"},assigneeFilter:{type:"string",enum:["assigned","unassigned"]},parent:{type:"string"},reviewer:{type:"string"},attributedAuthor:{type:"string"},planFingerprint:{type:"string",pattern:"^[a-f0-9]{64}$"},historyEvent:{type:"array",items:{type:"string"}},risk:{type:"string"},confidence:{anyOf:[{type:"string"},{type:"number"}]},sprint:{type:"string"},release:{type:"string"},blockedBy:{type:"string"},blockedReason:{type:"string"},unblockNote:{type:"string"},reporter:{type:"string"},severity:{type:"string"},environment:{type:"string"},reproSteps:{type:"string"},resolution:{type:"string"},expectedResult:{type:"string"},actualResult:{type:"string"},affectedVersion:{type:"string"},fixedVersion:{type:"string"},component:{type:"string"},regression:{anyOf:[{type:"boolean"},{type:"string"},{type:"number"}]},customerImpact:{type:"string"},definitionOfReady:{type:"string"},order:{anyOf:[{type:"string"},{type:"number"}]},goal:{type:"string"},objective:{type:"string"},value:{type:"string"},impact:{type:"string"},outcome:{type:"string"},whyNow:{type:"string"},mode:{type:"string",enum:["keyword","semantic","hybrid"]},semanticWeight:{anyOf:[{type:"string"},{type:"number"}]},op:{type:"string"},compact:{type:"boolean"},raw:{type:"boolean"},brief:{type:"boolean"},full:{type:"boolean"},includeEmpty:{type:"boolean"},view:{type:"string",enum:["agenda","day","week","month"]},date:{type:"string"},from:{type:"string"},before:{type:"string"},at:{type:"string"},to:{type:"string"},migrationId:{type:"string"},fieldTypeScope:{type:"string"},past:{type:"boolean"},fullPeriod:{type:"boolean"},include:{type:"string"},recurrenceLookaheadDays:{anyOf:[{type:"string"},{type:"number"}]},recurrenceLookbackDays:{anyOf:[{type:"string"},{type:"number"}]},occurrenceLimit:{anyOf:[{type:"string"},{type:"number"}]},includeLinked:{type:"boolean"},semantic:{type:"boolean"},hybrid:{type:"boolean"},titleExact:{type:"boolean"},phraseExact:{type:"boolean"},highlight:{type:"boolean"},includeBody:{type:"boolean"},noTruncate:{type:"boolean"},strictRead:{type:"boolean"},tag:{type:"string"},deadlineBefore:{type:"string"},deadlineAfter:{type:"string"},today:{type:"boolean"},recent:{type:"boolean"},updatedAfter:{type:"string"},updatedBefore:{type:"string"},createdAfter:{type:"string"},createdBefore:{type:"string"},filterAcMissing:{type:"boolean"},filterEstimatesMissing:{type:"boolean"},filterResolutionMissing:{type:"boolean"},filterMetadataMissing:{type:"boolean"},filterReviewerMissing:{type:"boolean"},filterRiskMissing:{type:"boolean"},filterConfidenceMissing:{type:"boolean"},filterSprintMissing:{type:"boolean"},filterReleaseMissing:{type:"boolean"},hasNotes:{type:"boolean"},noNotes:{type:"boolean"},hasLearnings:{type:"boolean"},noLearnings:{type:"boolean"},hasFiles:{type:"boolean"},noFiles:{type:"boolean"},hasDocs:{type:"boolean"},noDocs:{type:"boolean"},hasTests:{type:"boolean"},noTests:{type:"boolean"},hasComments:{type:"boolean"},noComments:{type:"boolean"},hasDeps:{type:"boolean"},noDeps:{type:"boolean"},hasBody:{type:"boolean"},emptyBody:{type:"boolean"},hasLinkedCommand:{type:"boolean"},noLinkedCommand:{type:"boolean"},filterHasNotes:{type:"boolean"},filterNoNotes:{type:"boolean"},filterHasLearnings:{type:"boolean"},filterNoLearnings:{type:"boolean"},filterHasFiles:{type:"boolean"},filterNoFiles:{type:"boolean"},filterHasDocs:{type:"boolean"},filterNoDocs:{type:"boolean"},filterHasTests:{type:"boolean"},filterNoTests:{type:"boolean"},filterHasComments:{type:"boolean"},filterNoComments:{type:"boolean"},filterHasDeps:{type:"boolean"},filterNoDeps:{type:"boolean"},filterHasBody:{type:"boolean"},filterEmptyBody:{type:"boolean"},filterHasLinkedCommand:{type:"boolean"},filterNoLinkedCommand:{type:"boolean"},ids:{type:"string"},limit:{anyOf:[{type:"string"},{type:"number"}]},blockedLimit:{anyOf:[{type:"string"},{type:"number"}]},readyOnly:{type:"boolean"},offset:{anyOf:[{type:"string"},{type:"number"}]},progress:{type:"boolean"},background:{type:"boolean"},runId:{type:"string"},stream:{anyOf:[{type:"boolean"},{type:"string",enum:["stdout","stderr","both","rows","ndjson","jsonl"]}]},tail:{anyOf:[{type:"string"},{type:"number"}]},addJson:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},eventType:{type:"string"},includeMeta:{type:"boolean"},allActionable:{type:"boolean"},verboseAuthorEvents:{type:"boolean"},match:{type:"string"},onlyIndex:{anyOf:[{type:"string"},{type:"number"}]},removeIndex:{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}},onlyLast:{type:"boolean"},envSet:{type:"array",items:{type:"string"}},envClear:{type:"array",items:{type:"string"}},sharedHostSafe:{type:"boolean"},detail:{type:"string",enum:["summary","deep"]},trace:{type:"boolean"},reload:{type:"boolean"},watch:{type:"boolean"},runtimeProbe:{type:"boolean"},fixManagedState:{type:"boolean"},isolated:{type:"boolean"},ignoreGlobal:{type:"boolean"},pmContext:{type:"string",enum:["schema","tracker","auto"]},overrideLinkedPmContext:{type:"boolean"},workspaceContext:{type:"string",enum:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{type:"boolean"},allowUntrustedLinkedTests:{type:"boolean"},acknowledgeLinkedTests:{type:"boolean"},failOnContextMismatch:{type:"boolean"},failOnSkipped:{type:"boolean"},failOnEmptyTestRun:{type:"boolean"},requireAssertionsForPm:{type:"boolean"},checkContext:{type:"boolean"},autoPmContext:{type:"boolean"},measure:{type:"array",items:{type:"string"}},metricBelow:{type:"string"},metricDiff:{type:"string"},diff:{type:"boolean"},storage:{type:"boolean"},metadataCoverage:{type:"boolean"},fieldUtilization:{type:"boolean"},byAssignee:{type:"boolean"},byTag:{type:"boolean"},byPriority:{type:"boolean"},tagPrefix:{type:"string"},measurements:{type:"boolean"},metric:{type:"string"},measurementLimit:{type:"integer",minimum:0,maximum:1e3},observe:{type:"array",items:{type:"string"}},improvementDirection:{type:"string",enum:["higher","lower","target"]},measurementSource:{type:"string"},measurementItem:{type:"string"},measurementRevision:{type:"string"},provenanceCoverage:{type:"boolean"},fleetAttribution:{type:"boolean"},eventLimit:{type:"integer",minimum:1,maximum:1e5},minimumSample:{type:"integer",minimum:1,maximum:1e4},verify:{type:"boolean"},literal:{type:"array",items:{type:"string"}},regex:{type:"array",items:{type:"string"}},replacement:{type:"string"},timeout:{anyOf:[{type:"string"},{type:"number"}]},validateClose:{type:"string",enum:["off","warn","strict"]},checkMetadata:{type:"boolean"},metadataProfile:{type:"string",enum:["core","strict","custom"]},checkResolution:{type:"boolean"},checkLifecycle:{type:"boolean"},checkStaleBlockers:{type:"boolean"},dependencyCycleSeverity:{type:"string",enum:["off","warn","error"]},parentCycleSeverity:{type:"string",enum:["off","warn","error"]},checkFiles:{type:"boolean"},checkStorageIntegrity:{type:"boolean"},strictDirectories:{type:"boolean"},requireMergeDrivers:{type:"boolean"},checkOnly:{type:"boolean"},checkTelemetry:{type:"boolean"},noRefresh:{type:"boolean"},refreshVectors:{type:"boolean"},verboseStaleItems:{type:"boolean"},skipVectors:{type:"boolean"},skipIntegrity:{type:"boolean"},skipDrift:{type:"boolean"},verboseDiagnostics:{type:"boolean"},allAffectedIds:{type:"boolean"},scanMode:{type:"string",enum:["default","tracked-all","tracked-all-strict"]},includePmInternals:{type:"boolean"},verboseFileLists:{type:"boolean"},strictExit:{type:"boolean"},failOnWarn:{type:"boolean"},fixHints:{type:"boolean"},autoFix:{type:"boolean"},fixScope:{type:"array",items:{type:"string",enum:["metadata","resolution","estimates","lifecycle"]}},pruneMissing:{type:"boolean"},checkHistoryDrift:{type:"boolean"},checkCommandReferences:{type:"boolean"},counts:{type:"boolean"},edit:{type:"integer",minimum:1},delete:{type:"integer",minimum:1},dryRun:{type:"boolean"},normalizeProvenance:{type:"boolean"},all:{type:"boolean"},clear:{type:"boolean"},cliOnly:{type:"boolean"},packagesOnly:{type:"boolean"},repair:{type:"boolean"},packageName:{type:"string"},rollback:{type:"string"},noCheckpoint:{type:"boolean"},force:{type:"boolean"},ifAvailable:{type:"boolean"},ifAbsent:{type:"boolean"},next:{type:"boolean"},maxAttempts:{anyOf:[{type:"integer",minimum:1,maximum:100},{type:"string",pattern:"^(?:[1-9]|[1-9][0-9]|100)$"}]},includeDecisions:{type:"boolean"},explainRanking:{type:"boolean"},noTags:{type:"boolean"},noExtensionHealth:{type:"boolean"},run:{type:"boolean"},count:{type:"boolean"},sum:{type:"string"},avg:{type:"string"},tree:{type:"boolean"},treeId:{type:"string",minLength:1},definition:{type:"object"},trigger:{type:"string",enum:["pre-commit","pre-push","pre-merge","ci","pre-release","post-release","scheduled","on-claim","on-close"]},gate:{type:"string",minLength:1},treeDepth:{anyOf:[{type:"string"},{type:"number"}]},includeUnparented:{type:"boolean"},gcScope:{type:"array",items:{type:"string",enum:["index","embeddings","runtime","locks"]}},maxDepth:{anyOf:[{type:"string"},{type:"number"}]},nodeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},edgeLimit:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},tokenBudget:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},cursor:{type:"string"},direction:{type:"string",enum:["outgoing","incoming","both"]},kind:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},after:{type:"string"},maxPaths:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},sample:{anyOf:[{type:"string"},{type:"integer",minimum:1}]},exemptIsolate:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},collapse:{type:"string",enum:["none","repeated"]},shell:{type:"string",enum:["bash","zsh","fish"]},stdin:{type:"boolean"},file:{type:"string"},preserveSourceIds:{type:"boolean"},folder:{type:"string"},subcommand:{type:"string"},name:{type:"string"},defaultStatus:{type:"string"},alias:{type:"array",items:{type:"string"}},role:{type:"array",items:{type:"string"}},fieldType:{type:"string",enum:["string","number","boolean","string_array"]},commands:{type:"array",items:{type:"string"}},cliFlag:{type:"string"},required:{type:"boolean"},requiredOnCreate:{type:"boolean"},allowUnset:{type:"boolean"},requiredTypes:{type:"array",items:{type:"string"}},infer:{type:"boolean"},minCount:{type:"number"},text:{type:"string"},add:{type:"array",items:{type:"string"}},addGlob:{type:"array",items:{type:"string"}},remove:{type:"array",items:{type:"string"}},migrate:{type:"array",items:{type:"string"}},discover:{type:"boolean"},apply:{type:"boolean"},discoveryNote:{type:"string"},lookupPath:{type:"array",items:{type:"string"}},explain:{type:"boolean"},lines:{type:"string",pattern:"^[1-9]\\d*:[1-9]\\d*$"},decisionDepth:{type:"integer",minimum:1,maximum:32},addNote:{type:"string"},list:{type:"boolean"},appendStable:{type:"boolean"},validatePaths:{type:"boolean"},dep:{type:"array",items:{type:"string"}},depRemove:{type:"array",items:{type:"string"}},replaceDeps:{type:"boolean"},replaceTests:{type:"boolean"},replaceFiles:{type:"boolean"},replaceDocs:{type:"boolean"},comment:{type:"array",items:{type:"string"}},note:{type:"array",items:{type:"string"}},learning:{type:"array",items:{type:"string"}},linkedFile:{type:"array",items:{type:"string"}},linkedTest:{type:"array",items:{type:"string"}},doc:{type:"array",items:{type:"string"}},reminder:{type:"array",items:{type:"string"}},event:{type:"array",items:{type:"string"}},typeOption:{type:"array",items:{type:"string"}},field:{type:"array",items:{type:"string"}},unset:{type:"array",items:{type:"string"}},clearDeps:{type:"boolean"},clearComments:{type:"boolean"},clearNotes:{type:"boolean"},clearLearnings:{type:"boolean"},clearFiles:{type:"boolean"},clearTests:{type:"boolean"},clearDocs:{type:"boolean"},clearReminders:{type:"boolean"},clearEvents:{type:"boolean"},clearTypeOptions:{type:"boolean"},criterion:{type:"array",items:{type:"string"}},clearCriteria:{type:"boolean"},groupBy:{type:"string"},completion:{type:"boolean"},format:{type:"string"},unbounded:{type:"boolean"},depth:{type:"string",enum:["brief","standard","deep","full"]},section:{type:"array",items:{type:"string",enum:["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]}},activityLimit:{anyOf:[{type:"string"},{type:"number"}]},staleThreshold:{type:"string"},policy:{type:"string"}},Dv={assurance:{definition:Nv,kind:{type:"string",enum:["measurement","assertion","gate"]},subcommand:{type:"string",enum:["list","show","put","remove","run","verdicts","presets","apply","derive","promote","risk"]},preset:{type:"string",enum:["software-delivery","research","agent-evaluation","operations"]},enforcement:{type:"string",enum:["warn","block"]},limit:{type:"integer",minimum:1,maximum:1e3}},activity:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},"update-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"close-many":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},"history-compact":{ids:{anyOf:[{type:"string"},{type:"number"},{type:"array",items:{anyOf:[{type:"string"},{type:"number"}]}}]}},events:{since:{type:"string",minLength:1},type:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},author:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},item:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},limit:{type:"integer",minimum:0,maximum:1e3},harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},history:{harness:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},remind:{at:{type:"string",minLength:1}}},yz=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],$f={subcommand:{type:"string",enum:[...yz]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...fp]},mode:{type:"string",enum:[...up]},resumeContext:{type:"string"},related:{type:"string"},blocks:{type:"string"},claim:{type:"boolean"},fromSearch:{type:"string"},stepTitle:{type:"string"},step:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},stepBody:{type:"string"},stepOwner:{type:"string"},stepStatus:{type:"string",enum:[...Ai]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...pp]},linkNote:{type:"string"},promoteToItemDep:{type:"boolean"},allowMultipleActive:{type:"boolean"},file:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},test:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},doc:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]},decisionText:{type:"string"},decision:{type:"string"},decisionRationale:{type:"string"},decisionEvidence:{type:"string"},discoveryText:{type:"string"},discovery:{type:"string"},validationText:{type:"string"},validation:{type:"string"},validationCommand:{type:"string"},validationExpected:{type:"string"},steps:{type:"array",items:{type:"string"}},materializeType:{type:"string"},materializeParent:{type:"string"},materializeTags:{type:"string"},field:{anyOf:[{type:"string"},{type:"array",items:{type:"string"}}]}},jf={subcommand:{description:"Plan workflow operation to run.",examples:["create","show","add-step","approve"]},stepRef:{description:"Plan step id or order for step lifecycle subcommands.",examples:["plan-step-001","1"]},reorderTo:{description:"New integer order for reorder-step.",examples:[1,"2"]},scope:{description:"Short free-text scope statement describing what the Plan covers.",examples:["Release readiness audit","Search package migration"]},mode:{description:"Plan lifecycle mode.",examples:["draft","research","approved"]},step:{description:"Ordered initial step titles for create (string or array, never comma-split; stepTitle, when also set, becomes the first step). For step subcommands a single value aliases stepTitle.",examples:[["Read the code","Write the fix","Run the tests"]]},file:{description:"File link to attach while creating or materializing a Plan.",examples:["path=src/cli.ts,note=implementation surface"]},test:{description:"Test command link to attach while creating or materializing a Plan.",examples:["command=pnpm build,timeout_seconds=300"]},doc:{description:"Documentation link to attach while creating or materializing a Plan.",examples:["path=docs/SDK.md,note=public API reference"]}},ri={action:{description:"Tool action to execute."},pmExecutable:{description:"Override the pm executable used by actions that invoke or verify an external CLI process.",examples:["pm","node dist/cli.js"]},force:{description:"Allow the selected action to override its supported ownership, terminal-state, or destructive-operation guard."},limit:{description:"Maximum number of rows returned by the selected action.",examples:[10,"25"]},text:{description:"Text payload used by append, comment, note, or learning mutations."},path:{description:"Optional PM data root override for this invocation.",examples:[".agents/pm"]},scope:{description:"Scope selector for commands that operate on project or global state. Linked files, docs, and tests default to project scope when omitted.",examples:["project","global"]},detail:{description:"Detail mode for commands that support concise and deep diagnostics.",examples:["summary","deep"]},trace:{description:"When true for extension-doctor, include actionable registration traces in deep diagnostics."},reload:{description:"When true for extension action payloads, trigger cache-busted extension module reload."},watch:{description:"When true for extension-reload/extension action payloads, enable watch mode semantics."},runtimeProbe:{description:"When true for extension-manage, run a doctor-like runtime activation probe for parity fields."},fixManagedState:{description:"When true for extension-manage/extension-doctor, adopt unmanaged extensions before diagnostics/update checks."},isolated:{description:"When true for extension-doctor/package-doctor, ignore global registrations for hermetic project diagnostics."},ignoreGlobal:{description:"Alias for isolated on extension-doctor/package-doctor action payloads."},target:{description:"Positional target argument for the selected action (ID, source, package source, or extension name).",examples:["pm-a1b2",".agents/pm/extensions/sample","sample-extension"]},capability:{description:"Starter capability selected by extension-init or package-init scaffolding.",examples:["commands","hooks","search","schema"]},declarative:{description:"Generate the package composeExtension declarative blueprint starter."},output:{description:"File path for commands that write generated output, such as package/extension describe Markdown references.",examples:["docs/pm-package-reference.md"]},markdown:{description:"Render the package or extension description as Markdown instead of structured output.",examples:[!0]},github:{description:"GitHub shorthand owner/repo[/path] source for package/extension install actions.",examples:["org/repo/extensions/sample"]},ref:{description:"Git ref/branch/tag used when installing from GitHub shorthand/URL sources.",examples:["main","v1.0.0"]},cliOnly:{description:"Restrict upgrade to the pm CLI/SDK npm package."},packagesOnly:{description:"Restrict upgrade to managed installable pm packages."},repair:{description:"Force npm global reinstall semantics when upgrading the pm CLI/SDK."},tag:{description:"npm version or dist-tag used for CLI and registry package upgrades.",examples:["latest","next","2026.5.11"]},today:{description:"When true for list actions, include only items updated since local midnight today."},recent:{description:"When true for list actions, include only items updated in the last seven days."},packageName:{description:"Override the pm CLI package name for self-upgrade automation and tests.",examples:["@unbrained/pm-cli"]},json:{description:"Emit machine-readable JSON output."},quiet:{description:"Suppress stdout payload output."},noExtensions:{description:"Disable extension loading for this invocation."},noPager:{description:"Disable pager integration for help and long output."},tokenAccounting:{description:"Request a bounded transport-level receipt for output emitted by a compatible CLI or MCP host."},outputInclude:{description:"Comma-separated fields or sections retained by any built-in read action.",examples:["id,title,status","summary,counts"]},outputLimit:{description:"Universal read row ceiling, or unbounded to disable the shared ceiling.",examples:[10,"unbounded"]},outputBudget:{description:"Universal estimated-token ceiling for a read result, or unbounded to disable the shared ceiling.",examples:[600,1200,"unbounded"]},outputFormat:{description:"Universal read-result encoding selector.",examples:["toon","json"]},outputSession:{description:"Caller-carried JSON session state that enforces a token ceiling across read calls and replaces repeated item facts with resolvable context references.",examples:[{version:1,id:"orientation",token_budget:4e3,spent_tokens:0,seen_item_ids:[]}]},outputCursor:{description:"Opaque continuation cursor returned when a declared row collection is compacted by the output budget."},outputRowContract:{description:"Include the row selector and TOON row-encoding contract on a read result."},profile:{description:"Emit deterministic timing diagnostics to stderr."},timeoutMs:{description:"Tool execution timeout in milliseconds.",examples:[12e4]},id:{description:"Item identifier for read or mutation actions.",examples:["pm-a1b2"]},treeId:{description:"Commit, tree, snapshot, or immutable workspace identity judged by an assurance gate.",examples:["0123456789abcdef","release-candidate-3"]},definition:{description:"Structured measurement, assertion, or gate declaration used by assurance put."},trigger:{description:"Lifecycle trigger used to evaluate an assurance gate.",examples:["ci","pre-release"]},gate:{description:"Stable assurance gate id used to filter durable verdict history.",examples:["release-readiness"]},owner:{description:"pm item that owns preset or observation-derived assurance assertions.",examples:["pm-a1b2"]},enforcement:{description:"Explicit next assurance enforcement level.",examples:["warn","block"]},runId:{description:"Background test run identifier.",examples:["tr-kq9x3f-93acde"]},title:{description:"Item title text."},description:{description:"Item description text."},type:{description:"Item type name from the active runtime type registry.",examples:["Task","Feature"]},subcommand:{description:"Subcommand selector for schema, profile, telemetry, and graph actions."},name:{description:"Custom definition name, schema migration source name, or profile name.",examples:["Spike","review","component"]},defaultStatus:{description:"Default status hint recorded for a custom item type.",examples:["open"]},alias:{description:"Aliases for the custom item type or status (repeatable).",examples:[["spike","research"]]},role:{description:"Lifecycle roles for a custom status (schema add-status): draft, active, blocked, terminal, terminal_done, terminal_canceled, default_open, default_close, default_cancel.",examples:[["active"],["terminal","terminal_done"]]},fieldType:{description:"Value type for a custom field (schema add-field): string, number, boolean, or string_array.",examples:["string","number","string_array"]},fieldTypeScope:{description:"Optional item type restricting which records participate in schema rename-field.",examples:["Issue","Feature"]},migrationId:{description:"Optional stable idempotency override used to persist and resume a schema migration plan; omitted values are derived from the workspace and normalized request.",examples:["severity-to-impact-v2"]},commands:{description:"Commands a custom field is wired onto (schema add-field): create, update, update_many, list, search, calendar, context.",examples:[["create","update"],["create","update","list"]]},cliFlag:{description:"Override the auto-derived CLI flag for a custom field (schema add-field).",examples:["--owner"]},required:{description:"Mark a custom field as always required (schema add-field)."},requiredOnCreate:{description:"Mark a custom field as required at create time (schema add-field)."},allowUnset:{description:"Whether a custom field may be cleared via --unset (schema add-field); defaults to true."},allowDuplicate:{description:"Explicitly proceed when strict similarity governance finds likely duplicate items."},allowUnresolvedDeps:{description:"Permit unresolved local dependency targets while returning dependency_target_unresolved warning receipts. Cross-workspace references should use source_kind=external instead.",examples:[!0]},requiredTypes:{description:"Restrict a custom field's requirement to specific item types (schema add-field).",examples:[["Bug"],["Story","Spike"]]},infer:{description:"Infer custom item types from title-prefix conventions (schema add-type); previews unless apply is true."},minCount:{description:"Minimum number of items sharing a title prefix for schema add-type inference (default 10).",examples:[10,25]},preset:{description:"Governance preset for initialization flows.",examples:["minimal","default","strict"]},idPrefix:{description:"Tracker item identifier prefix used by initialization; overrides the positional compatibility prefix.",examples:["pm","work"]},workspace:{description:"Workspace directory where initialization resolves or creates the tracker.",examples:[".","packages/app"]},typePreset:{description:"Domain item-type preset registered during initialization.",examples:["agile","ops","research"]},defaults:{description:"Use non-interactive setup defaults during initialization."},verbose:{description:"Include the full resolved settings tree in init output."},agentGuidance:{description:"Control AGENTS.md/CLAUDE.md guidance behavior during init: ask, add, skip, or status.",examples:["ask","add","skip","status"]},withPackages:{description:"Install all bundled first-party pm packages during initialization."},mergeFence:{description:"Install the repository merge-driver fence for a fresh Git-backed tracker; set false to opt out."},createMode:{description:"Create required-option policy mode.",examples:["strict","progressive"]},schedulePreset:{description:"Schedule-centric create preset for Reminder, Meeting, and Event types.",examples:["lightweight"]},status:{description:"Item status value. Statuses are project-configurable via .agents/pm/settings.json (schema block); the built-in defaults are draft, open, in_progress, blocked, closed, canceled. Custom statuses defined for the project are accepted \u2014 discover the active set with the pm_contracts tool (workspace.statuses) or `pm contracts`. Unknown statuses are rejected at runtime with a did-you-mean hint rather than blocked by a fixed schema enum.",examples:["open","in_progress"]},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for duplicate discovery.",examples:["2026-01-01T00:00:00.000Z"]},threshold:{description:"Minimum duplicate similarity score from zero through one.",examples:[.85]},priority:{description:"Priority value in range 0..4.",examples:[0,1,"2"]},order:{description:"Planning order/rank value for create/update, or sort direction (asc|desc) for list-family sorting.",examples:[0,1,"2","asc","desc"]},sort:{description:"List-family sort field selector.",examples:["priority","deadline","updated_at","created_at","title","parent"]},tags:{description:"Comma-delimited tag list.",examples:["pm-cli,agent-ux"]},addTags:{description:"Tags to add to the existing list without replacing it. Each entry may be CSV or a JSON array.",examples:[["agent-ux"],["fix","security"]]},addAc:{description:"Acceptance criteria appended individually without replacing the existing list (one criterion per entry).",examples:[["error path covered by a regression test"]]},removeAc:{description:"Acceptance criteria removed individually by exact text match; the mutation fails atomically if any selector is unmatched (one criterion per entry).",examples:[["superseded manual QA step"]]},removeTags:{description:"Tags to remove from the existing list. Each entry may be CSV or a JSON array.",examples:[["stale"],["legacy","wontfix"]]},deadline:{description:"ISO/date timestamp or relative offset (+6h/+1d/+2w/+6m).",examples:["2026-04-01T00:00:00.000Z","+1d"]},reminder:{description:"Repeatable reminder seed entries at=<iso|relative>,text=<text>.",examples:[["at=+2d,text=Review PR"]]},event:{description:"Repeatable event seed entries start=<iso|relative> with end=<iso|relative> or duration=<relative|30min|PT30M>. Bare `m` remains months for backward compatibility.",examples:[["start=2026-07-01T10:00:00Z,duration=2h,title=planning"],["start=2026-07-01T10:00:00Z,duration=30min,title=standup"],["start=2026-07-01T10:00:00Z,duration=PT30M,title=window"]]},historyEvent:{description:"Unknown-author history target in <item-id>:<one-based-line> form.",examples:[["pm-example:4","pm-example:5"]]},planFingerprint:{description:"Exact SHA-256 returned by a history-author-acknowledge dry-run preview; apply refuses stale or changed source coordinates.",examples:["0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"]},estimate:{description:"Estimated effort in minutes.",examples:[60,"120"]},acceptanceCriteria:{description:"Complete acceptance-criteria text supplied while creating or replacing an item field."},author:{description:"Intentional mutation-author override. Agent harness identity is automatic when omitted."},attributedAuthor:{description:"Principal attributed to the immutable unknown-author history events after review.",examples:["reviewed-principal"]},message:{description:"History message for mutation audit trail."},ifAbsent:{description:"For annotations, append only when no existing entry has the same resolved author and exact stored text; retries return changed false without a history event."},assignee:{description:"Assignee identity."},assigneeFilter:{description:"Assignee presence selector for list, calendar, and context filters.",examples:["assigned","unassigned"]},parent:{description:"Parent item ID filter for hierarchical list queries.",examples:["pm-epic01"]},blockedLimit:{description:"Cap blocked rows returned by the next action (defaults to the ready --limit).",examples:["3"]},readyOnly:{description:"When true, the next action omits the blocked companion list."},unset:{description:"Repeatable list of item-metadata fields to clear explicitly during create/update mutations.",examples:[["deadline","assignee"],["close-reason"]]},clearDeps:{description:"When true, clear linked dependencies."},replaceDeps:{description:"When true for update, atomically replace dependencies with the supplied --dep values."},replaceTests:{description:"When true for update, atomically replace linked tests with the supplied --test values."},replaceFiles:{description:"When true for update, atomically replace linked files with the supplied --file values."},replaceDocs:{description:"When true for update, atomically replace linked docs with the supplied --doc values."},lookupPath:{description:"One or more source paths whose referencing pm items should be returned by files lookup.",examples:[["src/sdk/files.ts"],["README.md","docs/SDK.md"]]},explain:{description:"Include ranked linked-file, rationale, and governing-decision evidence for a files lookup."},lines:{description:"Inclusive start:end source-line range for Git contribution attribution; requires one lookup path.",examples:["10:24"]},decisionDepth:{description:"Maximum typed relationship depth searched for a governing Decision during files lookup.",examples:[8]},clearComments:{description:"When true, clear item comments."},clearNotes:{description:"When true, clear item notes."},clearLearnings:{description:"When true, clear item learnings."},clearFiles:{description:"When true, clear linked files."},clearTests:{description:"When true, clear linked tests."},clearDocs:{description:"When true, clear linked docs."},clearReminders:{description:"When true, clear reminders."},clearEvents:{description:"When true, clear events."},clearTypeOptions:{description:"When true, clear type option metadata."},clearCriteria:{description:"When true for config set criteria-list keys (definition-of-done, metadata-required-fields, lifecycle pattern lists), clear the criteria list."},mode:{description:"Mode selector for search and reindex (keyword|semantic|hybrid).",examples:["keyword","hybrid"]},semanticWeight:{description:"Per-query hybrid semantic weight override in [0,1] for search action; invalid values fall back to settings.",examples:[.2,"0.7"]},op:{description:"History operation filter for activity output.",examples:["create","update","close","update_ownership_bypass"]},fullPeriod:{description:"For day/week/month calendar views, include the full anchored period instead of clipping the start to now."},progress:{description:"Emit progress diagnostics to stderr for long-running operations."},background:{description:"Run linked tests in managed background mode."},addJson:{description:"JSON input: one structured context event for notes, or repeatable linked-test entries for test.",examples:[['{"command":"node scripts/run-tests.mjs test -- tests/unit/output.spec.ts","timeout_seconds":240}']]},eventType:{description:"For notes action, return structured context events whose top-level type matches this value."},includeMeta:{description:"Include structured-event counts for notes reads; filtered reads also include total, returned, limit, and has-more metadata."},allActionable:{description:"For history-author-acknowledge, select every currently actionable undispositioned event."},match:{description:"Run only linked tests whose command or path contains this case-insensitive substring.",examples:["output.spec.ts","coverage"]},onlyIndex:{description:"Run only the 1-based linked-test index from pm test <id> --list order.",examples:[1,"2"]},removeIndex:{description:"Remove linked tests by their 1-based positions from pm test <id> --list order; repeatable and lossless for commands containing commas or equals signs.",examples:[[1],["2","4"]]},onlyLast:{description:"Run only the most recently added linked-test entry."},envSet:{description:"Repeatable runtime environment KEY=VALUE overrides for linked-test execution.",examples:[["PORT=0","PLAYWRIGHT_HTML_OPEN=never"]]},envClear:{description:"Repeatable runtime environment variable names to clear before linked-test execution.",examples:[["PLAYWRIGHT_BASE_URL"]]},sharedHostSafe:{description:"Apply additive shared-host-safe runtime defaults during linked-test execution."},pmContext:{description:"PM linked-test context mode (schema keeps isolated tracker data; tracker seeds source tracker data; auto uses tracker for PM tracker-read linked commands).",examples:["schema","tracker","auto"]},overrideLinkedPmContext:{description:"Force run-level --pm-context to override per-linked-test pm_context_mode metadata for all linked-test entries."},workspaceContext:{description:"Source-workspace mode: source preserves read-only source context, isolated omits it for self-sandboxing commands, and snapshot runs from a temporary workspace paired with the selected tracker sandbox.",examples:["source","isolated","snapshot"]},overrideLinkedWorkspaceContext:{description:"Force run-level --workspace-context over per-linked-test workspace_context_mode metadata."},allowUntrustedLinkedTests:{description:"Explicitly execute commands not yet trusted by this clone when testing.allow_untrusted_linked_tests is also enabled."},acknowledgeLinkedTests:{description:"Record clone-local trust for the item's current linked commands without executing them."},failOnContextMismatch:{description:"Fail linked PM command runs when source and sandbox tracker item counts differ."},failOnSkipped:{description:"Treat skipped linked tests as dependency-failed policy violations."},failOnEmptyTestRun:{description:"Treat successful linked-test commands that report zero executed tests as failures."},requireAssertionsForPm:{description:"Require assertion metadata for linked PM command test entries during run execution."},checkContext:{description:"Run linked PM command context preflight diagnostics before command execution."},autoPmContext:{description:"Auto-remediate PM tracker-read linked commands by routing those entries through tracker context regardless of linked-test pm_context_mode overrides."},measure:{description:"Repeatable numeric run evidence in name=value[,unit=...][,threshold=...] form.",examples:[["coverage=100,unit=percent,threshold=100"]]},metricBelow:{description:"Return recorded evidence below a name=value threshold.",examples:["coverage=100"]},metricDiff:{description:"Compare the latest and previous values for one metric.",examples:["coverage"]},dryRun:{description:"Preview command effects without mutating storage artifacts."},normalizeProvenance:{description:"For history-repair: remove invalid legacy provenance observations and emit only aggregate privacy-safe repair evidence."},all:{description:"For history-repair action: scan every stream for drift and repair each drifted stream in one audited pass (mutually exclusive with id)."},clear:{description:"For focus action: clear the session focused item instead of setting it (mutually exclusive with id)."},gcScope:{description:"Repeatable gc scope selector values (index, embeddings, runtime, locks, checkpoints, transactions).",examples:[["index","embeddings"],["runtime"],["locks"],["checkpoints"]]},storage:{description:"For stats action: include aggregate history-stream storage metrics (total streams/lines/bytes, largest + deepest streams, oldest/newest entries) for compaction and storage planning."},fieldUtilization:{description:"For stats action: include a field_utilization block reporting present/total/percent for content fields (notes, learnings, files, docs, tests, comments, deps, body, linked_command) across all items so under-documented dimensions are visible at a glance."},measurements:{description:"For stats action: include the audited append-only improvement ledger and baseline-to-latest trends."},metric:{description:"Exact improvement metric name used to filter ledger reads.",examples:["quality.coverage.lines"]},measurementLimit:{description:"Maximum newest improvement observations returned by stats.",examples:[50]},observe:{description:"Repeatable audited observation in name=value[,unit=...][,threshold=...] form.",examples:[["quality.coverage.lines=100,unit=percent,threshold=100"]]},improvementDirection:{description:"Improvement direction for newly recorded observations.",examples:["higher","lower","target"]},measurementSource:{description:"Producing gate or instrument for a new observation.",examples:["pnpm coverage"]},measurementItem:{description:"Tracked item that owns an improvement observation.",examples:["pm-123abc"]},measurementRevision:{description:"Explicit source revision for a new observation.",examples:["0123456789abcdef"]},provenanceCoverage:{description:"For stats action: compare configured provenance descriptors with bounded immutable-history observations."},fleetAttribution:{description:"For stats action: derive observational throughput, rework, and defect-escape rates by harness, model, and author source."},eventLimit:{description:"Maximum immutable history events consumed by an analytics projection.",examples:[1e4]},minimumSample:{description:"Minimum denominator before analytics rates are reported.",examples:[5]},offset:{description:"Number of matching rows to skip before limit is applied.",examples:[0,50,"100"]},provenance:{description:"Return patch-free immutable author, harness, instance, and extensible provenance rows."},provenanceSummary:{description:"Include bounded observed, unavailable, legacy-missing, and unresolved-author counts."},agentInstance:{description:"Privacy-safe agent invocation fingerprint filter, supplied once or as a list.",examples:["a1b2c3d4",["a1b2c3d4","e5f6g7h8"]]},provenanceFilter:{description:"Exact extensible provenance predicate in dimension=value form, supplied once or as a list.",examples:["model=gpt-5.6-sol",["effort=xhigh","role=reviewer"]]},before:{description:"For history-compact, compact entries strictly before this boundary (version number or ISO timestamp). Single-id mode only.",examples:["5","2026-06-01T00:00:00.000Z"]},at:{description:"Read-only historical projection boundary as an item version or ISO timestamp.",examples:["3","2026-07-01T12:00:00.000Z"]},allOver:{description:"For history-compact bulk mode, compact every stream with more than N entries. When history.compact_policy is enabled and this is omitted, the policy's max_entries is used.",examples:[200,"500"]},minEntries:{description:"For history-compact bulk mode, skip streams with at most N entries as already-compact (default 3).",examples:[3,"10"]},closed:{description:"For history-compact bulk mode, compact only closed (terminal) items' history streams."},allStreams:{description:"For history-compact bulk mode, compact every history stream regardless of lifecycle state."},literal:{description:"Repeatable literal matcher used by history-redact to scrub exact string values.",examples:["[redacted_path_prefix]/private/path"]},regex:{description:"Repeatable regex matcher used by history-redact. Accepts either /pattern/flags or a raw pattern (global mode is auto-enabled).",examples:["/192\\\\.168\\\\.[0-9.]+/g","token=[A-Za-z0-9_-]+"]},replacement:{description:'Replacement text used by history-redact (defaults to "[redacted]").',examples:["[scrubbed_path]"]},validateClose:{description:'Close-time metadata validation mode ("off", "warn", or "strict").',examples:["off","warn","strict"]},checkMetadata:{description:"Run metadata completeness checks."},metadataProfile:{description:"Select metadata validation profile for --check-metadata.",examples:["core","strict","custom"]},checkResolution:{description:"Run closed-item resolution metadata checks."},checkLifecycle:{description:"Run active-item lifecycle governance drift checks."},checkStaleBlockers:{description:"Include stale blocker-pattern diagnostics in lifecycle checks."},dependencyCycleSeverity:{description:"Set dependency-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},parentCycleSeverity:{description:"Set parent-cycle warning policy for lifecycle checks.",examples:["off","warn","error"]},checkFiles:{description:"Run linked-file and orphaned-file checks."},checkStorageIntegrity:{description:"Run deep item, history, index, and vector storage integrity checks."},strictDirectories:{description:"Treat optional item-type directories as required health failures."},requireMergeDrivers:{description:"Treat never-installed clone-local semantic merge drivers as required health failures."},checkOnly:{description:"For health action, run read-only diagnostics without refreshing vectors."},checkTelemetry:{description:"For health action, probe telemetry endpoint health and include network diagnostics."},noRefresh:{description:"For health action, skip vector refresh while still running checks."},refreshVectors:{description:"For health action, explicitly refresh stale vectors."},verboseStaleItems:{description:"For health action, include full stale-item arrays in vectorization details."},verboseAuthorEvents:{description:"For health action, include every actionable unknown-author event coordinate."},skipVectors:{description:"For health action, skip vectorization checks for a faster diagnostic run."},skipIntegrity:{description:"For health action, skip item/history file integrity checks for a faster diagnostic run."},skipDrift:{description:"For health action, skip history drift hash checks for a faster diagnostic run."},scanMode:{description:"Select file candidate scan mode for --check-files.",examples:["default","tracked-all","tracked-all-strict"]},includePmInternals:{description:"Include PM storage internals in tracked-all candidate scans."},verboseFileLists:{description:"For validate action, include full file-path lists for --check-files details."},verboseDiagnostics:{description:"For validate action, include full diagnostic ID lists instead of compact summaries."},strictExit:{description:"Return non-zero exit when health/validate/extension-doctor warnings are present."},failOnWarn:{description:"Alias for strictExit in health/validate/extension-doctor action payloads."},fixHints:{description:"For validate action, add a machine-executable fix_hints[] of pm commands to each failing check's details."},autoFix:{description:"For validate action, apply the safe, deterministic subset of fix-hint remediations (field backfills) automatically; combine with dryRun to preview and fixScope to grant gated scopes."},fixScope:{description:"For validate action, grant --auto-fix scopes (metadata, resolution, estimates, lifecycle). Defaults to the safe scopes metadata and resolution; estimates (per-type default estimated_minutes backfill) and lifecycle must be named explicitly.",examples:[["estimates"],["lifecycle"],["metadata","resolution"]]},pruneMissing:{description:"For validate action, remove stale linked-file/doc LINKS whose paths classified as deleted (link removal only \u2014 never touches real files); honors dryRun."},checkHistoryDrift:{description:"Run item/history hash drift checks."},checkCommandReferences:{description:"Run linked-command PM-ID reference checks."},edit:{description:"For comments, notes, and learnings actions, replace the annotation at this 1-based index with supplied replacement text."},delete:{description:"For comments, notes, and learnings actions, delete the annotation at this 1-based index."},stdin:{description:"For comments, notes, and learnings actions, read annotation text from piped stdin (supports multiline markdown)."},file:{description:"CLI-only path to an input file for commands that read payload text; tool actions exclude host file access.",examples:["notes/comment.md"]},preserveSourceIds:{description:"Preserve explicit source IDs during Beads imports instead of normalizing to tracker prefix.",examples:[!0]},appendStable:{description:"When true for files action, preserve existing linked-file order and append new links without full-array resorting."},discover:{description:"When true for files action, use `pm files discover <id>` to scan item text for referenced file paths."},apply:{description:"Persist changes instead of returning a dry-run preview: for files discovery, add the missing discovered file links; for schema add-type --infer, register the inferred custom item types."},discoveryNote:{description:"Note attached to file links added by files discovery.",examples:["discovered from item text"]},addNote:{description:"Note attached to every link added by add/addGlob in this call (per-entry embedded note= wins; requires add or addGlob). Maps to the CLI --note flag on pm files/pm docs.",examples:["command wiring"]},list:{description:"When true, list command-specific entries without mutating state (for example linked paths for files/docs or topics for guide).",examples:[!0]},stream:{description:"Stream selector: test-runs logs accepts stdout|stderr|both; activity accepts boolean/rows|ndjson|jsonl for line-delimited output.",examples:["stderr","stdout","both","rows","ndjson","jsonl",!0]},tail:{description:"Number of lines to tail for background run logs.",examples:[100]},query:{description:"Search query text for search action."},for:{description:"Named context intent projection declared for the selected read action.",examples:["orient","inspect","triage","execute","discover"]},keywords:{description:"Alias for query in search action payloads."},includeLinked:{description:"Include readable linked docs/files/tests content in keyword and hybrid lexical scoring."},titleExact:{description:"For search action, require exact normalized title match for the full query string."},phraseExact:{description:"For search action, require exact normalized query phrase match in item text fields."},highlight:{description:"For search action, emit per-field matched-text snippets (wrapped in \xAB\u2026\xBB) on each hit. Off by default."},includeBody:{description:"When true for list-family actions, include item body text in projected rows."},noTruncate:{description:"When true for list-family actions, return every matched row, overriding any limit (surfaces total when rows were dropped)."},strictRead:{description:"When true for list-family actions, fail if any source item or item directory cannot be read."},compact:{description:"Render compact projection output for search and list-family actions."},raw:{description:"For activity, restore the compact per-event stream instead of the default item digest."},brief:{description:"Emit compact low-token output for commands that support terse projections or health details.",examples:[!0]},full:{description:"Enable command-specific full/detail output mode when supported, such as deep item reads for get or full payload mode for search/history."},includeEmpty:{description:"For stats, restore zero-count registered type and lifecycle-status buckets."},fields:{description:"Comma-separated projection fields for get, search, list-family, or context outputs. Valid field names are command-specific (e.g. score/matched_fields apply to search; context projects focus-row fields such as priority/deadline/completion_pct).",examples:["id,title,status,parent,type","id,title,score,matched_fields","id,title,priority,deadline"]},groupBy:{description:"Comma-separated aggregate grouping fields (supported: parent,type,priority,status,assignee,tags,sprint,release).",examples:["parent,type","type,status","priority,assignee","tags","sprint,release"]},count:{description:"Enable grouped count output for aggregate action."},completion:{description:"For aggregate action, add open/in_progress/closed/other counts and completion_pct per group."},sum:{description:"Numeric field to sum per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},avg:{description:"Numeric field to average per aggregate group (count and null_count are still returned).",examples:["estimated_minutes","priority"]},tree:{description:"When true for list/get actions, render recursive parent/child tree ordering."},treeDepth:{description:"Maximum recursion depth for tree output (0 keeps root rows only).",examples:[0,1,"2"]},includeUnparented:{description:"Include unparented rows when aggregate grouping includes parent."},maxDepth:{description:"Maximum dependency traversal depth for deps action (0 keeps only the root node).",examples:[0,1,"2"]},nodeLimit:{description:"Maximum related nodes returned by deps --format context.",examples:[10,"20"]},edgeLimit:{description:"Maximum related edges returned by deps --format context.",examples:[20,"40"]},tokenBudget:{description:"Maximum estimated output tokens for the command output.",examples:[600,"1200"]},cursor:{description:"Opaque continuation cursor returned by deps --format context."},direction:{description:'Graph-context traversal direction for deps action ("outgoing", "incoming", or "both").',examples:["both","incoming"]},kind:{description:"Registered relationship kinds narrowing deps --format context traversal (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},after:{description:"Continuation cursor resuming a bounded listing or traversal after this previously returned id.",examples:["pm-x1y2"]},maxPaths:{description:"Maximum enumerated paths for graph paths queries.",examples:[5,"10"]},sample:{description:"Maximum evidence sample entries per graph audit finding.",examples:[10,"25"]},exemptIsolate:{description:"Item ids the graph audit treats as explicitly valid isolates (string, comma-separated, or array).",examples:["pm-x1y2",["pm-x1y2","pm-a3b4"]]},exemptIsolateType:{description:"Item types whose active isolates the graph audit treats as policy-valid (string, comma-separated, or array).",examples:["Reminder",["Reminder","Event"]]},saveBaseline:{description:"When true, persist the graph audit census as the change-since-baseline comparison point (audit only)."},rebuild:{description:"When true, rebuild and warm the durable graph index (graph index only)."},collapse:{description:'Dependency tree collapse mode for deps action ("none" or "repeated").',examples:["none","repeated"]},summary:{description:"When true, return the command's compact summary projection (deps counts, health rollup, or contracts command intents)."},shell:{description:"Shell target for completion generation.",examples:["bash"]},eagerTags:{description:"When true for completion, eagerly embed current tracker tags into generated scripts (legacy mode)."},contractAction:{description:"Filter contracts schema to one tool action.",examples:["create","update"]},command:{description:"Scope contracts output to one CLI command name; action/schema surfaces narrow by default.",examples:["create","search","list"]},schemaOnly:{description:"When true, contracts action returns schema-focused payloads (mutually exclusive with flagsOnly/availabilityOnly)."},flagsOnly:{description:"When true, contracts action returns only command flag surface payloads (mutually exclusive projection mode)."},availabilityOnly:{description:"When true, contracts action returns only action availability payloads (mutually exclusive projection mode)."},runtimeOnly:{description:"When true, contracts action only includes actions invocable in the current runtime."},activeOnly:{description:"Alias for runtimeOnly in contracts action payloads."},depth:{description:"Context depth level controlling how many sections are included (brief=focus+agenda, standard=+hierarchy/activity/progress/workload, deep=all sections, full=every section with no per-section row cap).",examples:["brief","standard","deep","full"]},section:{description:"Repeatable section selector for context; overrides --depth when provided.",examples:[["hierarchy","activity"],["blockers","files","staleness"]]},activityLimit:{description:"Maximum number of recent activity entries to include in context output.",examples:[5,10,"20"]},staleThreshold:{description:"Staleness cutoff in days for context staleness section (e.g. 7 or 7d).",examples:["7","14d","30"]}},Pv={assurance:{subcommand:{description:"Assurance operation: list, show, put, remove, run, verdicts, presets, apply, derive, promote, or risk.",examples:["list","run","derive","promote","risk"]},kind:{description:"Assurance declaration kind for registry operations: measurement, assertion, or gate.",examples:["measurement","assertion","gate"]},id:{description:"Stable assurance declaration id or gate id, depending on subcommand.",examples:["active-issues","release-readiness"]},limit:{description:"Maximum number of newest assurance verdicts returned.",examples:[10,25]},preset:{description:"Built-in assurance project shape to preview or apply.",examples:["software-delivery","agent-evaluation"]}},update:{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},"update-many":{acceptanceCriteria:{description:"Complete acceptance-criteria replacement text. Use removeAc plus addAc together for an atomic one-entry repair that preserves unrelated criteria."}},stats:{since:{description:"Inclusive ISO 8601 timestamp or negative duration lower bound for provenance and fleet analytics.",examples:["2026-08-01T00:00:00.000Z","-30d"]}},events:{since:{description:"Durable event cursor returned as next_cursor, or an inclusive event timestamp.",examples:["eyJmaW5nZXJwcmludCI6Ii4uLiJ9","2026-08-01T00:00:00.000Z"]},type:{description:"Mutation event type filter, supplied once or as a list.",examples:["create",["create","update"]]},author:{description:"Mutation author filter, supplied once or as a list.",examples:["agent-a",["agent-a","agent-b"]]},item:{description:"Tracked item id filter, supplied once or as a list.",examples:["pm-a1b2",["pm-a1b2","pm-c3d4"]]},limit:{description:"Maximum mutation events returned, from 0 through 1000.",examples:[0,100]},cursorMode:{description:"Cursor framing: batch returns one terminal next_cursor (default); row also adds a cursor to every event.",examples:["batch","row"]}},remind:{at:{description:"Reminder time as an ISO 8601 timestamp or supported relative expression.",examples:["2026-08-02T09:00:00+02:00","tomorrow 09:00"]}},deps:{tokenBudget:{description:"Maximum estimated output tokens for deps --format context.",examples:[600,"1200"]}},comments:{full:{description:"Return the complete post-mutation comment history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a comment only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},notes:{full:{description:"Return the complete post-mutation note history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a note only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."},since:{description:"Inclusive ISO 8601 creation timestamp lower bound for structured note event filtering.",examples:["2026-01-01T00:00:00.000Z"]}},learnings:{full:{description:"Return the complete post-mutation learning history instead of the bounded mutation receipt projection."},ifAbsent:{description:"Append a learning only when the resolved author and exact stored text are absent; a duplicate retry returns changed false without writing history."}},next:{tag:{description:"Only recommend items carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the recommendation context.",examples:[600,"1200"]}},claim:{tag:{description:"When claiming the next item, only consider work carrying this exact tag.",examples:["sdk","release"]},tokenBudget:{description:"Maximum estimated output tokens for the next-item context returned with the claim.",examples:[600,"1200"]}},close:{text:{description:"Backward-compatible alias for the item close reason when reason is not provided."}},"close-task":{text:{description:"Close reason used before releasing the item's active assignment."}},schema:{name:{description:"Custom item type name (add-type/remove-type/show), custom status id (show-status/add-status/remove-status), or custom field key (add-field/remove-field/show-field). Required for those subcommands.",examples:["Spike","review","component"]}},profile:{name:{description:"Profile name for show/apply/lint. Built-in profiles are agile, ops, and research; an active extension can contribute additional archetype names that resolve here too.",examples:["agile","ops","research"]}},graph:{subcommand:{description:"Graph query selector: ancestors|descendants|predecessors|successors|paths|impact|analyze|audit|communities|redundancy|dominators|slack|centrality|articulation|plan|index. Traversals, paths, impact, and dominators require id; paths also requires target; slack reports critical-path float, centrality ranks betweenness/closeness/degree, articulation reports cut points and bridges; plan derives dry-run remediation proposals from the governance audit; index reports, rebuilds, or clears the durable cross-process graph index.",examples:["successors","audit"]},clear:{description:"When true, delete the durable graph index (graph index only)."},id:{description:"Root item id for traversal, paths, impact, and dominators graph queries.",examples:["pm-x1y2"]},target:{description:"Target item id for graph paths queries.",examples:["pm-a3b4"]},direction:{description:'Edge orientation for graph paths/impact/dominators queries ("outgoing", "incoming", or "both"; default "both").',examples:["incoming"]},kind:{description:"Registered relationship kinds narrowing the graph query (string, comma-separated, or array).",examples:["blocked_by",["parent","related"]]},maxDepth:{description:"Maximum graph traversal depth (non-negative integer).",examples:[2,"4"]},after:{description:"Resume a hierarchy/ordering graph traversal after this previously returned node id.",examples:["pm-x1y2"]},limit:{description:"Maximum returned rows per bounded graph collection (traversal ids, impact rows, analyze/communities samples, redundancy rows, dominator bottlenecks).",examples:[10,"25"]},summary:{description:"When true, return counts-first graph envelopes without row collections."}}};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b81a68c1-565d-56f6-a0eb-35d2c737bdb7")}catch{}})();var hz=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],bz=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],Uv=new Set(["action","cwd","options",...Object.keys(ni).filter(e=>e!=="severity")]);function wz(e){let t=e.trim().toLowerCase(),n="";for(let r=0;r<t.length;r+=1){let o=t[r];if(o!=="-"&&o!=="_"){n+=o;continue}let i=r+1;for(;t[i]==="-"||t[i]==="_";)i+=1;let s=t[i];if(s!==void 0&&(s>="a"&&s<="z"||s>="0"&&s<="9")){n+=s.toUpperCase(),r=i;continue}n+=t.slice(r,i),r=i-1}return Uv.has(n)?{field:e,property:n,owner:"mcp_tool_input",nested_path:`options.${n}`}:void 0}var Ez={create:["fullChangedFields","idOnly"],copy:["fullChangedFields","idOnly"],update:["fullChangedFields","idOnly"],"item-reopen":["fullChangedFields","idOnly"],close:["fullChangedFields","idOnly"],restore:["fullChangedFields","idOnly"],append:["fullChangedFields"],"update-many":["fullChangedFields"],"close-many":["fullChangedFields"],assurance:["fullChangedFields","idOnly"]},zv=["createMode","status","deadline","estimate","acceptanceCriteria","definitionOfReady","order","rank","goal","objective","value","impact","outcome","whyNow","assignee","reviewer","risk","confidence","sprint","release","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact","comment","note","learning","reminder","event","typeOption"],eY=Object.freeze({"close-many":["list","expected_result","expected","actual_result","actual","validate_close","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],"update-many":["list","update","dry_run","checkpoint","no_checkpoint","filterAssignee_filter"],...Object.fromEntries(Je.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Le(e){return zn(e)}var vz=Le([...yf.map(e=>e.param),...Ma.map(e=>e.param),"assignee","closeReason","completedAt"]),qv=Le([...hf.map(e=>e.param),...Ma.map(e=>e.param),"force"]),Tz=Le([...wf.map(e=>e.param),...qv.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),kz=Le([...Ef.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),Lv=Le([...Tf.map(e=>e.param),"past","section"]),Az=Le([...vf.map(e=>e.param),"stream"]),Uf=Le([...mf.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),Fr=Uf.filter(e=>e!=="all"&&e!=="status"),Sz=Uf.filter(e=>e!=="status"),on=[[{property:"today",schema:{const:!0}},{property:"recent",schema:{const:!0}}],[{property:"today",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}],[{property:"recent",schema:{const:!0}},{property:"updatedAfter",schema:{type:"string",pattern:"\\S"}}]],xz=[[{property:"summary",schema:{const:!0}},{property:"schemaOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"summary",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"flagsOnly",schema:{const:!0}}],[{property:"schemaOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}],[{property:"flagsOnly",schema:{const:!0}},{property:"availabilityOnly",schema:{const:!0}}]],Cz=Le([..._f.map(e=>e.param),"count","completion","includeUnparented"]),Oz=Le(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...gf.map(e=>e.param)]),Mv=Le(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),Ae=["author","message","force"],Vv=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],oi=["author","assignee","message","force"],Iz=["target","scope","capability","declarative","github","ref","init","install","uninstall","explore","manage","describe","markdown","output","reload","doctor","catalog","list","adopt","adoptAll","activate","deactivate","runtimeProbe","fixManagedState","isolated","ignoreGlobal","detail","trace","watch","strictExit","failOnWarn"];function Fv(e){return{[`${e}-init`]:{required:["target"],optional:["scope","capability",...e==="package"?["declarative"]:[]]},[`${e}-install`]:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},[`${e}-uninstall`]:{required:["target"],optional:["scope"]},[`${e}-explore`]:{optional:["scope"]},[`${e}-manage`]:{optional:["scope","runtimeProbe","fixManagedState"]},[`${e}-describe`]:{optional:["target","scope","markdown","output"]},[`${e}-reload`]:{optional:["scope","watch"]},[`${e}-doctor`]:{optional:["scope","detail","trace","fixManagedState","isolated","ignoreGlobal","strictExit","failOnWarn"]},[`${e}-catalog`]:{optional:["scope","fields"]},[`${e}-adopt`]:{required:["target"],optional:["scope","github","ref"]},[`${e}-adopt-all`]:{optional:["scope"]},[`${e}-activate`]:{required:["target"],optional:["scope"]},[`${e}-deactivate`]:{required:["target"],optional:["scope"]},[e]:{optional:Iz}}}var $v={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},jv={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Ha={init:{optional:["prefix","idPrefix","workspace","preset","typePreset","defaults","author","agentGuidance","withPackages","mergeFence","force","verbose"]},config:{required:["scope","configAction"],optional:["key","value","criterion","clearCriteria","format","policy"]},...Fv("extension"),...Fv("package"),"package-upgrade":jv,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:jv,create:{required:["title","description","type","status","priority","message"],optional:vz},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Uf,mutuallyExclusiveWhen:on},"list-all":{optional:Sz,mutuallyExclusiveWhen:on},"list-draft":{optional:Fr,mutuallyExclusiveWhen:on},"list-open":{optional:Fr,mutuallyExclusiveWhen:on},"list-in-progress":{optional:Fr,mutuallyExclusiveWhen:on},"list-blocked":{optional:Fr,mutuallyExclusiveWhen:on},"list-closed":{optional:Fr,mutuallyExclusiveWhen:on},"list-canceled":{optional:Fr,mutuallyExclusiveWhen:on},aggregate:{optional:Cz},guide:{optional:["list","format","depth"]},context:{optional:Lv},ctx:{optional:Lv},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:Oz,anyOfRequired:[["query"],["keywords"]]},eval:{optional:["mode","k","failUnder","queries","format"]},events:{optional:["since","type","author","item","limit","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","cursorMode"]},merge:{required:["subcommand"],optional:["dryRun","author","message","force","includeReconciled","artifact","basePath","oursPath","theirsPath","output","outputPath","itemPath","prefer"]},workspace:{required:["subcommand"],optional:["snapshotAction","name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"],conditionalRequired:[{property:"subcommand",value:"snapshot",required:["snapshotAction"]}]},meet:$v,event:$v,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...Mv,"for"]},reindex:{optional:["mode","progress"]},history:{required:["id"],optional:["limit","compact","full","provenance","provenanceSummary","harness","agentInstance","provenanceFilter","diff","verify","field","strictExit","failOnWarn","format"]},"history-redact":{required:["id"],optional:["literal","regex","replacement","dryRun",...Ae],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...Ae],oneOfRequired:[["id"],["all"]]},"history-author-acknowledge":{optional:["historyEvent","allActionable","dryRun","planFingerprint","limit","attributedAuthor","reviewer","reason"],oneOfRequired:[["historyEvent"],["allActionable"]]},"history-compact":{optional:["id","before","ids","allOver","closed","allStreams","minEntries","dryRun",...Ae]},schema:{required:["subcommand"],optional:["name","description","defaultStatus","folder","alias","role","order","fieldType","commands","cliFlag","required","requiredOnCreate","allowUnset","requiredTypes","typePreset","infer","minCount","apply","to","migrationId","fieldTypeScope","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"show-status",required:["name"]},{property:"subcommand",value:"add-type",required:["name"]},{property:"subcommand",value:"remove-type",required:["name"]},{property:"subcommand",value:"add-status",required:["name"]},{property:"subcommand",value:"remove-status",required:["name"]},{property:"subcommand",value:"add-field",required:["name"]},{property:"subcommand",value:"remove-field",required:["name"]},{property:"subcommand",value:"show-field",required:["name"]},{property:"subcommand",value:"rename-type",required:["name","to"]},{property:"subcommand",value:"rename-field",required:["name","to"]},{property:"subcommand",value:"remap-status",required:["name","to"]},{property:"subcommand",value:"apply-preset",required:["typePreset"]}]},profile:{required:["subcommand"],optional:["name","dryRun","author","force"],conditionalRequired:[{property:"subcommand",value:"show",required:["name"]},{property:"subcommand",value:"apply",required:["name"]},{property:"subcommand",value:"lint",required:["name"]}]},plan:{required:["subcommand"],optional:["id","stepRef","reorderTo","title","description","template","scope","parent","related","blocks","blockedBy","harness","mode","resumeContext","tags","priority",...zv,"body","claim","fromSearch","stepTitle","step","stepBody","stepOwner","stepStatus","stepEvidence","stepBlockedReason","stepReplacement","dependsOn","link","linkKind","linkNote","promoteToItemDep","allowMultipleActive","file","test","doc","decisionText","decision","decisionRationale","decisionEvidence","discoveryText","discovery","validationText","validation","validationCommand","validationExpected","depth","fields","steps","materializeType","materializeParent","materializeTags","field",...Ae]},activity:{optional:Az},restore:{required:["id","target"],optional:Ae},update:{required:["id"],optional:qv,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:Tz,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...Vv,...Ae]},"close-many":{optional:kz},delete:{required:["id"],optional:["dryRun",...Ae]},append:{required:["id","body"],optional:Ae},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...Ae],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...Ae],mutuallyExclusive:[["addJson","add"],["addJson","stdin"],["addJson","file"],["addJson","edit"],["addJson","delete"],["edit","ifAbsent"],["delete","ifAbsent"]]},learnings:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...Ae],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},files:{required:[],optional:["id","add","addGlob","remove","migrate","list","addNote","discover","apply","discoveryNote","appendStable","validatePaths","lookupPath","scope","limit","offset","noTruncate","strictRead","explain","lines","decisionDepth",...Ae],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...Ae],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},deps:{required:["id"],optional:["format","maxDepth","collapse","summary","full","nodeLimit","edgeLimit","tokenBudget","cursor","direction","kind"]},graph:{required:["subcommand"],optional:["id","target","kind","maxDepth","limit","after","direction","maxPaths","sample","exemptIsolate","exemptIsolateType","saveBaseline","rebuild","clear","summary","full"]},test:{required:["id"],optional:["add","addJson","remove","removeIndex","run","match","onlyIndex","onlyLast","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","acknowledgeLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext","measure","metricBelow","metricDiff",...Ae],mutuallyExclusive:[["acknowledgeLinkedTests","run"],["acknowledgeLinkedTests","background"]]},"test-all":{optional:["status","limit","offset","background","timeout","progress","envSet","envClear","sharedHostSafe","pmContext","overrideLinkedPmContext","workspaceContext","overrideLinkedWorkspaceContext","allowUntrustedLinkedTests","failOnContextMismatch","failOnSkipped","failOnEmptyTestRun","requireAssertionsForPm","checkContext","autoPmContext"]},telemetry:{optional:["subcommand","limit"]},"test-runs-list":{optional:["status","limit"]},"test-runs-status":{required:["runId"]},"test-runs-logs":{required:["runId"],optional:["stream","tail"]},"test-runs-stop":{required:["runId"],optional:["force"]},"test-runs-resume":{required:["runId"],optional:["author"]},stats:{optional:["includeEmpty","storage","metadataCoverage","fieldUtilization","byAssignee","byTag","byPriority","tagPrefix","measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]},duplicates:{optional:["status","since","threshold","limit"]},health:{optional:["strictDirectories","requireMergeDrivers","strictExit","failOnWarn","checkOnly","checkTelemetry","noRefresh","refreshVectors","verboseStaleItems","verboseAuthorEvents","brief","summary","skipVectors","skipIntegrity","skipDrift","full"]},validate:{optional:["checkStorageIntegrity","checkMetadata","metadataProfile","checkResolution","checkLifecycle","checkStaleBlockers","dependencyCycleSeverity","parentCycleSeverity","checkFiles","scanMode","includePmInternals","verboseFileLists","verboseDiagnostics","allAffectedIds","strictExit","failOnWarn","fixHints","autoFix","dryRun","fixScope","pruneMissing","checkHistoryDrift","checkCommandReferences","counts","full"]},assurance:{required:["subcommand"],optional:["kind","id","definition","trigger","treeId","gate","limit","dryRun","author","message","preset","owner","apply","enforcement"],conditionalRequired:[{property:"subcommand",value:"list",required:["kind"]},{property:"subcommand",value:"show",required:["kind","id"]},{property:"subcommand",value:"put",required:["kind","id","definition"]},{property:"subcommand",value:"remove",required:["kind","id"]},{property:"subcommand",value:"run",required:["id","trigger"]},{property:"subcommand",value:"apply",required:["preset","owner"]},{property:"subcommand",value:"derive",required:["owner"]},{property:"subcommand",value:"promote",required:["id","enforcement"]}]},gc:{optional:["dryRun","gcScope"]},contracts:{optional:["contractAction","command","summary","schemaOnly","flagsOnly","availabilityOnly","runtimeOnly","activeOnly","full"],mutuallyExclusiveWhen:xz},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...Mv,...oi],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:oi},"start-task":{required:["id"],optional:oi},"pause-task":{required:["id"],optional:oi},"close-task":{required:["id"],optional:["text","validateClose",...oi]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},Rz=Object.freeze(Object.fromEntries(Je.map(e=>[e,Ha[e]])));function Gv(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function Nz(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=ri[e];return{...n,description:r?.description??Gv(e),...r?.examples?{examples:r.examples}:{}}}function Dz(e,t){if((e==="list"||e.startsWith("list-"))&&t==="all")return{description:"Return items from every lifecycle status instead of the default active-status set."};if(e==="plan"&&Object.prototype.hasOwnProperty.call(jf,t))return jf[t];let n=Pv[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:ri[t]}function Pz(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=Dz(e,t);return{...r,description:o?.description??Gv(t),...o?.examples?{examples:o.examples}:{}}}function Lz(e,t){let n=Dv[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call($f,t)?$f[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:ni[t]}function Mz(e,t){let n={action:{const:e,description:ri.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=Lz(e,r);o&&(n[r]=Pz(e,r,o))}return n}function Fz(e,t){let n=t.flat();return t.map(r=>{let o=n.filter(i=>!r.includes(i));return{required:[...r],...o.length>0?{not:{anyOf:o.map(i=>({required:[i]}))}}:{},...e==="history-repair"&&r.includes("all")?{properties:{all:{const:!0}}}:e==="claim"&&r.includes("next")?{properties:{next:{const:!0}}}:{}}})}function $z(e){let t=[];if(e.conditionalRequired&&e.conditionalRequired.length>0)for(let n of e.conditionalRequired)t.push({if:{properties:{[n.property]:{const:n.value}},required:[n.property]},then:{required:n.required}});if(e.dependentAnyOfRequired&&e.dependentAnyOfRequired.length>0)for(let n of e.dependentAnyOfRequired)t.push({if:{required:[n.property]},then:{anyOf:n.anyOfRequired.map(r=>({required:[...r]}))}});if(e.mutuallyExclusive&&e.mutuallyExclusive.length>0)for(let n of e.mutuallyExclusive)t.push({not:{required:Le(n)}});if(e.mutuallyExclusiveWhen&&e.mutuallyExclusiveWhen.length>0)for(let n of e.mutuallyExclusiveWhen)t.push({not:{allOf:n.map(r=>({properties:{[r.property]:r.schema},required:[r.property]}))}});return t}function zf(e){if(!Object.prototype.hasOwnProperty.call(Ha,e))return;let t=Ha[e],n=Ez[e]??[];return Le(["action",...hz,...st(e)!==void 0?bz:[],...n,...t.required??[],...t.optional??[]])}function Bv(e){let t=Ha[e],n=Le(t.required??[]),r=zf(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:Mz(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=Fz(e,t.oneOfRequired));let i=$z(t);return i.length>0&&(o.allOf=i),o}function jz(e,t={}){let n=Bv(e),r={...n.properties};delete r.action;let o=[...n.anyOf??[],...n.oneOf??[]],i=(t.required??n.required.map(String)).filter(a=>a==="action"?!1:t.required===void 0?!0:!o.some(c=>c.required?.map(String).includes(a))),s={type:"object",additionalProperties:t.additionalProperties??!0,properties:{...r,options:{type:"object",additionalProperties:!0,description:"Advanced command options forwarded to the selected pm action."},...t.properties},required:i};return n.anyOf!==void 0&&(s.anyOf=n.anyOf),n.oneOf!==void 0&&(s.oneOf=n.oneOf),n.allOf!==void 0&&(s.allOf=n.allOf),s}function Hv(e){let t,n=()=>t??=e();return new Proxy({},{get:(r,o)=>n()[o],has:(r,o)=>o in n(),ownKeys:()=>Reflect.ownKeys(n()),getOwnPropertyDescriptor:(r,o)=>{let i=Reflect.getOwnPropertyDescriptor(n(),o);return i&&(i.configurable=!0),i}})}var qf="4.10.1",Wv=qf.split(".")[0],Kv="1.4.0",Uz=Hv(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Wv}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":qf,type:"object",oneOf:Je.map(e=>Bv(e))}));function zz(e,t){let n=Nz(e,t);if(typeof n.type=="string")return n;let o=(Array.isArray(n.anyOf)?n.anyOf:[]).find(a=>typeof a.type=="string");if(o){let{anyOf:a,...c}=n;return{...o,...c}}let{anyOf:i,...s}=n;return{...s,type:"string"}}function qz(){let e={action:{type:"string",description:ri.action?.description??"Tool action to execute."},options:{type:"object",additionalProperties:!0,description:"Advanced command options object forwarded to the selected pm action."}};for(let t of Object.keys(ni).sort())e[t]=zz(t,ni[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Kv,type:"object",additionalProperties:!1,required:["action"],properties:e}}var Vz=Hv(qz);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f4e5eed5-94c2-536a-8685-e20b735de480")}catch{}})();var Gz=new Set(["--author","--follow","--help","--lean","--token-accounting","--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor","--output-row-contract","--no-changed-fields","--no-extensions","--no-pager","--pm-path","--profile","--quiet","--interval-ms"]),Bz=new Set([...$g,...jg]),Hz=new Set(["--brief","--format","--full","--full-changed-fields","--id-only","--no-truncate","--stream"]),Wz=new Set(["--body-file","--file","--stdin-json"]),Kz=new Set(["--global","--local","--project"]),Yz=new Set(["--activity-limit","--default-depth","--section-activity","--section-blockers","--section-files","--section-hierarchy","--section-progress","--section-staleness","--section-tests","--section-workload","--stale-threshold-days"]),Xz=new Set(["action","fullChangedFields","idOnly","path","pmExecutable","timeoutMs"]),Jz=new Set(["configAction","id","name","query","reason","subcommand","target","text"]),Qz={assurance:{id:"<id>",kind:"<kind>",preset:"[kind]|[id]",subcommand:"<action>"},event:{title:"<title>"},files:{lookupPath:"lookup <path...>"},meet:{title:"<title>"},"item-reopen":{id:"<id>",reason:"<reason>"},merge:{subcommand:"<subcommand>"},remind:{title:"<title>"},workspace:{name:"<name>",subcommand:"snapshot",snapshotAction:"<snapshot-action>",target:"<target>"}},Zz={assurance:{"--tree":"treeId","--owner":"owner","--apply":"apply","--enforcement":"enforcement"},init:{"--id-prefix":"idPrefix","--no-merge-fence":"mergeFence","--workspace":"workspace"},create:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},update:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},"update-many":{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},files:{"--note":"addNote"},docs:{"--note":"addNote"},comments:{"--full-history":"full"},notes:{"--file":"text","--full-history":"full"},learnings:{"--full-history":"full"},gc:{"--scope":"gcScope"},contracts:{"--action":"contractAction"},schema:{"--no-allow-unset":"allowUnset","--type":"fieldTypeScope"},"history-author-acknowledge":{"--event":"historyEvent","--all-actionable":"allActionable"},"extension-init":{"--capability":"capability"},"package-init":{"--capability":"capability"},"extension-install":{"--gh":"github"},"package-install":{"--gh":"github"},"extension-adopt":{"--gh":"github"},"package-adopt":{"--gh":"github"},extension:{"--gh":"github","--scaffold":"init"},package:{"--gh":"github","--scaffold":"init"},install:{"--gh":"github"}},eq={"--pm-path":"path"},Xv={stats:{"--analytics":["measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]}};function tq(e){return e.startsWith("extension-")?`extension ${e.slice(10)}`:e.startsWith("package-")?`package ${e.slice(8)}`:e.startsWith("item-")?`item ${e.slice(5)}`:e}function Yv(e,t){let n=Zz[e]?.[t]??eq[t];return n!==void 0?n:t.replace(/^--/,"").replaceAll("_","-").replace(/-([a-z])/g,(r,o)=>o.toUpperCase())}function nq(e){let t=new Set;return e.filter(({flag:n})=>!n.startsWith("--")||t.has(n)?!1:(t.add(n),!0))}function rq(e,t){return t.find(({aliases:n})=>n?.includes(e))?.flag}function oq(e,t,n,r){let o=Xv[e]?.[t.flag];if(o!==void 0&&o.every(a=>r.has(a)))return{surface:"cli",input:t.flag,counterpart:o[0],disposition:"shared",reason:"The validated CLI JSON object fans out across strict SDK parameters."};let i=Yv(e,t.flag);if(r.has(i))return{surface:"cli",input:t.flag,counterpart:i,disposition:"shared",reason:"The CLI flag maps directly to a strict SDK action parameter."};let s=rq(t.flag,n);if(s!==void 0){let a=Yv(e,s);if(r.has(a))return{surface:"cli",input:t.flag,counterpart:a,disposition:"compatibility_alias",reason:`Compatibility spelling for ${s}.`}}return Gz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_transport",reason:"CLI process transport is supplied by the in-process SDK host."}:Hz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_presentation",reason:"CLI rendering or mutation projection does not alter the SDK result envelope."}:Wz.has(t.flag)?{surface:"cli",input:t.flag,disposition:"cli_adapter",reason:"Local file or stdin adaptation is a CLI boundary concern."}:Yz.has(t.flag)?{surface:"cli",input:t.flag,counterpart:"key",disposition:"compatibility_alias",reason:"CLI config shorthand normalizes to the SDK configAction/key/value contract."}:Kz.has(t.flag)?{surface:"cli",input:t.flag,counterpart:"scope",disposition:"cli_scope_selector",reason:"Mutually exclusive CLI scope switches normalize to the SDK scope parameter."}:{surface:"cli",input:t.flag,counterpart:i,disposition:"unclassified",reason:"The CLI flag has no strict SDK parameter or approved boundary classification."}}function iq(e,t,n){let r=Object.entries(Xv[e]??{}).find(([s,a])=>a.includes(t)&&n.some(({input:c,disposition:l})=>c===s&&l==="shared"));if(r!==void 0)return{surface:"sdk",input:t,counterpart:r[0],disposition:"shared",reason:"The strict SDK parameter is reachable through the validated CLI JSON object."};let o=n.find(({counterpart:s,disposition:a})=>s===t&&(a==="shared"||a==="compatibility_alias"||a==="cli_scope_selector"));if(o!==void 0)return{surface:"sdk",input:t,counterpart:o.input,disposition:"shared",reason:"The strict SDK parameter is reachable from the CLI contract."};let i=Qz[e]?.[t];return i!==void 0?{surface:"sdk",input:t,counterpart:i,disposition:"shared",reason:"The strict SDK parameter maps to a canonical CLI positional argument."}:Xz.has(t)?{surface:"sdk",input:t,disposition:"sdk_transport",reason:"The SDK host supplies in-process transport and workspace selection."}:Jz.has(t)?{surface:"sdk",input:t,disposition:"cli_positional",reason:"The CLI accepts this SDK parameter as a positional command argument."}:{surface:"sdk",input:t,disposition:"sdk_native",reason:"The typed SDK exposes this structured input without a canonical CLI long flag."}}function sq(e={}){let t=e.actions??Je,n=e.resolveFlags??Ff,r=e.resolveParameters??zf;return t.map(o=>{let i=tq(o),s=nq(n(i)).filter(({flag:d})=>st(o)!==void 0||!Bz.has(d)),a=new Set(r(o)??[]),c=s.map(d=>oq(o,d,s,a)),l=[...a].sort((d,u)=>d.localeCompare(u)).map(d=>iq(o,d,c));return{action:o,command:i,cli:c,sdk:l,unclassified:[...c,...l].filter(({disposition:d})=>d==="unclassified")}})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="167b98d4-a5b5-581d-ac0a-17e8e3bfc490")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{Option as aq}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01742f33-d1e8-5684-a585-2add88ddb73c")}catch{}})();async function kY(e,t,n,r,o){let i=Br(process.cwd(),r.path),s=await $e("command_result",{command:e,args:t,options:n,global:r,pm_root:i,result:o});return s.handled?s.result:o}function AY(e,t){for(let[n,r]of Object.entries(t))e.setOptionValueWithSource(n,r,"cli")}function Jv(e,t){let n=[],r=new Set;for(let o of t.keys){if(!Object.hasOwn(e,o))continue;let i=e[o];if(i!=null){if(typeof i=="string"){n.push(i);continue}if(!Array.isArray(i)||!i.every(s=>typeof s=="string"))return;r.has(i)||(r.add(i),n.push(...i))}}return n.length>0?n.join("; "):void 0}var Vf=Symbol("pm.resolvedGlobalOptions");function cq(e){return typeof e=="object"&&e!==null?e:{}}function Se(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function SY(e,t){e[Vf]={...t}}function xY(e){delete e[Vf]}function qn(e,t){return typeof e[t]=="string"?e[t]:void 0}function CY(e){let t=lq(e),n=e[Vf];if(n)return{...n,...t.length>0?{command:t}:{}};let r=cq(e),o=typeof r.optsWithGlobals=="function"?r.optsWithGlobals():typeof r.opts=="function"?r.opts():{};return{json:o.json===!0?!0:void 0,quiet:!!o.quiet,noChangedFields:o.changedFields===!1,...o.fullChangedFields===!0?{fullChangedFields:!0}:{},idOnly:o.idOnly===!0,...o.lean===!0?{lean:!0}:{},...o.tokenAccounting===!0?{tokenAccounting:!0}:{},outputInclude:qn(o,"outputInclude"),outputLimit:qn(o,"outputLimit"),outputBudget:qn(o,"outputBudget"),outputSession:qn(o,"outputSession"),outputCursor:qn(o,"outputCursor"),...o.outputRowContract===!0?{outputRowContract:!0}:{},...o.outputFormat==="toon"||o.outputFormat==="json"?{outputFormat:o.outputFormat}:{},path:qn(o,"pmPath")??qn(o,"path"),noExtensions:o.extensions===!1,noPager:!!o.noPager,profile:!!o.profile,...t.length>0?{command:t}:{},...typeof o.author=="string"?{author:o.author}:{}}}function lq(e){let t=[],n=e;for(;n?.parent;)t.unshift(n.name()),n=n.parent;return t.join(" ")}async function OY(e){if(e.json===!0)return e;let t=Br(process.cwd(),e.path);if(!await ee(ge(t)))return e;let n=await at(t);return{...e,defaultOutputFormat:n.output.default_format}}function dq(e,t){let n=t??[];return n.push(e),n}function Ge(e,t,n){if(typeof n!="string")return;let r=n.trim();r.length!==0&&e.push(t,r)}function Ve(e,t,n){n===!0&&e.push(t)}function Vn(e,t,n){if(Array.isArray(n))for(let r of n){if(typeof r!="string")continue;let o=r.trim();o.length!==0&&e.push(t,o)}}function k(e,t){return e[t]===!0?!0:void 0}function It(e,t){return e[t]===!1?!0:void 0}function IY(e,t){return typeof e[t]=="string"?e[t]:void 0}function uq(e,t,n,r=!1,o=void 0){let i=new aq(t,n).hideHelp();r&&i.argParser(o??dq),e.addOption(i)}function RY(e,t,n){for(let[r,o]of t)uq(e,r,o,n)}function Wa(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Qv(e,t){let n=Na(e,t);return typeof n=="string"||typeof n=="number"&&Number.isFinite(n)?n:void 0}function Ka(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function NY(e,t){let n=["test",e,"--run","--json","--progress"];return Vn(n,"--add",t.add),Vn(n,"--add-json",t.addJson),Vn(n,"--remove",t.remove),Vn(n,"--remove-index",t.removeIndex),Ge(n,"--match",t.match),Ge(n,"--only-index",t.onlyIndex),Ve(n,"--only-last",t.onlyLast),Vn(n,"--measure",t.measure),Ge(n,"--metric-below",t.metricBelow),Ge(n,"--metric-diff",t.metricDiff),Zv(n,t),Ge(n,"--author",t.author),Ge(n,"--message",t.message),Ve(n,"--force",t.force),n}function Zv(e,t){Ge(e,"--timeout",t.timeout),Vn(e,"--env-set",t.envSet),Vn(e,"--env-clear",t.envClear),Ve(e,"--shared-host-safe",t.sharedHostSafe),Ge(e,"--pm-context",t.pmContext),Ve(e,"--override-linked-pm-context",t.overrideLinkedPmContext),Ge(e,"--workspace-context",t.workspaceContext),Ve(e,"--override-linked-workspace-context",t.overrideLinkedWorkspaceContext),Ve(e,"--allow-untrusted-linked-tests",t.allowUntrustedLinkedTests),Ve(e,"--fail-on-context-mismatch",t.failOnContextMismatch),Ve(e,"--fail-on-skipped",t.failOnSkipped),Ve(e,"--fail-on-empty-test-run",t.failOnEmptyTestRun),Ve(e,"--require-assertions-for-pm",t.requireAssertionsForPm),Ve(e,"--check-context",t.checkContext),Ve(e,"--auto-pm-context",t.autoPmContext)}function DY(e){let t=["test-all","--json","--progress"];return Ge(t,"--status",e.status),Ge(t,"--limit",e.limit),Ge(t,"--offset",e.offset),Zv(t,e),t}function fq(e){return e.join(",")}function PY(e,t={}){let n=s=>Ct(e,Se(df,s)),r=s=>Da(e,Se(Pa,s)),o=n("type");if(t.requireType!==!1&&o===void 0)throw new h("Missing required option --type <value>. Why required: create resolves runtime schema fields/workflow from item type. Retry: add --type <built-in or configured custom type> (example: --type Task).",g.USAGE);let i={title:n("title"),description:n("description"),type:o,template:n("template"),createMode:n("createMode"),schedulePreset:n("schedulePreset"),status:n("status"),closeReason:n("closeReason"),completedAt:n("completedAt"),priority:n("priority"),tags:n("tags"),addTags:r("addTags"),body:n("body"),deadline:n("deadline"),estimatedMinutes:n("estimatedMinutes"),acceptanceCriteria:Jv(e,Se(Pa,"acceptanceCriteria")),definitionOfReady:n("definitionOfReady"),order:n("order"),rank:n("rank"),goal:n("goal"),objective:n("objective"),value:n("value"),impact:n("impact"),outcome:n("outcome"),whyNow:n("whyNow"),author:n("author"),message:n("message"),assignee:n("assignee"),parent:n("parent"),allowMissingParent:Wa(e,["allowMissingParent","allow_missing_parent"])===!0,allowUnresolvedDeps:Wa(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,allowDuplicate:k(e,"allowDuplicate")===!0,reviewer:n("reviewer"),risk:n("risk"),confidence:n("confidence"),sprint:n("sprint"),release:n("release"),blockedBy:n("blockedBy"),blockedReason:n("blockedReason"),unblockNote:n("unblockNote"),reporter:n("reporter"),severity:n("severity"),environment:n("environment"),reproSteps:n("reproSteps"),resolution:n("resolution"),expectedResult:n("expectedResult"),actualResult:n("actualResult"),affectedVersion:n("affectedVersion"),fixedVersion:n("fixedVersion"),component:n("component"),regression:e.regression===!0?"true":n("regression"),customerImpact:n("customerImpact"),dep:r("dep"),comment:r("comment"),note:r("note"),learning:r("learning"),file:r("file"),test:r("test"),doc:r("doc"),reminder:r("reminder"),event:r("event"),typeOption:r("typeOption"),field:r("field"),unset:r("unset"),clearDeps:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Ka(i,e),i}function LY(e){let t=o=>Ct(e,Se(ff,o)),n=o=>Da(e,Se(La,o)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Jv(e,Se(La,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:Wa(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:k(e,"replaceDeps"),replaceTests:k(e,"replaceTests"),replaceFiles:k(e,"replaceFiles"),replaceDocs:k(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:k(e,"clearDeps"),clearComments:k(e,"clearComments"),clearNotes:k(e,"clearNotes"),clearLearnings:k(e,"clearLearnings"),clearFiles:k(e,"clearFiles"),clearTests:k(e,"clearTests"),clearDocs:k(e,"clearDocs"),clearReminders:k(e,"clearReminders"),clearEvents:k(e,"clearEvents"),clearTypeOptions:k(e,"clearTypeOptions")};return Ka(r,e),r}var pq=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","filterAcMissing","filterEstimatesMissing","filterEstimateMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","filterHasNotes","filterNoNotes","filterHasLearnings","filterNoLearnings","filterHasFiles","filterNoFiles","filterHasDocs","filterNoDocs","filterHasTests","filterNoTests","filterHasComments","filterNoComments","filterHasDeps","filterNoDeps","filterHasBody","filterEmptyBody","filterHasLinkedCommand","filterNoLinkedCommand","ids","limit","offset","dryRun","rollback","checkpoint"]);function MY(e){let t={};for(let[n,r]of Object.entries(e))pq.has(n)||(t[n]=r);return t}function M(e,t){let n=Se(af,t),r=Ct(e,n);if(r!==void 0)return r;for(let o of n.keys){let i=e[o];if(Array.isArray(i)){let s=i.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof i=="string")return i;if(typeof i=="number"&&Number.isFinite(i))return String(i)}}function eT(e){let t=k(e,"filterFilesMissing"),n=k(e,"filterDocsMissing");return{filterReviewerMissing:k(e,"filterReviewerMissing"),filterRiskMissing:k(e,"filterRiskMissing"),filterConfidenceMissing:k(e,"filterConfidenceMissing"),filterSprintMissing:k(e,"filterSprintMissing"),filterReleaseMissing:k(e,"filterReleaseMissing"),hasNotes:k(e,"hasNotes"),hasLearnings:k(e,"hasLearnings"),hasFiles:k(e,"hasFiles"),hasDocs:k(e,"hasDocs"),hasTests:k(e,"hasTests"),hasComments:k(e,"hasComments"),hasDeps:k(e,"hasDeps"),hasBody:k(e,"hasBody"),hasLinkedCommand:k(e,"hasLinkedCommand"),noNotes:It(e,"notes"),noLearnings:It(e,"learnings"),noFiles:It(e,"files")??t,filterFilesMissing:t,noDocs:It(e,"docs")??n,filterDocsMissing:n,noTests:It(e,"tests"),noComments:It(e,"comments"),noDeps:It(e,"deps"),emptyBody:k(e,"emptyBody"),noLinkedCommand:It(e,"linkedCommand")}}function FY(e){let t={status:M(e,"status"),type:M(e,"type"),tag:M(e,"tag"),priority:M(e,"priority"),deadlineBefore:M(e,"deadlineBefore"),deadlineAfter:M(e,"deadlineAfter"),updatedAfter:M(e,"updatedAfter"),updatedBefore:M(e,"updatedBefore"),createdAfter:M(e,"createdAfter"),createdBefore:M(e,"createdBefore"),today:k(e,"today"),recent:k(e,"recent"),ids:M(e,"ids"),assignee:M(e,"assignee"),assigneeFilter:M(e,"assigneeFilter"),parent:M(e,"parent"),sprint:M(e,"sprint"),release:M(e,"release"),limit:M(e,"limit"),offset:M(e,"offset"),noTruncate:It(e,"truncate"),includeBody:k(e,"includeBody"),strictRead:k(e,"strictRead"),compact:k(e,"compact"),brief:k(e,"brief"),full:k(e,"full"),fields:M(e,"fields"),sort:M(e,"sort"),order:M(e,"order"),tree:k(e,"tree"),treeDepth:M(e,"treeDepth"),filterAcMissing:k(e,"filterAcMissing"),filterEstimatesMissing:Wa(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:k(e,"filterResolutionMissing"),filterMetadataMissing:k(e,"filterMetadataMissing"),...eT(e)};return Ka(t,e),t}function $Y(e){return{groupBy:typeof e.groupBy=="string"?e.groupBy:void 0,count:e.count===!0?!0:void 0,completion:e.completion===!0?!0:void 0,sum:typeof e.sum=="string"?e.sum:void 0,avg:typeof e.avg=="string"?e.avg:void 0,includeUnparented:e.includeUnparented===!0||e.include_unparented===!0,status:typeof e.status=="string"?e.status:void 0,type:M(e,"type"),tag:M(e,"tag"),priority:M(e,"priority"),deadlineBefore:M(e,"deadlineBefore"),deadlineAfter:M(e,"deadlineAfter"),assignee:M(e,"assignee"),assigneeFilter:M(e,"assigneeFilter"),parent:M(e,"parent"),sprint:M(e,"sprint"),release:M(e,"release")}}function jY(e,t,n){if(rr(t),n.quiet)return;let r=Array.isArray(t.warnings)?t.warnings:[],o={type:"meta",command:e,count:t.count,now:t.now,filters:t.filters};if(r.length>0&&(o.warnings=r),!!vt(`${JSON.stringify(o)}
199
+ `)){for(let i of t.items)if(!vt(`${JSON.stringify({type:"item",command:e,item:i})}
200
+ `))return;vt(`${JSON.stringify({type:"end",command:e,count:t.count})}
201
+ `)}}function UY(e,t,n){if(rr(e),n.quiet)return;let r={type:"meta",command:"activity",count:e.count,filters:{id:t.id??null,op:t.op??null,author:t.author??null,from:t.from??null,to:t.to??null,limit:t.limit??null}};if(!vt(`${JSON.stringify(r)}
202
+ `))return;let o=e.compact&&e.compact_activity?e.compact_activity:e.activity??[];for(let i of o)if(!vt(`${JSON.stringify({type:"entry",command:"activity",entry:i})}
203
+ `))return;vt(`${JSON.stringify({type:"end",command:"activity",count:e.count})}
204
+ `)}function zY(e){let t=l=>Ct(e,Se(Oa,l)),n=l=>{let d=Na(e,Se(Oa,l));if(typeof d=="string"||typeof d=="number"&&Number.isFinite(d))return d},r=t("fields"),o=e.compact===!0,i=e.full===!0,s=!o&&!i&&r===void 0,c={mode:e.semantic===!0?"semantic":e.hybrid===!0?"hybrid":t("mode"),matchMode:t("matchMode"),minScore:n("minScore"),count:k(e,"count"),semanticWeight:n("semanticWeight"),includeLinked:k(e,"includeLinked"),titleExact:k(e,"titleExact"),phraseExact:k(e,"phraseExact"),highlight:k(e,"highlight"),status:t("status"),type:t("type"),tag:t("tag"),priority:t("priority"),deadlineBefore:t("deadlineBefore"),deadlineAfter:t("deadlineAfter"),updatedAfter:t("updatedAfter"),updatedBefore:t("updatedBefore"),createdAfter:t("createdAfter"),createdBefore:t("createdBefore"),assignee:t("assignee"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),fields:r,compact:o||s?!0:void 0,full:k(e,"full"),...eT(e)};return Ka(c,e),c}function qY(e){let t=e.map(n=>n.trim()).filter(n=>n.length>0).join(" ");if(t.length===0)throw new h("Search query must not be empty",g.USAGE);return t}function VY(e){let t=r=>Ct(e,Se(cf,r)),n={id:t("id"),op:t("op"),author:t("author"),from:t("from"),to:t("to"),limit:t("limit"),compact:e.full===!0||e.provenance===!0?!1:e.compact===!0||e.raw===!0?!0:void 0,...e.raw===!0||e.compact===!0||e.full===!0?{raw:!0}:{},unbounded:k(e,"unbounded"),provenance:k(e,"provenance"),provenanceSummary:k(e,"provenanceSummary"),harness:Array.isArray(e.harness)?e.harness:void 0,agentInstance:Array.isArray(e.agentInstance)?e.agentInstance:void 0,provenanceFilter:Array.isArray(e.provenanceFilter)?e.provenanceFilter:void 0};return Object.fromEntries(Object.entries(n).filter(([,r])=>r!==void 0))}var mq=new Set(["","rows","ndjson","jsonl","true","1","yes","on"]),_q=new Set(["false","off","none","0"]);function GY(e){if(e===!0)return!0;if(e===!1||e===void 0||e===null)return!1;if(typeof e=="string"){let t=e.trim().toLowerCase();if(mq.has(t))return!0;if(_q.has(t))return!1}throw new h("Activity --stream accepts rows|ndjson|jsonl (or no value)",g.USAGE)}function BY(e){let t=s=>Ct(e,Se(Ia,s)),n=s=>Qv(e,Se(Ia,s)),r=e.section,o=Array.isArray(r)?r.filter(s=>typeof s=="string"&&s.trim().length>0):typeof r=="string"&&r.trim().length>0?[r]:void 0,i={date:t("date"),from:t("from"),to:t("to"),past:e.past===!0?!0:void 0,type:t("type"),tag:t("tag"),priority:t("priority"),assignee:t("assignee"),assigneeFilter:t("assigneeFilter"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),format:t("format"),depth:t("depth"),fields:t("fields"),section:o&&o.length>0?o:void 0,activityLimit:t("activityLimit"),staleThreshold:t("staleThreshold"),tokenBudget:n("tokenBudget"),noExtensionHealth:e.extensionHealth===!1?!0:void 0,noTags:e.tags===!1?!0:void 0};for(let[s,a]of Object.entries(e))Object.hasOwn(i,s)||(i[s]=a);return i}function HY(e){let t=o=>Ct(e,Se(Ra,o)),n=o=>Qv(e,Se(Ra,o)),r={type:t("type"),tag:t("tag"),priority:n("priority"),assignee:t("assignee"),assigneeFilter:t("assigneeFilter"),sprint:t("sprint"),release:t("release"),parent:t("parent"),limit:t("limit"),blockedLimit:t("blockedLimit"),readyOnly:e.readyOnly===!0||e.ready_only===!0?!0:void 0,format:t("format"),tokenBudget:n("tokenBudget")};for(let[o,i]of Object.entries(e))Object.hasOwn(r,o)||(r[o]=i);return r}function gq(e){if(!e||typeof e!="object")return[];let t=e,n=new Set,r=a=>{if(typeof a!="string")return;let c=a.trim();c.length!==0&&n.add(c)};r(t.id);let o=t.item;o&&typeof o=="object"&&r(o.id);let i=t.ids;if(Array.isArray(i))for(let a of i)r(a);let s=t.items;if(Array.isArray(s))for(let a of s)!a||typeof a!="object"||r(a.id);return[...n].sort((a,c)=>a.localeCompare(c))}async function WY(e,t){let n=Br(process.cwd(),e.path),r=await Nu(n,gq(t),{background:!Zd()});e.profile&&r.warnings.length>0&&vd(`profile:search_refresh_warnings=${fq(r.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]="13c02696-29a7-598e-888a-3502fd88bfbe")}catch{}})();export{yq as a,si as b,ee as c,Bf as d,le as e,Y as f,L as g,$r as h,tt as i,ai as j,Xa as k,vq as l,ci as m,li as n,di as o,ui as p,fi as q,Wf as r,Me as s,pi as t,sT as u,aT as v,Sq as w,_e as x,ec as y,lT as z,Ja as A,x as B,g as C,_i as D,h as E,$ as F,uT as G,q as H,Xf as I,Iq as J,fT as K,Yf as L,Jf as M,pT as N,gT as O,yT as P,Lq as Q,oe as R,_t as S,np as T,de as U,zq as V,MT as W,UT as X,zT as Y,VT as Z,GT as _,ic as $,sc as aa,We as ba,n2 as ca,WT as da,$c as ea,ac as fa,cp as ga,hi as ha,yt as ia,cc as ja,ZT as ka,Yn as la,lp as ma,Xn as na,bi as oa,Jn as pa,wi as qa,l2 as ra,d2 as sa,u2 as ta,vi as ua,Ti as va,f2 as wa,p2 as xa,m2 as ya,_2 as za,ki as Aa,Ur as Ba,lc as Ca,up as Da,Ai as Ea,fp as Fa,pp as Ga,g2 as Ha,y2 as Ia,fc as Ja,pc as Ka,gk as La,qr as Ma,xi as Na,Vr as Oa,Ep as Pa,vp as Qa,Pk as Ra,Fk as Sa,Ci as Ta,kp as Ua,N2 as Va,Br as Wa,Hk as Xa,Dt as Ya,ge as Za,Qn as _a,Hr as $a,Zn as ab,Ap as bb,mc as cb,Oi as db,Kk as eb,D2 as fb,Yk as gb,Xk as hb,P2 as ib,L2 as jb,Jk as kb,M2 as lb,X as mb,Qp as nb,Zp as ob,tm as pb,nm as qb,_c as rb,hc as sb,bc as tb,U2 as ub,z2 as vb,q2 as wb,sA as xb,Sp as yb,V2 as zb,xp as Ab,wc as Bb,dA as Cb,uA as Db,Yr as Eb,Ec as Fb,vc as Gb,Tc as Hb,kc as Ib,Ac as Jb,Di as Kb,Sc as Lb,Q2 as Mb,bA as Nb,wA as Ob,B as Pb,ue as Qb,Lt as Rb,Pp as Sb,xc as Tb,Lp as Ub,Cc as Vb,Oc as Wb,Ic as Xb,Rc as Yb,Nc as Zb,Dc as _b,Lc as $b,Mc as ac,Fc as bc,lS as cc,hS as dc,wS as ec,Dm as fc,Pm as gc,NS as hc,yG as ic,ox as jc,ix as kc,AG as lc,jm as mc,sx as nc,Qc as oc,lx as pc,dx as qc,DG as rc,Wi as sc,mx as tc,_x as uc,gx as vc,yx as wc,hx as xc,bx as yc,wx as zc,$t as Ac,Ex as Bc,vx as Cc,rr as Dc,Tx as Ec,Ki as Fc,co as Gc,kx as Hc,Ax as Ic,ye as Jc,Yi as Kc,Ke as Lc,Zc as Mc,Sx as Nc,xx as Oc,Cx as Pc,Ox as Qc,$e as Rc,Xi as Sc,lo as Tc,Lx as Uc,$x as Vc,VG as Wc,jx as Xc,Ux as Yc,GG as Zc,KG as _c,e_ as $c,zx as ad,qx as bd,Vx as cd,Gx as dd,Xx as ed,Zx as fd,YG as gd,eC as hd,i_ as id,nC as jd,rC as kd,XG as ld,oC as md,Ji as nd,JG as od,or as pd,sC as qd,aC as rd,rl as sd,s_ as td,fC as ud,Ie as vd,he as wd,il as xd,nt as yd,ve as zd,VC as Ad,__ as Bd,sl as Cd,ts as Dd,al as Ed,y_ as Fd,HC as Gd,tO as Hd,nO as Id,ir as Jd,E_ as Kd,hB as Ld,v_ as Md,rO as Nd,bB as Od,bn as Pd,T_ as Qd,iO as Rd,os as Sd,yo as Td,gI as Ud,wn as Vd,ho as Wd,je as Xd,bl as Yd,zt as Zd,cs as _d,kI as $d,AI as ae,ls as be,Al as ce,XB as de,JB as ee,QB as fe,II as ge,RI as he,NI as ie,Pl as je,Ll as ke,Ml as le,a5 as me,nR as ne,rR as oe,oR as pe,iR as qe,sR as re,bo as se,Ul as te,zl as ue,cR as ve,c5 as we,lR as xe,ql as ye,wo as ze,Xe as Ae,zH as Be,qH as Ce,VH as De,gs as Ee,bR as Fe,wR as Ge,Gl as He,y5 as Ie,E5 as Je,Q_ as Ke,vR as Le,TR as Me,v5 as Ne,it as Oe,T5 as Pe,CR as Qe,RR as Re,FR as Se,ng as Te,O5 as Ue,I5 as Ve,Eo as We,Hl as Xe,Wl as Ye,R5 as Ze,zR as _e,N5 as $e,D5 as af,sg as bf,ys as cf,VR as df,fr as ef,pr as ff,hs as gf,bs as hf,vo as if,ag as jf,Xl as kf,To as lf,XR as mf,Ql as nf,JR as of,dg as pf,ug as qf,fg as rf,QR as sf,ZR as tf,pg as uf,ko as vf,z5 as wf,eN as xf,mg as yf,_g as zf,gg as Af,Zl as Bf,Je as Cf,yg as Df,tN as Ef,nN as Ff,rN as Gf,oN as Hf,iN as If,sN as Jf,aN as Kf,hg as Lf,cN as Mf,ed as Nf,bg as Of,wg as Pf,Eg as Qf,td as Rf,vg as Sf,Tg as Tf,nd as Uf,Bt as Vf,rd as Wf,xN as Xf,CN as Yf,Dg as Zf,Ts as _f,cd as $f,ld as ag,id as bg,Ao as cg,vs as dg,Sg as eg,sd as fg,xg as gg,An as hg,Mg as ig,$g as jg,jg as kg,MN as lg,st as mg,rH as ng,fd as og,qN as pg,oH as qg,Bg as rg,Wg as sg,Yg as tg,Xg as ug,Jg as vg,ey as wg,m0 as xg,vH as yg,g0 as zg,ny as Ag,TH as Bg,oy as Cg,h0 as Dg,v0 as Eg,iy as Fg,cy as Gg,vt as Hg,uy as Ig,gy as Jg,vd as Kg,aD as Lg,Ro as Mg,Kt as Ng,wr as Og,pD as Pg,Sd as Qg,Cy as Rg,mD as Sg,At as Tg,St as Ug,gD as Vg,Er as Wg,mW as Xg,xd as Yg,No as Zg,yD as _g,hD as $g,Od as ah,vr as bh,Id as ch,Cn as dh,kD as eh,_W as fh,gW as gh,Rd as hh,AD as ih,$s as jh,Py as kh,Te as lh,Yt as mh,On as nh,QD as oh,ZD as ph,eP as qh,tP as rh,Fd as sh,nP as th,rP as uh,sP as vh,Xy as wh,js as xh,In as yh,uP as zh,d6 as Ah,pP as Bh,Qy as Ch,mP as Dh,_P as Eh,hP as Fh,y6 as Gh,EP as Hh,T6 as Ih,AP as Jh,xP as Kh,CP as Lh,OP as Mh,IP as Nh,Ud as Oh,DP as Ph,N6 as Qh,D6 as Rh,P6 as Sh,L6 as Th,M6 as Uh,F6 as Vh,$6 as Wh,MP as Xh,FP as Yh,$P as Zh,jP as _h,UP as $h,zP as ai,qP as bi,K6 as ci,Hs as di,_L as ei,Zt as fi,at as gi,Fo as hi,Sr as ii,zh as ji,Zd as ki,k8 as li,OM as mi,IM as ni,RM as oi,ru as pi,jM as qi,sa as ri,uF as si,aa as ti,Go as ui,uu as vi,Or as wi,bF as xi,Bo as yi,Ho as zi,ub as Ai,kF as Bi,g3 as Ci,fu as Di,fb as Ei,IF as Fi,y3 as Gi,RF as Hi,NF as Ii,T3 as Ji,ua as Ki,yb as Li,mu as Mi,GF as Ni,BF as Oi,S3 as Pi,hb as Qi,Rr as Ri,gu as Si,hu as Ti,ga as Ui,F3 as Vi,Su as Wi,ha as Xi,Ab as Yi,ba as Zi,xu as _i,Cu as $i,Ou as aj,Iu as bj,Rb as cj,Nb as dj,xb as ej,Nu as fj,uj as gj,Lr as hj,vj as ij,Tj as jj,kj,Cj as lj,Oj as mj,Rj as nj,Fj as oj,Bb as pj,jj as qj,Uj as rj,zj as sj,g9 as tj,h9 as uj,Ea as vj,ju as wj,Wb as xj,Hb as yj,Gj as zj,Bj as Aj,Kb as Bj,Kj as Cj,Qj as Dj,e1 as Ej,n1 as Fj,r1 as Gj,s1 as Hj,c1 as Ij,l1 as Jj,b1 as Kj,Aa as Lj,mw as Mj,Y1 as Nj,s4 as Oj,FU as Pj,$U as Qj,jU as Rj,af as Sj,Oa as Tj,UU as Uj,Ia as Vj,Ra as Wj,cf as Xj,Ct as Yj,Na as Zj,Da as _j,lf as $j,df as ak,Pa as bk,uf as ck,ff as dk,La as ek,zU as fk,mf as gk,_f as hk,gf as ik,Yw as jk,Ma as kk,Xw as lk,yf as mk,Jw as nk,hf as ok,bf as pk,wf as qk,Ef as rk,HU as sk,vf as tk,Tf as uk,WU as vk,KU as wk,nE as xk,YU as yk,Un as zk,NK as Ak,ZU as Bk,DK as Ck,ja as Dk,Ua as Ek,$a as Fk,eE as Gk,ez as Hk,Fa as Ik,PK as Jk,LK as Kk,ti as Lk,oz as Mk,Ga as Nk,iz as Ok,Ba as Pk,sE as Qk,aE as Rk,cE as Sk,lE as Tk,dE as Uk,uE as Vk,fE as Wk,pE as Xk,mE as Yk,_E as Zk,gE as _k,yE as $k,hE as al,bE as bl,Rf as cl,wE as dl,EE as el,Nf as fl,ke as gl,Df as hl,Af as il,vE as jl,TE as kl,kE as ll,AE as ml,SE as nl,xE as ol,CE as pl,OE as ql,IE as rl,RE as sl,NE as tl,DE as ul,Sf as vl,PE as wl,LE as xl,Pf as yl,sz as zl,ME as Al,FE as Bl,$E as Cl,jE as Dl,UE as El,zE as Fl,qE as Gl,VE as Hl,GE as Il,BE as Jl,Lf as Kl,WE as Ll,KE as Ml,YE as Nl,XE as Ol,JE as Pl,QE as Ql,ZE as Rl,ev as Sl,tv as Tl,nv as Ul,rv as Vl,Mf as Wl,xf as Xl,av as Yl,cv as Zl,lv as _l,dv as $l,uv as am,fv as bm,pv as cm,Cf as dm,mv as em,_v as fm,Of as gm,gv as hm,yv as im,hv as jm,bv as km,wv as lm,Ot as mm,vv as nm,Tv as om,kv as pm,Av as qm,Sv as rm,pz as sm,mz as tm,Ff as um,gz as vm,Uv as wm,wz as xm,zv as ym,Vv as zm,Rz as Am,jz as Bm,qf as Cm,Wv as Dm,Kv as Em,Uz as Fm,Vz as Gm,sq as Hm,kY as Im,AY as Jm,SY as Km,xY as Lm,CY as Mm,lq as Nm,OY as Om,dq as Pm,IY as Qm,uq as Rm,RY as Sm,NY as Tm,DY as Um,fq as Vm,PY as Wm,LY as Xm,MY as Ym,FY as Zm,$Y as _m,jY as $m,UY as an,zY as bn,qY as cn,VY as dn,GY as en,BY as fn,HY as gn,WY as hn};
205
+ //# sourceMappingURL=chunk-NOPL37X4.js.map