@unbrained/pm-cli 2026.8.30 → 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 (176) hide show
  1. package/.agents/skills/HARNESS_COMPATIBILITY.md +1 -1
  2. package/.agents/skills/README.md +1 -1
  3. package/.agents/skills/pm-developer/SKILL.md +1 -1
  4. package/.agents/skills/pm-developer/references/COMMAND_PLAYBOOK.md +2 -2
  5. package/.agents/skills/pm-developer/references/MULTI_AGENT_MERGE.md +1 -1
  6. package/.agents/skills/pm-developer/references/TOKEN_BUDGETS.md +1 -1
  7. package/.agents/skills/pm-extensions/SKILL.md +2 -2
  8. package/.agents/skills/pm-extensions/references/AUTHORING.md +1 -1
  9. package/.agents/skills/pm-extensions/references/LIFECYCLE.md +1 -1
  10. package/.agents/skills/pm-sdk/SKILL.md +1 -1
  11. package/.agents/skills/pm-user/SKILL.md +2 -2
  12. package/.agents/skills/pm-user/references/WORKFLOWS.md +2 -2
  13. package/.claude-plugin/marketplace.json +2 -2
  14. package/AGENTS.md +16 -14
  15. package/CHANGELOG.md +41 -6
  16. package/README.md +3 -3
  17. package/dist/cli/commands/merge.d.ts +1 -1
  18. package/dist/cli/commands/merge.js +3 -3
  19. package/dist/cli/register-list-query.js +32 -17
  20. package/dist/cli/register-mutation.js +8 -5
  21. package/dist/cli/register-operations.d.ts +2 -0
  22. package/dist/cli/register-operations.js +20 -9
  23. package/dist/cli-bundle/bundle-manifest.json +144 -144
  24. package/dist/cli-bundle/chunks/{chunk-CMIEDWAY.js → chunk-2MC2LCXZ.js} +41 -41
  25. package/dist/cli-bundle/chunks/{chunk-WS2GJQVG.js → chunk-3WICXLVT.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-7SKMLSMX.js → chunk-6XIIGE7U.js} +2 -2
  27. package/dist/cli-bundle/chunks/chunk-ALKKAUFN.js +35 -0
  28. package/dist/cli-bundle/chunks/{chunk-MTTKAUBX.js → chunk-DTGWEL23.js} +2 -2
  29. package/dist/cli-bundle/chunks/chunk-GOACULJW.js +13 -0
  30. package/dist/cli-bundle/chunks/chunk-NOPL37X4.js +205 -0
  31. package/dist/cli-bundle/chunks/{chunk-2UETTHY6.js → chunk-TAG4VC22.js} +30 -30
  32. package/dist/cli-bundle/chunks/{chunk-3TEF3HM5.js → chunk-U45JXJCC.js} +2 -2
  33. package/dist/cli-bundle/chunks/{chunk-TGNAA66W.js → chunk-X4RCGLTX.js} +2 -2
  34. package/dist/cli-bundle/chunks/{chunk-2MKLQL2E.js → chunk-Y7VOMSZT.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-list-query-OMKJ5ONN.js → register-list-query-XYNX4ASQ.js} +11 -11
  36. package/dist/cli-bundle/chunks/register-mutation-2MVLRS3J.js +20 -0
  37. package/dist/cli-bundle/chunks/register-operations-WCIDXBU3.js +2 -0
  38. package/dist/cli-bundle/chunks/{register-setup-GLQ5SYV3.js → register-setup-KVNC5KPL.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-HVQ22RC4.js → chunk-2FEZ5SKM.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-Y3JJXRVK.js → chunk-4O4CJAR6.js} +5 -5
  41. package/dist/cli-bundle/focused-chunks/chunk-7VATS5QY.js +16 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-LYFWQMVC.js → chunk-BEVHCEWG.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-TDK3OCX3.js → chunk-FWPLDEXF.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-JEFKLWMM.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-JZYPPMXF.js → chunk-KB5OFSFD.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-73EDXGYE.js → chunk-MKHG3T76.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-3AVAWVZA.js → chunk-PF3E6Q36.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-AD6ULRAF.js → chunk-QDFJIRKN.js} +4 -4
  49. package/dist/cli-bundle/focused-chunks/{chunk-RKOKG43G.js → chunk-RMRCQPWU.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-XXOWRJZ5.js → chunk-S4U5CN5Q.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-THEPQMLX.js → chunk-SVXJYD6G.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-T2LXXSOD.js +158 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-Y6JJIX6I.js +51 -0
  54. package/dist/cli-bundle/main.js +2 -2
  55. package/dist/cli-bundle/sdk-authoring.js +1 -1
  56. package/dist/cli-bundle/sdk-contracts.js +1 -1
  57. package/dist/cli-bundle/sdk-core.js +27 -27
  58. package/dist/cli-bundle/sdk-governance.js +1 -1
  59. package/dist/cli-bundle/sdk-graph.js +1 -1
  60. package/dist/cli-bundle/sdk-merge.js +33 -33
  61. package/dist/cli-bundle/sdk-query.js +1 -1
  62. package/dist/cli-bundle/sdk-runtime.js +1 -1
  63. package/dist/cli-bundle/sdk-testing.js +1 -1
  64. package/dist/cli-bundle/sdk.js +10 -10
  65. package/dist/core/history/drift-scan.js +6 -6
  66. package/dist/core/history/history.d.ts +6 -0
  67. package/dist/core/history/history.js +47 -5
  68. package/dist/core/history/replay.d.ts +12 -1
  69. package/dist/core/history/replay.js +60 -39
  70. package/dist/core/schema/runtime-schema.d.ts +4 -0
  71. package/dist/core/schema/runtime-schema.js +60 -48
  72. package/dist/core/schema/status-defs-file.js +5 -2
  73. package/dist/mcp/legacy-adapter.d.ts +11 -2
  74. package/dist/mcp/legacy-adapter.js +26 -12
  75. package/dist/mcp/server.d.ts +2 -2
  76. package/dist/mcp/server.js +78 -15
  77. package/dist/mcp/tool-definitions.js +56 -2
  78. package/dist/sdk/agent-capability-contracts.js +4 -2
  79. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  80. package/dist/sdk/cli-contracts/flag-contracts.js +6 -2
  81. package/dist/sdk/cli-contracts/grammar-contracts.d.ts +1 -1
  82. package/dist/sdk/cli-contracts/grammar-contracts.js +12 -2
  83. package/dist/sdk/cli-contracts/runtime-contracts.js +3 -2
  84. package/dist/sdk/cli-contracts/tool-schema.js +11 -3
  85. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +14 -2
  86. package/dist/sdk/governance/health.js +17 -6
  87. package/dist/sdk/governance/status-role-diagnostics.d.ts +27 -0
  88. package/dist/sdk/governance/status-role-diagnostics.js +36 -0
  89. package/dist/sdk/governance/validate-normalization.d.ts +6 -0
  90. package/dist/sdk/governance/validate-normalization.js +37 -0
  91. package/dist/sdk/governance/validate.d.ts +1 -1
  92. package/dist/sdk/governance/validate.js +20 -35
  93. package/dist/sdk/governance/workspace-position.d.ts +69 -0
  94. package/dist/sdk/governance/workspace-position.js +164 -0
  95. package/dist/sdk/governance.d.ts +2 -0
  96. package/dist/sdk/governance.js +4 -2
  97. package/dist/sdk/history-read.js +14 -6
  98. package/dist/sdk/history-repair.js +17 -10
  99. package/dist/sdk/index.d.ts +2 -1
  100. package/dist/sdk/index.js +4 -3
  101. package/dist/sdk/init-agent-guidance.js +4 -4
  102. package/dist/sdk/lifecycle/update.js +23 -10
  103. package/dist/sdk/mcp/discovery.d.ts +152 -0
  104. package/dist/sdk/mcp/discovery.js +495 -0
  105. package/dist/sdk/mcp/protocol.d.ts +10 -2
  106. package/dist/sdk/mcp/protocol.js +15 -4
  107. package/dist/sdk/merge/index.d.ts +1 -1
  108. package/dist/sdk/merge/index.js +3 -3
  109. package/dist/sdk/merge/receipts.d.ts +27 -1
  110. package/dist/sdk/merge/receipts.js +27 -8
  111. package/dist/sdk/merge/three-way.d.ts +3 -1
  112. package/dist/sdk/merge/three-way.js +9 -7
  113. package/dist/sdk/query/context.js +11 -14
  114. package/dist/sdk/query/list.d.ts +2 -0
  115. package/dist/sdk/query/list.js +33 -12
  116. package/dist/sdk/runtime-extended-actions.js +10 -6
  117. package/dist/sdk/schema.js +12 -2
  118. package/dist/sdk/test/execution.d.ts +15 -0
  119. package/dist/sdk/test/execution.js +35 -27
  120. package/docs/AGENT_GUIDE.md +12 -4
  121. package/docs/AGENT_PROVENANCE_ADR.md +1 -1
  122. package/docs/AGENT_RUNTIME_PRIMITIVES.md +2 -2
  123. package/docs/ARCHITECTURE.md +5 -0
  124. package/docs/CLAUDE_CODE_PLUGIN.md +5 -5
  125. package/docs/COMMANDS.md +12 -12
  126. package/docs/CONFIGURATION.md +1 -1
  127. package/docs/CONTEXT_RECOVERY_PRIMITIVES.md +14 -5
  128. package/docs/DEFECT_RECURRENCE.md +2 -0
  129. package/docs/MCP_2026_07_28.md +33 -9
  130. package/docs/MCP_2026_07_28_CONFORMANCE.md +1 -0
  131. package/docs/MCP_CAPABILITY_SURFACES.md +7 -1
  132. package/docs/MCP_REMOTE_TRANSPORT_SECURITY.md +15 -3
  133. package/docs/MERGE_SAFETY.md +30 -2
  134. package/docs/ONBOARDING.md +1 -1
  135. package/docs/OUTPUT_TOKEN_ACCOUNTING.md +5 -3
  136. package/docs/PROGRESSIVE_TOOL_DISCOVERY.md +42 -0
  137. package/docs/README.md +3 -1
  138. package/docs/READ_OUTPUT_CONTRACTS.md +1 -1
  139. package/docs/RECURRENCE_RECOVERY_CONTRACTS.md +1 -1
  140. package/docs/SDK.md +3 -3
  141. package/docs/TESTING.md +23 -14
  142. package/docs/WORKSPACE_POSITION_AND_LIFECYCLE.md +113 -0
  143. package/docs/agent-task-token-baseline.json +157 -3
  144. package/docs/agent-task-transcripts.json +143 -0
  145. package/docs/examples/policy-restricted-extension/README.md +2 -2
  146. package/docs/examples/starter-extension/README.md +1 -1
  147. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +4 -3
  148. package/docs/performance/cli-transport-overhead.md +8 -6
  149. package/marketplace.json +2 -2
  150. package/package.json +4 -4
  151. package/packages/pm-beads/package.json +1 -1
  152. package/packages/pm-calendar/package.json +1 -1
  153. package/packages/pm-command-kit/package.json +1 -1
  154. package/packages/pm-digital-twin/package.json +1 -1
  155. package/packages/pm-governance-audit/package.json +1 -1
  156. package/packages/pm-guide-shell/package.json +1 -1
  157. package/packages/pm-kanban/package.json +1 -1
  158. package/packages/pm-lifecycle-hooks/package.json +1 -1
  159. package/packages/pm-linked-test-adapters/package.json +1 -1
  160. package/packages/pm-search-advanced/package.json +1 -1
  161. package/packages/pm-templates/package.json +1 -1
  162. package/packages/pm-todos/package.json +1 -1
  163. package/packages/pm-vcs/package.json +1 -1
  164. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  165. package/plugins/pm-claude/README.md +4 -3
  166. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  167. package/sdk/public-surface.json +314 -10
  168. package/dist/cli-bundle/chunks/chunk-7X6OZEIV.js +0 -34
  169. package/dist/cli-bundle/chunks/chunk-GNWPTEBW.js +0 -205
  170. package/dist/cli-bundle/chunks/chunk-N6OR6FAR.js +0 -13
  171. package/dist/cli-bundle/chunks/register-mutation-QBSNCOY3.js +0 -20
  172. package/dist/cli-bundle/chunks/register-operations-UC77FQZC.js +0 -2
  173. package/dist/cli-bundle/focused-chunks/chunk-3UMBF26I.js +0 -158
  174. package/dist/cli-bundle/focused-chunks/chunk-AXZ5AJAF.js +0 -50
  175. package/dist/cli-bundle/focused-chunks/chunk-G6PATS5E.js +0 -16
  176. package/dist/cli-bundle/focused-chunks/chunk-LLNTHF5X.js +0 -2
@@ -1,37 +1,37 @@
1
- import hs 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]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var wn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],mc=2,_c=Object.freeze({migration:"schema",validation:"schema"}),SO=Object.freeze({version:mc,capabilities:[...wn],legacy_aliases:{..._c}}),si=["off","warn","enforce"],ai=["off","warn","enforce"],ci=["none","restricted","strict"];var li=["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"],wr=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function vr(){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 gc=["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"],n_=["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",...gc,"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"],Te=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]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var di=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"]}]),ui=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Yt=".agents/pm",Er="settings.json";var r_=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],o_=["decisions","events","reminders","milestones","meetings","plans"],IO=[...r_,...o_],Se={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},fi={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}},pi=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],At={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 hc(e){return e?[...e]:void 0}var re={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:[...pi],lifecycle_closure_like_blocked_reason_patterns:[...At.blocked_reason],lifecycle_closure_like_resolution_patterns:[...At.resolution],lifecycle_closure_like_actual_result_patterns:[...At.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...fi.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:di.map(e=>({...e,aliases:hc(e.aliases),roles:hc(e.roles)})),fields:[],workflow:{...ui},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:vr()},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:""}}},mi={metadata:{},body:""},h={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},OO=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"});import{encode as cg}from"@toon-format/toon";import{isDeepStrictEqual as Bc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64223a83-1287-57ac-915d-dbd5e375a6eb")}catch{}})();var _i=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],yc=_i,Xt=["draft","open","in_progress","blocked","closed","canceled"],kr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Jt=["string","number","boolean","string_array","array","object"],Tr=["create","update","update_many","list","search","calendar","context"],Sr=["allow","warn","reject"];var gi=["project","global"];var Ar=["low","medium","high","critical"],xr=["low","medium","high"];var bc=["minimal","default","strict","custom"];var Cr=["daily","weekly","monthly","yearly"],vn=["mon","tue","wed","thu","fri","sat","sun"];function hi(e){return vn.indexOf(e)}var wc=["draft","research","review","approved","executing","paused","completed","superseded"],Ir=["pending","in_progress","completed","blocked","skipped","superseded"],vc=["codex","claude-code","cursor","generic"],Ec=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 y=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}};import i_ 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 s_(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 a_(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Or(o))}return n}function Or(e){let t=s_(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Or(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Or(r)}return a_(e)}function O(e){return JSON.stringify(Or(e))}function kc(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 c_(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function l_(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function d_(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(!kc(o,n,r,Ae))return!1;return!0}function u_(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(!kc([o,i],n,r,([a,c],[l,d])=>Ae(a,l)&&Ae(c,d)))return!1;return!0}function f_(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)=>Ae(n,t[r]))}function p_(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]||!Ae(e[i],t[i]))return!1}return!0}var m_=[c_,l_,d_,u_,f_];function Ae(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 m_){let r=n(e,t);if(r!==void 0)return r}return p_(e,t)}function ce(e){return i_.createHash("sha256").update(e,"utf8").digest("hex")}function st(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]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function Zt(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import{AsyncLocalStorage as __}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 g_=new __;function Tc(){let e=g_.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(){try{var e=typeof window<"u"?window:typeof 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 h_=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function q(){return Tc()??new Date().toISOString()}function Pe(e){return Number.isFinite(Date.parse(e))}function En(e){let t=h_.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,_,g]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=b_(d,u-1)&&p<=23&&_<=59&&g<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var y_=1e4,Rr=new Map;function Sc(e){let t=Rr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Rr.size>=y_&&Zt(Rr),Rr.set(e,n),n}function me(e,t){let n=Sc(e),r=Sc(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function b_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import Ac from"node:path";import*as te from"node:fs/promises";import Nr from"node:path";import w_ 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 v_=[10,25,50,100];async function at(e){await te.mkdir(e,{recursive:!0})}async function B(e){try{return await te.access(e),!0}catch{return!1}}function kn(e){return X(e)||xt(e,"ENOTDIR")}function X(e){return xt(e,"ENOENT")}async function J(e){try{return await te.readFile(e,"utf8")}catch(t){if(kn(t))return null;throw t}}async function $(e,t){let n=Nr.dirname(e);await at(n);let r=Nr.join(n,`.${Nr.basename(e)}.${process.pid}.${Date.now()}.${w_.randomBytes(4).toString("hex")}.tmp`);await te.writeFile(r,t,"utf8");try{await te.rename(r,e)}catch(o){if(process.platform==="win32"&&(xt(o,"EPERM")||xt(o,"EBUSY"))){let i=o;for(let s of v_){await new Promise(a=>setTimeout(a,s));try{await te.rename(r,e);return}catch(a){if(i=a,!xt(a,"EPERM")&&!xt(a,"EBUSY"))break}}try{await te.unlink(r)}catch{}throw i}if(xt(o,"EXDEV")){try{await te.copyFile(r,e)}finally{try{await te.unlink(r)}catch{}}return}try{await te.unlink(r)}catch{}throw o}}async function Qt(e,t){let n=Nr.dirname(e);await at(n);let r=await te.open(e,"a");try{await r.writeFile(`${t}
2
- `,"utf8")}finally{await r.close()}}function xt(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]="d6056922-237d-525a-b354-687493a4e123")}catch{}})();var E_=2e3,Dr=new Map;function Be(e){if(typeof e!="string")return"";let t=Dr.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Dr.size>=E_&&Zt(Dr),Dr.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]="88b9179f-569e-5cd6-b67c-c27431961554")}catch{}})();var _e=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Ic=ui,wi=di,k_=["create","update"],T_=new Set(kr),S_=new Set(Jt),A_=new Set(Tr),x_=new Set(Sr),C_=new Set(["string","number","boolean","array","object"]),I_=16;function Oc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var O_=[e=>e.type===void 0||typeof e.type=="string"&&C_.has(e.type),e=>!Object.hasOwn(e,"const")||Lr(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Lr(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||Oc(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Lr(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=>Lr(r,t)):Object.values(e).every(r=>Lr(r,t));return t.delete(e),n}function Pr(e,t=0,n=new Set){if(!Oc(e)||t>I_||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(!O_.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,I])=>[v,Pr(I,t+1,n)])),g=c===void 0?void 0:Pr(c,t+1,n),b=s===void 0?void 0:s.map(v=>Pr(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[g],...b??[]].some(v=>v===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:g,one_of:b}).filter(([,v])=>v!==void 0))}function Tn(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 Le(e){if(typeof e!="string"||e.length===0)return;let t=Be(e);return t.length>0?t:void 0}function R_(e){return e.startsWith("--")?e.slice(2):e}function xc(e){return typeof e=="string"?R_(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Rc(e){return e.replaceAll("_","-")}function bi(e,t){let n=Le(e.id);if(!n)return null;let r=[...new Set(Tn(e.aliases).map(Be).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=Tn(e.roles).filter(a=>T_.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 N_(e){return{draft_status:Le(e?.draft_status),open_status:Le(e?.open_status),in_progress_status:Le(e?.in_progress_status),blocked_status:Le(e?.blocked_status),close_status:Le(e?.close_status),canceled_status:Le(e?.canceled_status)}}function Nc(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Be(t[0]),r=Be(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function D_(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)Nc(n,r);return{typeKey:t.toLowerCase(),record:n}}function P_(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=D_(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)Nc(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 Dc(e){let t=Be(e.key??"");if(!t)return null;let n=Be(e.metadata_key??e.front_matter_key??t),r=xc(e.cli_flag??Rc(t));if(!r)return null;let o=Tn(e.cli_aliases).map(u=>xc(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=S_.has(i)?i:"string",a=(()=>{let u=Tn(e.commands).filter(f=>A_.has(f));return u.length>0?u:[...k_]})(),c=e.description?.trim(),l=Tn(e.required_types),d=e.value_schema===void 0?void 0:Pr(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 L_(e){let t=new Map;for(let[r,o]of e.entries()){let i=bi(o,r);i&&t.set(i.id,i)}let n=Cc([...t.values()]);return n.length>0?n:Cc(wi.map((r,o)=>bi(r,o)).filter(r=>r!==null))}function Cc(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function M_(e){let t=new Map;for(let n of e??[]){let r=Dc(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function F_(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 $_(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Rc(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 j_(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return x_.has(t)?t:"allow"}function ct(e){let t={..._e,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:wi,r=L_(n),o=M_(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(F_),fields:o.map($_),workflow:{...Ic,...N_(e?.workflow)},type_workflows:P_(e?.type_workflows),unknown_field_policy:j_(e?.unknown_field_policy)}}function U_(e){return`${JSON.stringify(e,null,2)}
3
- `}function z_(){return{definitions:[]}}function q_(){return{statuses:wi}}function B_(){return{fields:[]}}function G_(){return{workflow:Ic}}function H_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function V_(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 W_(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 K_(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 Y_(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 X_(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 ye(e,t,n){let r=t?.trim()||n;return Ac.isAbsolute(r)?r:Ac.join(e,r)}async function Pc(e,t){let n=ct(t),r=[{path:ye(e,n.files.types,_e.types),seed:z_()},{path:ye(e,n.files.statuses,_e.statuses),seed:q_()},{path:ye(e,n.files.fields,_e.fields),seed:B_()},{path:ye(e,n.files.workflows,_e.workflows),seed:G_()}],o=[];for(let i of r)await B(i.path)||(await $(i.path,U_(i.seed)),o.push(i.path));return{created_paths:o}}async function Lc(e,t){let n=ct(t),r=[],o=ye(e,n.files.types,_e.types),i=ye(e,n.files.statuses,_e.statuses),s=ye(e,n.files.fields,_e.fields),a=ye(e,n.files.workflows,_e.workflows),c,l,d,u,f,p=async(I,T)=>{let A=await J(I);if(A!==null)return H_(A,T,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=V_(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let g=await p(i,"runtime_schema_statuses_invalid_json");g!==void 0&&(l=W_(g),l===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await p(s,"runtime_schema_fields_invalid_json");b!==void 0&&(d=K_(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=Y_(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=X_(E)),{schema:ct({...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 yi(e,t,n){let r=e.filter(i=>i.roles.includes(t));if(r.length>0)return r[0].id;let o=n.map(i=>Le(i)).filter(i=>typeof i=="string");for(let i of o)if(e.some(s=>s.id===i))return i;return e[0]?.id}function Sn(e){let t=ct(e),n=t.statuses.map((g,b)=>bi(g,b)).filter(g=>g!==null),r=new Map,o=new Map;for(let g of n){o.set(g.id,g),r.set(g.id,g.id),r.set(g.id.replaceAll("_","-"),g.id),r.set(g.id.replaceAll("_"," "),g.id);for(let b of g.aliases)r.set(b,g.id),r.set(b.replaceAll("_","-"),g.id),r.set(b.replaceAll("_"," "),g.id)}let i=new Set,s=new Set,a=new Set,c=new Set,l=new Set,d=new Set;for(let g of n){let b=new Set(g.roles);(b.has("terminal")||b.has("terminal_done")||b.has("terminal_canceled"))&&i.add(g.id),b.has("terminal_done")&&s.add(g.id),b.has("terminal_canceled")&&a.add(g.id),b.has("active")&&c.add(g.id),b.has("blocked")&&l.add(g.id),b.has("draft")&&d.add(g.id)}let u=t.workflow,f=Le(u.open_status)??yi(n,"default_open",["open","in_progress",Xt[0]]),p=Le(u.close_status)??yi(n,"default_close",["closed","done","complete"]),_=Le(u.canceled_status)??yi(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:i,terminal_done_statuses:s,terminal_canceled_statuses:a,active_statuses:c,blocked_statuses:l,draft_statuses:d,open_status:f,close_status:p,canceled_status:_}}function Mr(e,t){let n=Be(e);if(n)return t.alias_to_id.get(n)}function vi(e){let t=ct(e),n=new Map,r=t.fields.map(c=>Dc(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 Ei(e,t){let n=Mr(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 J_=16;function $c(e){return Array.isArray(e)?e.flatMap(t=>$c(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 Mc(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 y(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Fc(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 y(`${t} must be a number`,h.USAGE);return r}function Z_(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 y(`${t} must be valid JSON ${n}`,h.USAGE)}function Q_(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 eg(e,t,n){if(t.const!==void 0&&O(e)!==O(t.const))return`${n} must equal ${O(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>O(r)===O(e)))return`${n} must be one of ${t.enum.map(r=>O(r)).join("|")}`;if(!Q_(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"&&!En(e))return`${n} must be an RFC 3339 date-time`}}function tg(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=Fr(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function ng(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=Fr(s,a,`${n}.${i}`,r+1);if(c)return c}}function Fr(e,t,n,r=0){if(r>J_)return`${n} value schema exceeds maximum depth`;let o=eg(e,t,n);if(o)return o;let i=tg(e,t,n,r);if(i)return i;let s=ng(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Fr(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 Ct(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Fr(t,e.value_schema,n);if(r)throw new y(r,h.USAGE);return t}function $r(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:Ct(e,Z_(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=$c(t);return e.type==="number"?Ct(e,i.map(s=>Fc(s,r)),r):e.type==="boolean"?Ct(e,i.map(s=>Mc(s,r)),r):Ct(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?Ct(e,Fc(o,r),r):e.type==="boolean"?Ct(e,Mc(o,r),r):Ct(e,typeof o=="string"?o:String(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]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var en=1,jr=1;function jc(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=en?t:en}function Uc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=en))return e}function rg(e,t=jr){return e<t?"outdated":e>t?"ahead":"current"}function zc(e,t=jr){let n=[],r=[];for(let o of e){let i=rg(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 og={"in-progress":"in_progress",cancelled:"canceled"};function It(e,t){if(t){let o=Mr(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=og[n]??n;if(Xt.includes(r))return r}import{decode as ig}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 ki(e){return{value:ig(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 sg=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function ag(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(sg);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Me(e){return ag(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]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function An(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function fe(e){return An(e)??void 0}function Xe(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function qc(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(){try{var e=typeof window<"u"?window:typeof 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 xi=new Set(["schema","tracker","auto"]),Vc=new Set(["source","isolated","snapshot"]),lg=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),dg=new Set(["passed","failed","stopped","canceled"]),ug=new Set(Ir);function rn(e){return e.replaceAll("\\","/")}function Wc(e){for(let t of e)if(t!==0)return t;return 0}function zr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Kc=["id","title","description","created_at","updated_at"],fg=new Set(Te);function Yc(e){if(e?.schema)return{statusRegistry:Sn(e.schema),fieldRegistry:vi(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function pg(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function lt(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new y(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function In(e,t){throw new y(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Xc(e){let t=new Set(fg);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||lt(t)}function On(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&lt(t),e}function Ti(e,t){let n=e[t];C(typeof n=="string",`${t} must be a string`),C(Pe(n),`${t} must be a valid ISO timestamp`)}function Gc(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 Ci(e,t,n){let r=e[t];r!==void 0&&(C(typeof r=="string",`${n} must be a string`),C(Pe(r),`${n} must be a valid ISO timestamp`))}function mg(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(vn.includes(n),`event.recurrence.by_weekday entries must be one of: ${vn.join(", ")}`)}}}function _g(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 gg(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(Pe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function hg(e){let t=On(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(Cr.includes(n),`event.recurrence.freq must be one of: ${Cr.join(", ")}`),Gc(t,"interval","event.recurrence.interval"),Gc(t,"count","event.recurrence.count"),Ci(t,"until","event.recurrence.until"),mg(t.by_weekday),_g(t.by_month_day),gg(t.exdates)}function yg(e){for(let r of Kc)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>=en,`pm_format_version must be an integer >= ${en}`),t}function bg(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=It(n,r),i=r?r.definitions.map(s=>s.id):[...Xt];C(o!==void 0,`status must be one of: ${i.join(", ")}`)}function wg(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 vg(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"||xr.includes(n);C(r,`confidence string value must be one of: ${[...xr,"med"].join(", ")}`);return}C(!1,"confidence must be a number or string")}}function Eg(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&lt("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Ar.includes(n);C(r,`severity value must be one of: ${[...Ar,"med"].join(", ")}`)}function kg(e){e.regression!==void 0&&typeof e.regression!="boolean"&&lt("regression must be a boolean")}function Tg(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=On(n,"reminders entries must be objects");C(typeof r.at=="string","reminder.at must be a string"),C(Pe(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 Sg(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 Ag(e){e.recurrence!==void 0&&(hg(e.recurrence),e.recurrence.until!==void 0&&C(me(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function xg(e){let t=On(e,"events entries must be objects");C(typeof t.start_at=="string","event.start_at must be a string"),C(Pe(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(Pe(t.end_at),"event.end_at must be a valid ISO timestamp"),C(me(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Sg(t),t.all_day!==void 0&&C(typeof t.all_day=="boolean","event.all_day must be a boolean"),Ag(t)}function Cg(e){let t=e.events;if(t!==void 0){C(Array.isArray(t),"events must be an array");for(let n of t)xg(n)}}function Ig(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 Og(e){let t=e.type_options;if(t===void 0)return;let n=On(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 Rg(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){pg(r,t)&&lt(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=$r(r,o,`metadata field "${r.metadata_key}"`)}catch(i){lt(String(i?.message).replace(/^Invalid\s+/u,""))}}}function Ng(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Xc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?lt(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ii(e,t){let n=On(e,"item metadata must be an object"),r=yg(n);bg(n,t),wg(n),vg(n),Eg(n),kg(n),Ti(n,"created_at"),Ti(n,"updated_at"),n.deadline!==void 0&&Ti(n,"deadline"),Tg(n),Cg(n),Ci(n,"closed_at","closed_at"),Ci(n,"completed_at","completed_at"),Ig(n),Og(n),Rg(n,r,t),Ng(n,t)}function Dg(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=me(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 Si(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=me(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 Pg(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=me(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function Lg(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Cr.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>vn.includes(s)))).sort((s,a)=>hi(s)-hi(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=>Pe(s)))).sort((s,a)=>me(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 Mg(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(Fg).sort($g)}function Fg(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:Lg(e.recurrence)};return zr(t),t}function $g(e,t){return Wc([me(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 jg(e){if(!(!e||e.length===0))return e.map(t=>({path:rn(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Ug(e){if(!e||e.length===0)return;let t=e.map(Gg).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)=>Wc([me(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 tn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function zg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ai(e){return typeof e=="string"?e:""}function qg(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 Ur(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function Bg(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:Ur(n.requested_pm_context_mode,xi),pm_context_mode:Ur(n.pm_context_mode,xi),workspace_context_mode:Ur(n.workspace_context_mode,Vc),trust_reason:Ur(n.trust_reason,lg)}));return t.length>0?t:void 0}function Gg(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=dg.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ai(e.started_at),finished_at:Ai(e.finished_at),recorded_at:Ai(e.recorded_at),attempt:zg(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:tn(e.passed)??0,failed:tn(e.failed)??0,skipped:tn(e.skipped)??0,items:tn(e.items),linked_tests:tn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:qg(e.measurements),executions:Bg(e.executions)};return zr(o),o}function Hg(e){if(!(!Array.isArray(e)||e.length===0))return e.map(Xg)}function xn(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 Ri(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ni(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Hc(e){if(!Ri(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Ni(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Vg(e){if(!Ri(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Ni(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Wg(e){let t=e?.trim().toLowerCase();if(!(!t||!xi.has(t)))return t}function Kg(e){let t=e?.trim().toLowerCase();if(!(!t||!Vc.has(t)))return t}function Yg(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ri(e))return{provenance_invalid:!0};let n=x(e.author),r=x(e.created_at),o=e.source_kind;return!n||!r||!Pe(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:x(e.source_ref)}}}function Xg(e){let t={command:e.command?.trim()||void 0,path:e.path?rn(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:Wg(e.pm_context_mode),workspace_context_mode:Kg(e.workspace_context_mode),...Yg(e.provenance,e.provenance_invalid),env_set:Hc(e.env_set),env_clear:xn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:xn(e.assert_stdout_contains),assert_stdout_regex:xn(e.assert_stdout_regex),assert_stderr_contains:xn(e.assert_stderr_contains),assert_stderr_regex:xn(e.assert_stderr_regex),assert_stdout_min_lines:tn(e.assert_stdout_min_lines),assert_json_field_equals:Hc(e.assert_json_field_equals),assert_json_field_gte:Vg(e.assert_json_field_gte),note:e.note?.trim()||void 0};return zr(t),t}function Jg(e){if(!(!e||e.length===0))return[...e].map(t=>({path:rn(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 x(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function Zg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.id),i=x(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=x(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 Qg(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:rn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function eh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.command),i=x(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=rn(i));let a=x(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function th(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:rn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function nh(e){if(e===null||typeof e!="object")return;let t=e,n=x(t.id),r=x(t.title),o=x(t.status),i=o&&ug.has(o)?o:void 0,s=qc(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 rh(l,t),l}function rh(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=x(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",Zg],["files","files",Qg],["tests","tests",eh],["docs","docs",th]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function oh(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=nh(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function ih(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=x(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=x(r.rationale);c&&(a.rationale=c);let l=x(r.evidence);l&&(a.evidence=l);let d=x(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function sh(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=x(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=x(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function ah(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.text);if(!o)continue;let i={text:o},s=x(r.command);s&&(i.command=s);let a=x(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function ch(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 nn(e){let t=0;for(;t<e.length&&e[t]===`
4
- `;)t+=1;return e.slice(t).trimEnd()}function lh(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(xr.includes(t))return t}function dh(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ar.includes(t))return t}function Cn(e){return e||void 0}function uh(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Ni(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function fh(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]=$r(r,o,`metadata field "${r.metadata_key}"`))}}function ph(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Xc(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&lt(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function Rn(e,t={}){let n=Yc(t),r=It(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:Uc(e.pm_format_version),source_type:x(e.source_type),type_options:ch(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Dg(e.dependencies),comments:Si(e.comments),notes:Si(e.notes),learnings:Si(e.learnings),files:jg(e.files),tests:Hg(e.tests),test_runs:Ug(e.test_runs),docs:Jg(e.docs),deadline:Cn(e.deadline),reminders:Pg(e.reminders),events:Mg(e.events),closed_at:Cn(e.closed_at),completed_at:Cn(e.completed_at),assignee:x(e.assignee),claim_principal:x(e.claim_principal),source_owner:x(e.source_owner),author:Cn(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:x(e.definition_of_ready),order:e.order,goal:x(e.goal),objective:x(e.objective),value:x(e.value),impact:x(e.impact),outcome:x(e.outcome),why_now:x(e.why_now),parent:x(e.parent),reviewer:x(e.reviewer),risk:e.risk??void 0,confidence:lh(e.confidence),sprint:x(e.sprint),release:x(e.release),blocked_by:x(e.blocked_by),blocked_reason:x(e.blocked_reason),unblock_note:x(e.unblock_note),reporter:x(e.reporter),severity:dh(e.severity),environment:x(e.environment),repro_steps:x(e.repro_steps),resolution:x(e.resolution),expected_result:x(e.expected_result),actual_result:x(e.actual_result),affected_version:x(e.affected_version),fixed_version:x(e.fixed_version),component:x(e.component),regression:e.regression,customer_impact:x(e.customer_impact),close_reason:Cn(e.close_reason),plan_mode:x(e.plan_mode),plan_scope:x(e.plan_scope),plan_harness:x(e.plan_harness),plan_resume_context:x(e.plan_resume_context),plan_steps:oh(e.plan_steps),plan_decisions:ih(e.plan_decisions),plan_discoveries:sh(e.plan_discoveries),plan_validation:ah(e.plan_validation)};return uh(i,e),fh(i,n),ph(i,n),zr(i),i}function Jc(e){return st(e,Te)}function mh(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 _h(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=mh(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 gh(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(`
5
- `,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 Oi(e,t){return Rn(e,{...t,onWarning:void 0})}function hh(e,t,n={}){let r=gh(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=_h(r.content);o||(e.trimStart().startsWith("{")&&In("json_markdown","JSON front matter is not valid JSON"),In("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{In("json_markdown","JSON front matter is not valid JSON")}return Ii(s,t),{metadata:Oi(s,n),body:nn(i)}}function yh(e,t,n={}){let r;try{r=ki(e).value}catch{In("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(!Kc.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&In("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ii(o.front_matter,t),C(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Oi(o.front_matter,n),body:nn(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"),Ii(s,t),{metadata:Oi(s,n),body:nn(typeof i=="string"?i:"")}}function bh(e,t={}){let n=Rn(e.metadata,t),r=Jc(n),o=JSON.stringify(r,null,2),i=nn(e.body??"");return i?`${o}
1
+ import ys 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]="ef5c8553-c206-5bb5-913a-85afb936f6d7")}catch{}})();var Tn=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],_c=2,gc=Object.freeze({migration:"schema",validation:"schema"}),PO=Object.freeze({version:_c,capabilities:[...Tn],legacy_aliases:{...gc}}),li=["off","warn","enforce"],di=["off","warn","enforce"],ui=["none","restricted","strict"];var fi=["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"],Er=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function kr(){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 hc=["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"],a_=["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",...hc,"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"],Se=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]="4bb01c24-e203-5f9f-ba23-25888bd7f6ea")}catch{}})();var pi=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"]}]),mi=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Xt=".agents/pm",Tr="settings.json";var c_=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],l_=["decisions","events","reminders","milestones","meetings","plans"],$O=[...c_,...l_],Ae={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},_i={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}},gi=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],Ot={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 yc(e){return e?[...e]:void 0}var oe={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:[...gi],lifecycle_closure_like_blocked_reason_patterns:[...Ot.blocked_reason],lifecycle_closure_like_resolution_patterns:[...Ot.resolution],lifecycle_closure_like_actual_result_patterns:[...Ot.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",..._i.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:pi.map(e=>({...e,aliases:yc(e.aliases),roles:yc(e.roles)})),fields:[],workflow:{...mi},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:kr()},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:""}}},hi={metadata:{},body:""},g={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},jO=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"});import{encode as _g}from"@toon-format/toon";import{isDeepStrictEqual as Gc}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="64223a83-1287-57ac-915d-dbd5e375a6eb")}catch{}})();var yi=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],bc=yi,Jt=["draft","open","in_progress","blocked","closed","canceled"],Sr=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Zt=["string","number","boolean","string_array","array","object"],Ar=["create","update","update_many","list","search","calendar","context"],xr=["allow","warn","reject"];var bi=["project","global"];var Cr=["low","medium","high","critical"],Ir=["low","medium","high"];var wc=["minimal","default","strict","custom"];var Or=["daily","weekly","monthly","yearly"],Sn=["mon","tue","wed","thu","fri","sat","sun"];function wi(e){return Sn.indexOf(e)}var vc=["draft","research","review","approved","executing","paused","completed","superseded"],Rr=["pending","in_progress","completed","blocked","skipped","superseded"],Ec=["codex","claude-code","cursor","generic"],kc=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"];(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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}};import d_ 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 u_(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 f_(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=Nr(o))}return n}function Nr(e){let t=u_(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>Nr(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return Nr(r)}return f_(e)}function R(e){return JSON.stringify(Nr(e))}function Tc(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 p_(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function m_(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function __(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(!Tc(o,n,r,xe))return!1;return!0}function g_(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(!Tc([o,i],n,r,([a,c],[l,d])=>xe(a,l)&&xe(c,d)))return!1;return!0}function h_(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)=>xe(n,t[r]))}function y_(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]||!xe(e[i],t[i]))return!1}return!0}var b_=[p_,m_,__,g_,h_];function xe(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 b_){let r=n(e,t);if(r!==void 0)return r}return y_(e,t)}function ae(e){return d_.createHash("sha256").update(e,"utf8").digest("hex")}function lt(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]="b2649352-0afa-5972-8c48-b999f86d5522")}catch{}})();function Qt(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import{AsyncLocalStorage as w_}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 v_=new w_;function Sc(){let e=v_.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(){try{var e=typeof window<"u"?window:typeof 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 E_=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function q(){return Sc()??new Date().toISOString()}function Pe(e){return Number.isFinite(Date.parse(e))}function An(e){let t=E_.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<=T_(d,u-1)&&p<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(l===void 0||Number(l)<=59)}var k_=1e4,Dr=new Map;function Ac(e){let t=Dr.get(e);if(t!==void 0)return t;let n=Date.parse(e);return Dr.size>=k_&&Qt(Dr),Dr.set(e,n),n}function me(e,t){let n=Ac(e),r=Ac(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function T_(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}import xc from"node:path";import*as ne from"node:fs/promises";import Pr from"node:path";import S_ 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 A_=[10,25,50,100];async function dt(e){await ne.mkdir(e,{recursive:!0})}async function B(e){try{return await ne.access(e),!0}catch{return!1}}function xn(e){return K(e)||Rt(e,"ENOTDIR")}function K(e){return Rt(e,"ENOENT")}async function Q(e){try{return await ne.readFile(e,"utf8")}catch(t){if(xn(t))return null;throw t}}async function j(e,t){let n=Pr.dirname(e);await dt(n);let r=Pr.join(n,`.${Pr.basename(e)}.${process.pid}.${Date.now()}.${S_.randomBytes(4).toString("hex")}.tmp`);await ne.writeFile(r,t,"utf8");try{await ne.rename(r,e)}catch(o){if(process.platform==="win32"&&(Rt(o,"EPERM")||Rt(o,"EBUSY"))){let i=o;for(let s of A_){await new Promise(a=>setTimeout(a,s));try{await ne.rename(r,e);return}catch(a){if(i=a,!Rt(a,"EPERM")&&!Rt(a,"EBUSY"))break}}try{await ne.unlink(r)}catch{}throw i}if(Rt(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 en(e,t){let n=Pr.dirname(e);await dt(n);let r=await ne.open(e,"a");try{await r.writeFile(`${t}
2
+ `,"utf8")}finally{await r.close()}}function Rt(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]="d6056922-237d-525a-b354-687493a4e123")}catch{}})();var x_=2e3,Lr=new Map;function qe(e){if(typeof e!="string")return"";let t=Lr.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Lr.size>=x_&&Qt(Lr),Lr.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 _e=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Oc=mi,Ei=pi,C_=["create","update"],I_=new Set(Sr),O_=new Set(Zt),R_=new Set(Ar),N_=new Set(xr),D_=new Set(["string","number","boolean","array","object"]),P_=16;function Rc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var L_=[e=>e.type===void 0||typeof e.type=="string"&&D_.has(e.type),e=>!Object.hasOwn(e,"const")||Fr(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Fr(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||Rc(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Fr(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=>Fr(r,t)):Object.values(e).every(r=>Fr(r,t));return t.delete(e),n}function Mr(e,t=0,n=new Set){if(!Rc(e)||t>P_||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(!L_.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,C])=>[v,Mr(C,t+1,n)])),y=c===void 0?void 0:Mr(c,t+1,n),b=s===void 0?void 0:s.map(v=>Mr(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...b??[]].some(v=>v===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(([,v])=>v!==void 0))}function In(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 ye(e){if(typeof e!="string"||e.length===0)return;let t=qe(e);return t.length>0?t:void 0}function M_(e){return e.startsWith("--")?e.slice(2):e}function Cc(e){return typeof e=="string"?M_(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Nc(e){return e.replaceAll("_","-")}function vi(e,t){let n=ye(e.id);if(!n)return null;let r=[...new Set(In(e.aliases).map(qe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=In(e.roles).filter(a=>I_.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 F_(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function Dc(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=qe(t[0]),r=qe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function $_(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)Dc(n,r);return{typeKey:t.toLowerCase(),record:n}}function j_(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=$_(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)Dc(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 Pc(e){let t=qe(e.key??"");if(!t)return null;let n=qe(e.metadata_key??e.front_matter_key??t),r=Cc(e.cli_flag??Nc(t));if(!r)return null;let o=In(e.cli_aliases).map(u=>Cc(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=O_.has(i)?i:"string",a=(()=>{let u=In(e.commands).filter(f=>R_.has(f));return u.length>0?u:[...C_]})(),c=e.description?.trim(),l=In(e.required_types),d=e.value_schema===void 0?void 0:Mr(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 U_(e){let t=new Map;for(let[r,o]of e.entries()){let i=vi(o,r);i&&t.set(i.id,i)}let n=Ic([...t.values()]);return n.length>0?n:Ic(Ei.map((r,o)=>vi(r,o)).filter(r=>r!==null))}function Ic(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function z_(e){let t=new Map;for(let n of e??[]){let r=Pc(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function q_(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 B_(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Nc(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 G_(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return N_.has(t)?t:"allow"}function ut(e){let t={..._e,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:Ei,r=U_(n),o=z_(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(q_),fields:o.map(B_),workflow:{...Oc,...F_(e?.workflow)},type_workflows:j_(e?.type_workflows),unknown_field_policy:G_(e?.unknown_field_policy)}}function H_(e){return`${JSON.stringify(e,null,2)}
3
+ `}function V_(){return{definitions:[]}}function W_(){return{statuses:Ei}}function K_(){return{fields:[]}}function Y_(){return{workflow:Oc}}function X_(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function J_(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 Z_(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 Q_(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 eg(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 tg(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 be(e,t,n){let r=t?.trim()||n;return xc.isAbsolute(r)?r:xc.join(e,r)}async function Lc(e,t){let n=ut(t),r=[{path:be(e,n.files.types,_e.types),seed:V_()},{path:be(e,n.files.statuses,_e.statuses),seed:W_()},{path:be(e,n.files.fields,_e.fields),seed:K_()},{path:be(e,n.files.workflows,_e.workflows),seed:Y_()}],o=[];for(let i of r)await B(i.path)||(await j(i.path,H_(i.seed)),o.push(i.path));return{created_paths:o}}async function Mc(e,t){let n=ut(t),r=[],o=be(e,n.files.types,_e.types),i=be(e,n.files.statuses,_e.statuses),s=be(e,n.files.fields,_e.fields),a=be(e,n.files.workflows,_e.workflows),c,l,d,u,f,p=async(C,k)=>{let S=await Q(C);if(S!==null)return X_(S,k,r)},_=await p(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=J_(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await p(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(l=Z_(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=Q_(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=eg(E),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=tg(E)),{schema:ut({...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 Cn(e,t,n,r=!1){let i=n.map(a=>ye(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 ng(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 rg(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 On(e){let t=ut(e),n=t.statuses.map((E,v)=>vi(E,v)).filter(E=>E!==null),{aliasToId:r,byId:o}=ng(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:l,terminalStatuses:d}=rg(n),u=t.workflow,f=ye(u.open_status)??Cn(n,"default_open",["open","in_progress",Jt[0]]),p=ye(u.in_progress_status)??Cn(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??Cn(n,"blocked",["blocked"]),y=ye(u.close_status)??Cn(n,"default_close",["closed","done","complete"]),b=ye(u.canceled_status)??Cn(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 tn(e,t){let n=qe(e);if(n)return t.alias_to_id.get(n)}function ki(e){let t=ut(e),n=new Map,r=t.fields.map(c=>Pc(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 Ti(e,t){let n=tn(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 og=16;function jc(e){return Array.isArray(e)?e.flatMap(t=>jc(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 Fc(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 $c(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 ig(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 sg(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 ag(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!sg(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"&&!An(e))return`${n} must be an RFC 3339 date-time`}}function cg(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=$r(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function lg(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=$r(s,a,`${n}.${i}`,r+1);if(c)return c}}function $r(e,t,n,r=0){if(r>og)return`${n} value schema exceeds maximum depth`;let o=ag(e,t,n);if(o)return o;let i=cg(e,t,n,r);if(i)return i;let s=lg(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if($r(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 Nt(e,t,n){if(!e.value_schema||t===void 0)return t;let r=$r(t,e.value_schema,n);if(r)throw new h(r,g.USAGE);return t}function jr(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:Nt(e,ig(i,r,e.type),r)}if(e.repeatable||e.type==="string_array"){let i=jc(t);return e.type==="number"?Nt(e,i.map(s=>$c(s,r)),r):e.type==="boolean"?Nt(e,i.map(s=>Fc(s,r)),r):Nt(e,i,r)}let o=Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return e.type==="number"?Nt(e,$c(o,r),r):e.type==="boolean"?Nt(e,Fc(o,r),r):Nt(e,typeof o=="string"?o:String(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]="77d3ebfa-789a-54cf-9d49-dbebab8d32ea")}catch{}})();var nn=1,Ur=1;function Uc(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=nn?t:nn}function zc(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=nn))return e}function dg(e,t=Ur){return e<t?"outdated":e>t?"ahead":"current"}function qc(e,t=Ur){let n=[],r=[];for(let o of e){let i=dg(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 ug={"in-progress":"in_progress",cancelled:"canceled"};function Dt(e,t){if(t){let o=tn(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=ug[n]??n;if(Jt.includes(r))return r}import{decode as fg}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 Si(e){return{value:fg(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 pg=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function mg(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(pg);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Le(e){return mg(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]="c29511ab-8c01-57f2-b353-cbc72900cb90")}catch{}})();function Rn(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function de(e){return Rn(e)??void 0}function Je(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function Bc(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(){try{var e=typeof window<"u"?window:typeof 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 Ii=new Set(["schema","tracker","auto"]),Wc=new Set(["source","isolated","snapshot"]),gg=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),hg=new Set(["passed","failed","stopped","canceled"]),yg=new Set(Rr);function sn(e){return e.replaceAll("\\","/")}function Kc(e){for(let t of e)if(t!==0)return t;return 0}function qr(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Yc=["id","title","description","created_at","updated_at"],bg=new Set(Se);function Xc(e){if(e?.schema)return{statusRegistry:On(e.schema),fieldRegistry:ki(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function wg(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function ft(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 Pn(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 Jc(e){let t=new Set(bg);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function I(e,t){e||ft(t)}function Ln(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&ft(t),e}function Ai(e,t){let n=e[t];I(typeof n=="string",`${t} must be a string`),I(Pe(n),`${t} must be a valid ISO timestamp`)}function Hc(e,t,n){let r=e[t];r!==void 0&&I(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Oi(e,t,n){let r=e[t];r!==void 0&&(I(typeof r=="string",`${n} must be a string`),I(Pe(r),`${n} must be a valid ISO timestamp`))}function vg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){I(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();I(Sn.includes(n),`event.recurrence.by_weekday entries must be one of: ${Sn.join(", ")}`)}}}function Eg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)I(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function kg(e){if(e!==void 0){I(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)I(typeof t=="string","event.recurrence.exdates entries must be strings"),I(Pe(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function Tg(e){let t=Ln(e,"event.recurrence must be an object");I(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();I(Or.includes(n),`event.recurrence.freq must be one of: ${Or.join(", ")}`),Hc(t,"interval","event.recurrence.interval"),Hc(t,"count","event.recurrence.count"),Oi(t,"until","event.recurrence.until"),vg(t.by_weekday),Eg(t.by_month_day),kg(t.exdates)}function Sg(e){for(let r of Yc)I(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;I(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&I(typeof n=="number"&&Number.isInteger(n)&&n>=nn,`pm_format_version must be an integer >= ${nn}`),t}function Ag(e,t){let n=e.status;I(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Dt(n,r),i=r?r.definitions.map(s=>s.id):[...Jt];I(o!==void 0,`status must be one of: ${i.join(", ")}`)}function xg(e){let t=e.priority;I(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;I(Array.isArray(n),"tags must be an array");for(let r of n)I(typeof r=="string","tags entries must be strings")}function Cg(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){I(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"||Ir.includes(n);I(r,`confidence string value must be one of: ${[...Ir,"med"].join(", ")}`);return}I(!1,"confidence must be a number or string")}}function Ig(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&ft("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||Cr.includes(n);I(r,`severity value must be one of: ${[...Cr,"med"].join(", ")}`)}function Og(e){e.regression!==void 0&&typeof e.regression!="boolean"&&ft("regression must be a boolean")}function Rg(e){let t=e.reminders;if(t!==void 0){I(Array.isArray(t),"reminders must be an array");for(let n of t){let r=Ln(n,"reminders entries must be objects");I(typeof r.at=="string","reminder.at must be a string"),I(Pe(r.at),"reminder.at must be a valid ISO timestamp"),I(typeof r.text=="string","reminder.text must be a string"),I(r.text.trim().length>0,"reminder.text must not be empty")}}}function Ng(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(I(typeof e[t]=="string",`event.${t} must be a string`),I(e[t].trim().length>0,`event.${t} must not be empty`))}function Dg(e){e.recurrence!==void 0&&(Tg(e.recurrence),e.recurrence.until!==void 0&&I(me(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function Pg(e){let t=Ln(e,"events entries must be objects");I(typeof t.start_at=="string","event.start_at must be a string"),I(Pe(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(I(typeof t.end_at=="string","event.end_at must be a string"),I(Pe(t.end_at),"event.end_at must be a valid ISO timestamp"),I(me(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),Ng(t),t.all_day!==void 0&&I(typeof t.all_day=="boolean","event.all_day must be a boolean"),Dg(t)}function Lg(e){let t=e.events;if(t!==void 0){I(Array.isArray(t),"events must be an array");for(let n of t)Pg(n)}}function Mg(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&I(typeof n=="string",`${t} must be a string`)}}function Fg(e){let t=e.type_options;if(t===void 0)return;let n=Ln(t,"type_options must be an object");for(let[r,o]of Object.entries(n))I(r.trim().length>0,"type_options keys must be non-empty"),I(typeof o=="string","type_options values must be strings"),I(o.trim().length>0,"type_options values must be non-empty strings")}function $g(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){wg(r,t)&&ft(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=jr(r,o,`metadata field "${r.metadata_key}"`)}catch(i){ft(String(i?.message).replace(/^Invalid\s+/u,""))}}}function jg(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Jc(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?ft(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ri(e,t){let n=Ln(e,"item metadata must be an object"),r=Sg(n);Ag(n,t),xg(n),Cg(n),Ig(n),Og(n),Ai(n,"created_at"),Ai(n,"updated_at"),n.deadline!==void 0&&Ai(n,"deadline"),Rg(n),Lg(n),Oi(n,"closed_at","closed_at"),Oi(n,"completed_at","completed_at"),Mg(n),Fg(n),$g(n,r,t),jg(n,t)}function Ug(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=me(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 xi(e){if(!(!e||e.length===0))return[...e].sort((t,n)=>{let r=me(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 zg(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=me(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function qg(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!Or.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Sn.includes(s)))).sort((s,a)=>wi(s)-wi(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=>Pe(s)))).sort((s,a)=>me(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 Bg(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(Gg).sort(Hg)}function Gg(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:qg(e.recurrence)};return qr(t),t}function Hg(e,t){return Kc([me(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 Vg(e){if(!(!e||e.length===0))return e.map(t=>({path:sn(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function Wg(e){if(!e||e.length===0)return;let t=e.map(Jg).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)=>Kc([me(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 rn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function Kg(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ci(e){return typeof e=="string"?e:""}function Yg(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 zr(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function Xg(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:zr(n.requested_pm_context_mode,Ii),pm_context_mode:zr(n.pm_context_mode,Ii),workspace_context_mode:zr(n.workspace_context_mode,Wc),trust_reason:zr(n.trust_reason,gg)}));return t.length>0?t:void 0}function Jg(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=hg.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ci(e.started_at),finished_at:Ci(e.finished_at),recorded_at:Ci(e.recorded_at),attempt:Kg(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:rn(e.passed)??0,failed:rn(e.failed)??0,skipped:rn(e.skipped)??0,items:rn(e.items),linked_tests:rn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:Yg(e.measurements),executions:Xg(e.executions)};return qr(o),o}function Zg(e){if(!(!Array.isArray(e)||e.length===0))return e.map(rh)}function Nn(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Di(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Pi(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Vc(e){if(!Di(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Pi(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function Qg(e){if(!Di(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Pi(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function eh(e){let t=e?.trim().toLowerCase();if(!(!t||!Ii.has(t)))return t}function th(e){let t=e?.trim().toLowerCase();if(!(!t||!Wc.has(t)))return t}function nh(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Di(e))return{provenance_invalid:!0};let n=x(e.author),r=x(e.created_at),o=e.source_kind;return!n||!r||!Pe(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:x(e.source_ref)}}}function rh(e){let t={command:e.command?.trim()||void 0,path:e.path?sn(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:eh(e.pm_context_mode),workspace_context_mode:th(e.workspace_context_mode),...nh(e.provenance,e.provenance_invalid),env_set:Vc(e.env_set),env_clear:Nn(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:Nn(e.assert_stdout_contains),assert_stdout_regex:Nn(e.assert_stdout_regex),assert_stderr_contains:Nn(e.assert_stderr_contains),assert_stderr_regex:Nn(e.assert_stderr_regex),assert_stdout_min_lines:rn(e.assert_stdout_min_lines),assert_json_field_equals:Vc(e.assert_json_field_equals),assert_json_field_gte:Qg(e.assert_json_field_gte),note:e.note?.trim()||void 0};return qr(t),t}function oh(e){if(!(!e||e.length===0))return[...e].map(t=>({path:sn(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 x(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function ih(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.id),i=x(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=x(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 sh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function ah(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.command),i=x(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=sn(i));let a=x(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function ch(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.path);if(!o)continue;let i={path:sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=x(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function lh(e){if(e===null||typeof e!="object")return;let t=e,n=x(t.id),r=x(t.title),o=x(t.status),i=o&&yg.has(o)?o:void 0,s=Bc(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 dh(l,t),l}function dh(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=x(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",ih],["files","files",sh],["tests","tests",ah],["docs","docs",ch]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function uh(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=lh(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function fh(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=x(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=x(r.rationale);c&&(a.rationale=c);let l=x(r.evidence);l&&(a.evidence=l);let d=x(r.step_id);d&&(a.step_id=d),t.push(a)}return t.length>0?t:void 0}function ph(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=x(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=x(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function mh(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=x(r.text);if(!o)continue;let i={text:o},s=x(r.command);s&&(i.command=s);let a=x(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function _h(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 on(e){let t=0;for(;t<e.length&&e[t]===`
4
+ `;)t+=1;return e.slice(t).trimEnd()}function gh(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Ir.includes(t))return t}function hh(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(Cr.includes(t))return t}function Dn(e){return e||void 0}function yh(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Pi(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function bh(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]=jr(r,o,`metadata field "${r.metadata_key}"`))}}function wh(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Jc(t),o=Object.keys(e).filter(i=>!n.has(i)).sort((i,s)=>i.localeCompare(s));o.length>0&&t.unknownFieldPolicy==="reject"&&ft(`unknown schema fields are not allowed: ${o.join(", ")}`),o.length>0&&t.onWarning?.(`item_unknown_schema_fields:${o.join(",")}`)}function Mn(e,t={}){let n=Xc(t),r=Dt(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:zc(e.pm_format_version),source_type:x(e.source_type),type_options:_h(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:Ug(e.dependencies),comments:xi(e.comments),notes:xi(e.notes),learnings:xi(e.learnings),files:Vg(e.files),tests:Zg(e.tests),test_runs:Wg(e.test_runs),docs:oh(e.docs),deadline:Dn(e.deadline),reminders:zg(e.reminders),events:Bg(e.events),closed_at:Dn(e.closed_at),completed_at:Dn(e.completed_at),assignee:x(e.assignee),claim_principal:x(e.claim_principal),source_owner:x(e.source_owner),author:Dn(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:x(e.definition_of_ready),order:e.order,goal:x(e.goal),objective:x(e.objective),value:x(e.value),impact:x(e.impact),outcome:x(e.outcome),why_now:x(e.why_now),parent:x(e.parent),reviewer:x(e.reviewer),risk:e.risk??void 0,confidence:gh(e.confidence),sprint:x(e.sprint),release:x(e.release),blocked_by:x(e.blocked_by),blocked_reason:x(e.blocked_reason),unblock_note:x(e.unblock_note),reporter:x(e.reporter),severity:hh(e.severity),environment:x(e.environment),repro_steps:x(e.repro_steps),resolution:x(e.resolution),expected_result:x(e.expected_result),actual_result:x(e.actual_result),affected_version:x(e.affected_version),fixed_version:x(e.fixed_version),component:x(e.component),regression:e.regression,customer_impact:x(e.customer_impact),close_reason:Dn(e.close_reason),plan_mode:x(e.plan_mode),plan_scope:x(e.plan_scope),plan_harness:x(e.plan_harness),plan_resume_context:x(e.plan_resume_context),plan_steps:uh(e.plan_steps),plan_decisions:fh(e.plan_decisions),plan_discoveries:ph(e.plan_discoveries),plan_validation:mh(e.plan_validation)};return yh(i,e),bh(i,n),wh(i,n),qr(i),i}function Zc(e){return lt(e,Se)}function vh(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 Eh(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=vh(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 kh(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(`
5
+ `,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 Ni(e,t){return Mn(e,{...t,onWarning:void 0})}function Th(e,t,n={}){let r=kh(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=Eh(r.content);o||(e.trimStart().startsWith("{")&&Pn("json_markdown","JSON front matter is not valid JSON"),Pn("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{Pn("json_markdown","JSON front matter is not valid JSON")}return Ri(s,t),{metadata:Ni(s,n),body:on(i)}}function Sh(e,t,n={}){let r;try{r=Si(e).value}catch{Pn("toon","TOON item document is not valid TOON")}I(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(!Yc.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&Pn("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ri(o.front_matter,t),I(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Ni(o.front_matter,n),body:on(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return I(i===void 0||typeof i=="string","TOON item document body must be a string"),Ri(s,t),{metadata:Ni(s,n),body:on(typeof i=="string"?i:"")}}function Ah(e,t={}){let n=Mn(e.metadata,t),r=Zc(n),o=JSON.stringify(r,null,2),i=on(e.body??"");return i?`${o}
6
6
 
7
7
  ${i}
8
8
  `:`${o}
9
- `}function wh(e,t={}){let n=Rn(e.metadata,t),r=Jc(n),o=nn(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=cg(s),c;try{c=ki(a).value}catch(l){throw new y("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:l instanceof Error?l.message:String(l)})}if(!Bc(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!Bc(s[u],l[u]))??"document";throw new y(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${d}".`,h.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}
10
- `}function xe(e,t={}){let n=Me(e);if(n)throw new y(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Yc(t);return r==="toon"?yh(e,o,t):hh(e,o,t)}function Ot(e,t={}){return(t.format??"toon")==="toon"?wh(e,t):bh(e,t)}function be(e,t={}){return{metadata:Rn(e.metadata,t),body:nn(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{}})();import ld from"fast-json-patch";import{AsyncLocalStorage as $y}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]="624aced5-552c-5354-9e34-b96e267d34d1")}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]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();import qr from"node:fs";import Rt from"node:path";import{fileURLToPath as vh}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 Eh="@unbrained/pm-cli";function kh(e){try{return JSON.parse(qr.readFileSync(e,"utf8")).name===Eh}catch{return!1}}function Th(e){let t=qr.existsSync(e)&&qr.statSync(e).isDirectory()?Rt.resolve(e):Rt.dirname(Rt.resolve(e));for(;;){let n=Rt.join(t,"package.json");if(qr.existsSync(n)&&kh(n))return t;let r=Rt.dirname(t);if(r===t)return;t=r}}function on(e,t=[]){let n=vh(e),r=Th(n);return r||Rt.resolve(Rt.dirname(n),...t)}import{readFileSync as Hh,readdirSync as eN,statSync as Vh}from"node:fs";import Z from"node:path";import Ih 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 dt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Sh(e){let t=e.key.trim();if(t.length===0)return null;let n=dt(e.aliases),r=e.description?.trim();return{key:t,values:dt(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 Ah=e=>e,Qc=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function xh(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 Ch(e,t){let n=new Map;for(let r of e??[]){let o=xh(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 Zc(e,t){return t?dt(e):void 0}function Di(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Br(e,t={}){let n=t.resolvePolicyCommand??Ah,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=dt(e.aliases),l=(e.options??[]).map(u=>Sh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=Ch(e.command_option_policies,n);return{name:r,description:Di(e.description),default_status:Di(e.default_status),folder:Di(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Zc(e.required_create_fields,o),required_create_repeatables:Zc(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 Oh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],Rh=["dep","comment","note","learning","file","test","doc"],Pi=["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"],VR=["title","description","type","status","priority","tags","body",...Pi,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],WR=["title","description","body","status","closeReason","priority","type","tags",...Pi,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],tl={"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"},KR={...tl},YR={...tl},nl=[["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"]],rl=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function ol(e){return Object.fromEntries(e)}var XR=ol([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...nl,["author","--author"],["message","--message"],["dep","--dep"],...rl]),JR=ol([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...nl,...rl,["author","--author"],["message","--message"],["force","--force"]]);function Gr(e){let t=Nh(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function il(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=Ih.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 Nh(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 Dh(e){return Br(e,{resolvePolicyCommand:Qc})}function Nn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Ph(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:Nn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Nn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Lh(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 Mh(e){if(Array.isArray(e.options))return e.options.map(t=>Ph(t)).filter(t=>t!==null)}function Fh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Lh(t)).filter(t=>t!==null)}function $h(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:Nn(t,"aliases"),required_create_fields:Nn(t,"required_create_fields"),required_create_repeatables:Nn(t,"required_create_repeatables"),options:Mh(t),command_option_policies:Fh(t)}}function jh(e,t){return e.required_create_fields?dt(e.required_create_fields):t?.required_create_fields??[]}function Uh(e,t){return e.required_create_repeatables?dt(e.required_create_repeatables):t?.required_create_repeatables??[]}function zh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function qh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Bh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=il(e.folder??t?.folder??Gr(n)),s={name:n,folder:i,aliases:dt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:jh(e,t),required_create_repeatables:Uh(e,t),options:zh(e,t),command_option_policies:qh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function el(e,t){for(let n of e){let r=Dh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Bh(r,i))}}function Gh(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=$h(o);i&&t.push(i)}}return t}function le(e,t=null){let n=new Map;for(let c of yc)n.set(c.toLowerCase(),{name:c,folder:Se[c],aliases:[],required_create_fields:[...Oh],required_create_repeatables:[...Rh],options:[],command_option_policies:[]});el(e.item_types?.definitions??[],n),el(Gh(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(){try{var e=typeof window<"u"?window:typeof 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 Wh={json_markdown:".md",toon:".toon"},Kh={".md":"json_markdown",".toon":"toon"};var sn=[".md",".toon"];function Hr(e){try{return Vh(e),!0}catch{return!1}}function Yh(e){try{let t=JSON.parse(Hh(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Xh(e){let t=Z.resolve(e);for(;;){let n=Z.join(t,Yt),r=Z.join(n,Er);if(Hr(r))return n;let o=Z.join(t,Er);if(Hr(o)&&Yh(o))return t;let i=Z.dirname(t);if(i===t)return;t=i}}function sl(e){return Xh(e)??Z.resolve(e,Yt)}function ne(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=Z.resolve(e,r);if(!Hr(we(o))){let i=Z.join(o,Yt);if(Hr(we(i)))return i}return o}return sl(e)}function Vr(e){let t=Z.resolve(e),n=Z.dirname(t);return Z.basename(t)==="pm"&&Z.basename(n)===".agents"?Z.dirname(n):t}function we(e){return Z.join(e,Er)}function Jh(e,t,n=Se){let r=n[t]??Gr(t);return Z.join(e,r)}function an(e,t,n,r="toon",o=Se){return Z.join(Jh(e,t,o),`${n}${Wh[r]}`)}function Wr(e){let t=e.replaceAll("\\","/"),n=Z.posix.extname(t).toLowerCase();return Kh[n]??null}function Ge(e,t){return Z.join(e,"history",`${t}.jsonl`)}function al(e,t){return Z.join(e,"locks",`${t}.lock`)}function Kr(e){return Z.join(e,"runtime")}(function(){try{var e=typeof window<"u"?window:typeof 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 iN=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"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]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function Nt(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,g=Math.min(f,p,_);c>1&&d>1&&e[c-1]===t[d-2]&&e[c-2]===t[d-1]&&(g=Math.min(g,o[d-2]+1)),s[d]=g,g<l&&(l=g)}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]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var cl=Jt;function Li(e){let t=e.trim().toLowerCase();return cl.includes(t)?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]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}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]="1558713a-91ea-5eef-8426-d910e0b77045")}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]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function Dt(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function Zh(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function ll(e){return e?Je(e):{}}function dl(e){return e?Je(e):Zh()}function Je(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]="065f61c6-2123-5a6d-984a-569bb14d6911")}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]="a30142c8-b04d-5878-8497-c902ff299e94")}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]="dc9a3977-a78a-501e-b600-45e7031dcebd")}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]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var ul=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 vN=new Set(ul);(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 Fi=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"}]),Qh=new Set(Fi.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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 $i=[{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 Yr(e){return e.trim().toLowerCase().replaceAll("-","_")}function ey(e){if(e===void 0)return;let t=Yr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function ji(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)ji(n,t);return Object.freeze(e)}for(let n of Object.values(e))ji(n,t);return Object.freeze(e)}function ty(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 ny(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 ry(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 oy(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=Yr(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 iy(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 sy(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 ay(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var Ui=class{#e=new Map;#t=new Map;constructor(t=$i){for(let n of t)this.register(n)}register(t){let n=oy(t);if(iy(t,n),sy(t,n),ty(t,n),ny(t,n),ry(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=ey(t.inverse),o=[...new Set((t.aliases??[]).map(Yr))].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.#t.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:ay(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?ji(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#t.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Yr(t);return this.#e.get(this.#t.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 cn(){return new Ui}var NN=cn();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 dy=5e3;async function pl(e,t,n){let r=[];for(let o of e)try{await o.run(Je(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function uy(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 y(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let 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 y(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new y(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function zi(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:Je(t.before),after:t.after===null?null:Je(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 y(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},dy),o.unref?.()})])}catch(i){throw i instanceof y?i:new y(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.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)}uy(r,n,t.operation)}}async function qi(e,t){return pl(e.onWrite,"onWrite",t)}async function Bi(e,t){return pl(e.onRead,"onRead",t)}function fy(e){return{handled:!1,result:e.payload,warnings:[]}}function py(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function my(e){return{service:e.service,command:e.command?Dt(e.command):void 0,args:e.args?Je(e.args):void 0,options:e.options?ll(e.options):void 0,global:e.global?dl(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:Je(e.payload)}}function _y(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 gy(e,t){return _y(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 hy(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&Ae(e,n.payload)}function yy(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}}}async function Gi(e,t){let n=py(e,t.service);if(n.length===0)return fy(t);let r=[];for(let o of n)try{let i=my(t),s=await Promise.resolve(o.run(i));if(hy(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=yy(o,gy(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(){try{var e=typeof window<"u"?window:typeof 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 RD=Object.freeze(vr());(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 Xr=null;var jy=null;var Uy=null,zy=null;var qy=[],By=new $y;function ut(){return By.getStore()}var Gy=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function V(){let e=ut();return e?e.registrations:Uy}function Hi(e){if(!e)return;let t=ut();t?t.affectedItems.push(e):qy.push(e)}function Jr(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"||Gy.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function ve(e){let t=ut(),n=t?t.hooks:Xr;return n?qi(n,e):[]}async function Vi(e){let t=ut(),n=t?t.hooks:Xr;n&&await zi(n,e)}async function Fe(e){let t=ut(),n=t?t.hooks:Xr;return n?Bi(n,e):[]}function Zr(){let e=ut();return((e?e.hooks:Xr)?.onRead?.length??0)>0}function Hy(e,t){let n=ut(),r=n?n.commandContext:zy;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 He(e,t){let n=ut(),r=n?n.services:jy;return r?Gi(r,Hy(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as Qi}from"node:async_hooks";import{createHash as eb}from"node:crypto";import Ve from"node:fs";import kl from"node:os";import no from"node:path";import{AsyncLocalStorage as Vy}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 Wy=new Vy,hl=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Qr(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Dn(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Qr(n.id,128),o=Qr(n.parent_id,128);if(r===void 0||!hl.test(r)||o!==void 0&&!hl.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Qr(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Wi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Qr(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function Ky(e,t,n){let r=Wy.getStore(),o=Wi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Dn(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={...Wi(r?.provenance),...o,...Wi(e?.provenance)},a=Dn(e?.episode,!1)??Dn(n,!1)??i??Dn(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 eo(e,t){return Ky(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as Ki,promises as nP,readFileSync as Yy}from"node:fs";import Ze 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 Xy="session.json";function Yi(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Jy(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=Yi(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=>Yi(c,128)),a=t.focused_item_id===void 0||Yi(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function Zy(e){return Ze.join(Kr(e),Xy)}function Qy(e,t){let n=t.PM_PATH?.trim();if(n){let o=Ze.resolve(e,n);if(Ki(Ze.join(o,"settings.json")))return o;let i=Ze.join(o,".agents","pm");if(Ki(Ze.join(i,"settings.json")))return i}let r=Ze.resolve(e);for(let o=0;o<32;o+=1){let i=Ze.join(r,".agents","pm");if(Ki(Ze.join(i,"settings.json")))return i;let s=Ze.dirname(r);if(s===r)break;r=s}}function yl(e){if(!e.key)return;let t=Qy(e.cwd,e.env);if(t)try{let n=JSON.parse(Yy(Zy(t),"utf8"));return Jy(n.semantic_attribution?.[e.key])}catch{return}}(function(){try{var e=typeof window<"u"?window:typeof 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 es=["model","effort","role","topic","version"],oo=new Qi,tb=new Qi,ts=new Qi,ns=[{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:[]}],Tl=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),nb=Object.freeze({...Tl,max_bytes:4194304}),Xi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function rb(e){let t=Pn(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"?nb:Tl,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 ob=Object.freeze(ns.filter(e=>e.harness!=="ci").map(rb).sort((e,t)=>e.harness.localeCompare(t.harness))),ib=new Map,sb=new Map;function H(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function Pt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function Pn(e){let t=e.harness.trim().toLowerCase();if(!Xi.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:Pt(e.environment_keys),model_environment_keys:Pt(e.model_environment_keys),session_environment_keys:Pt(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),Pt(r)]).filter(([n])=>Xi.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"&&Xi.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:Pt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:Pt(e.argv_markers).map(n=>n.toLowerCase()),client_names:Pt(e.client_names).map(n=>n.toLowerCase())}}var ab=ns.map(Pn);function ro(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function Sl(e=[]){let t=new Map(ns.filter(o=>o.harness!=="ci").map(o=>[o.harness,Pn(o)]));for(let{adapter:o}of ib.values())t.set(o.harness,Pn(o.descriptor));let n=[...t.values(),...ab.filter(o=>o.harness==="ci"),...[...sb.values()].map(o=>o.descriptor),...ts.getStore()?.descriptors??[],...e.map(Pn)],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 rs(e,t){for(let n of t??[]){let r=H(e[n]);if(r)return r.slice(0,256)}}function cb(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 Al(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 H(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return H(i.slice(s.length+1))?.slice(0,256)}}var lb=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Lt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return lb.has(n)?n:void 0}function Ji(e,t){return H(e?.[t])?.slice(0,256)}var db=1048576,bl=4194304,to=new Map,wl=Object.freeze({}),Zi=new Map,vl=Object.freeze({});function El(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function ub(e){let t;try{t=JSON.parse(e)}catch{return vl}let n=El(t);if(!n)return vl;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=H(a.value.model)?.slice(0,256),s??=H(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=El(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function fb(e,t,n){let r=H(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=no.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=no.join(t.home_dir??kl.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=Ve.openSync(s,"r");try{let c=Ve.fstatSync(a),l=`${s}\0${c.size}\0${c.mtimeMs}`,d=Zi.get(l);if(d)return d[e];let u=Math.min(c.size,db),f=Math.min(u,Math.ceil(u/2)),p=Math.min(u-f,c.size-f),_=Buffer.alloc(f);Ve.readSync(a,_,0,f,0);let g=Buffer.alloc(p);p>0&&Ve.readSync(a,g,0,p,c.size-p);let b={},E=c.size<=u?Buffer.concat([_,g]).toString("utf8").split(`
9
+ `}function xh(e,t={}){let n=Mn(e.metadata,t),r=Zc(n),o=on(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i)),a=_g(s),c;try{c=Si(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(!Gc(c,s)){let l=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},d=Object.keys(s).find(u=>!Gc(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}
10
+ `}function Ce(e,t={}){let n=Le(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=Xc(t);return r==="toon"?Sh(e,o,t):Th(e,o,t)}function Pt(e,t={}){return(t.format??"toon")==="toon"?xh(e,t):Ah(e,t)}function we(e,t={}){return{metadata:Mn(e.metadata,t),body:on(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{}})();import dd from"fast-json-patch";import{AsyncLocalStorage as Hy}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]="624aced5-552c-5354-9e34-b96e267d34d1")}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]="22af7808-6456-5889-b6e3-1abd73f35738")}catch{}})();import Br from"node:fs";import Lt from"node:path";import{fileURLToPath as Ch}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 Ih="@unbrained/pm-cli";function Oh(e){try{return JSON.parse(Br.readFileSync(e,"utf8")).name===Ih}catch{return!1}}function Rh(e){let t=Br.existsSync(e)&&Br.statSync(e).isDirectory()?Lt.resolve(e):Lt.dirname(Lt.resolve(e));for(;;){let n=Lt.join(t,"package.json");if(Br.existsSync(n)&&Oh(n))return t;let r=Lt.dirname(t);if(r===t)return;t=r}}function an(e,t=[]){let n=Ch(e),r=Rh(n);return r||Lt.resolve(Lt.dirname(n),...t)}import{readFileSync as Zh,readdirSync as lN,statSync as Qh}from"node:fs";import ee from"node:path";import Mh 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 pt(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Nh(e){let t=e.key.trim();if(t.length===0)return null;let n=pt(e.aliases),r=e.description?.trim();return{key:t,values:pt(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 Dh=e=>e,el=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function Ph(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 Lh(e,t){let n=new Map;for(let r of e??[]){let o=Ph(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 Qc(e,t){return t?pt(e):void 0}function Li(e){let t=e?.trim();return t&&t.length>0?t:void 0}function Gr(e,t={}){let n=t.resolvePolicyCommand??Dh,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=pt(e.aliases),l=(e.options??[]).map(u=>Nh(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),d=Lh(e.command_option_policies,n);return{name:r,description:Li(e.description),default_status:Li(e.default_status),folder:Li(e.folder),aliases:c.length>0?c:void 0,required_create_fields:Qc(e.required_create_fields,o),required_create_repeatables:Qc(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 Fh=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],$h=["dep","comment","note","learning","file","test","doc"],Mi=["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"],tN=["title","description","type","status","priority","tags","body",...Mi,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],nN=["title","description","body","status","closeReason","priority","type","tags",...Mi,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],nl={"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"},rN={...nl},oN={...nl},rl=[["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"]],ol=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function il(e){return Object.fromEntries(e)}var iN=il([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...rl,["author","--author"],["message","--message"],["dep","--dep"],...ol]),sN=il([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...rl,...ol,["author","--author"],["message","--message"],["force","--force"]]);function Hr(e){let t=jh(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function sl(e){let t=e.trim(),r=t.replaceAll("\\","/").replace(/^\/+/,""),o=Mh.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 jh(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 Uh(e){return Gr(e,{resolvePolicyCommand:el})}function Fn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function zh(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:Fn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Fn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function qh(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 Bh(e){if(Array.isArray(e.options))return e.options.map(t=>zh(t)).filter(t=>t!==null)}function Gh(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>qh(t)).filter(t=>t!==null)}function Hh(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:Fn(t,"aliases"),required_create_fields:Fn(t,"required_create_fields"),required_create_repeatables:Fn(t,"required_create_repeatables"),options:Bh(t),command_option_policies:Gh(t)}}function Vh(e,t){return e.required_create_fields?pt(e.required_create_fields):t?.required_create_fields??[]}function Wh(e,t){return e.required_create_repeatables?pt(e.required_create_repeatables):t?.required_create_repeatables??[]}function Kh(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Yh(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function Xh(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=sl(e.folder??t?.folder??Hr(n)),s={name:n,folder:i,aliases:pt([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Vh(e,t),required_create_repeatables:Wh(e,t),options:Kh(e,t),command_option_policies:Yh(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function tl(e,t){for(let n of e){let r=Uh(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,Xh(r,i))}}function Jh(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=Hh(o);i&&t.push(i)}}return t}function ue(e,t=null){let n=new Map;for(let c of bc)n.set(c.toLowerCase(),{name:c,folder:Ae[c],aliases:[],required_create_fields:[...Fh],required_create_repeatables:[...$h],options:[],command_option_policies:[]});tl(e.item_types?.definitions??[],n),tl(Jh(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(){try{var e=typeof window<"u"?window:typeof 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 ey={json_markdown:".md",toon:".toon"},ty={".md":"json_markdown",".toon":"toon"};var cn=[".md",".toon"];function Vr(e){try{return Qh(e),!0}catch{return!1}}function ny(e){try{let t=JSON.parse(Zh(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function ry(e){let t=ee.resolve(e);for(;;){let n=ee.join(t,Xt),r=ee.join(n,Tr);if(Vr(r))return n;let o=ee.join(t,Tr);if(Vr(o)&&ny(o))return t;let i=ee.dirname(t);if(i===t)return;t=i}}function al(e){return ry(e)??ee.resolve(e,Xt)}function re(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=ee.resolve(e,r);if(!Vr(ve(o))){let i=ee.join(o,Xt);if(Vr(ve(i)))return i}return o}return al(e)}function Wr(e){let t=ee.resolve(e),n=ee.dirname(t);return ee.basename(t)==="pm"&&ee.basename(n)===".agents"?ee.dirname(n):t}function ve(e){return ee.join(e,Tr)}function oy(e,t,n=Ae){let r=n[t]??Hr(t);return ee.join(e,r)}function ln(e,t,n,r="toon",o=Ae){return ee.join(oy(e,t,o),`${n}${ey[r]}`)}function Kr(e){let t=e.replaceAll("\\","/"),n=ee.posix.extname(t).toLowerCase();return ty[n]??null}function Be(e,t){return ee.join(e,"history",`${t}.jsonl`)}function cl(e,t){return ee.join(e,"locks",`${t}.lock`)}function Yr(e){return ee.join(e,"runtime")}(function(){try{var e=typeof window<"u"?window:typeof 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 mN=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"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]="294d43fb-b6e8-5a5f-91fe-73ba21075bf5")}catch{}})();function Mt(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]="f6ec614c-2e47-5ce0-bbf6-8dde97ffb99e")}catch{}})();var ll=Zt;function Fi(e){let t=e.trim().toLowerCase();return ll.includes(t)?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]="e81790e9-3de2-5639-a84d-2c4714afbbf4")}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]="1558713a-91ea-5eef-8426-d910e0b77045")}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]="2f268c53-f096-5eed-9ddb-01fed4839ae5")}catch{}})();function Ft(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function iy(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function dl(e){return e?Ze(e):{}}function ul(e){return e?Ze(e):iy()}function Ze(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]="065f61c6-2123-5a6d-984a-569bb14d6911")}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]="a30142c8-b04d-5878-8497-c902ff299e94")}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]="dc9a3977-a78a-501e-b600-45e7031dcebd")}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]="b799a368-2a8a-5031-8d14-f6b9dc4a3978")}catch{}})();var fl=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 ON=new Set(fl);(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 ji=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"}]),sy=new Set(ji.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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 Ui=[{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 Xr(e){return e.trim().toLowerCase().replaceAll("-","_")}function ay(e){if(e===void 0)return;let t=Xr(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function zi(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)zi(n,t);return Object.freeze(e)}for(let n of Object.values(e))zi(n,t);return Object.freeze(e)}function cy(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 ly(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 dy(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 uy(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=Xr(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 fy(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 py(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 my(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var qi=class{#e=new Map;#t=new Map;constructor(t=Ui){for(let n of t)this.register(n)}register(t){let n=uy(t);if(fy(t,n),py(t,n),cy(t,n),ly(t,n),dy(t,n),this.#e.has(n)||this.#t.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=ay(t.inverse),o=[...new Set((t.aliases??[]).map(Xr))].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.#t.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:my(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?zi(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#t.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Xr(t);return this.#e.get(this.#t.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 dn(){return new qi}var zN=dn();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 hy=5e3;async function ml(e,t,n){let r=[];for(let o of e)try{await o.run(Ze(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}function yy(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 Bi(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:Ze(t.before),after:t.after===null?null:Ze(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."]}))},hy),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)}yy(r,n,t.operation)}}async function Gi(e,t){return ml(e.onWrite,"onWrite",t)}async function Hi(e,t){return ml(e.onRead,"onRead",t)}function by(e){return{handled:!1,result:e.payload,warnings:[]}}function wy(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function vy(e){return{service:e.service,command:e.command?Ft(e.command):void 0,args:e.args?Ze(e.args):void 0,options:e.options?dl(e.options):void 0,global:e.global?ul(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:Ze(e.payload)}}function Ey(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 ky(e,t){return Ey(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 Ty(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&xe(e,n.payload)}function Sy(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}}}async function Vi(e,t){let n=wy(e,t.service);if(n.length===0)return by(t);let r=[];for(let o of n)try{let i=vy(t),s=await Promise.resolve(o.run(i));if(Ty(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=Sy(o,ky(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(){try{var e=typeof window<"u"?window:typeof 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 UD=Object.freeze(kr());(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 Jr=null;var Vy=null;var Wy=null,Ky=null;var Yy=[],Xy=new Hy;function mt(){return Xy.getStore()}var Jy=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function Y(){let e=mt();return e?e.registrations:Wy}function Wi(e){if(!e)return;let t=mt();t?t.affectedItems.push(e):Yy.push(e)}function Zr(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"||Jy.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}async function Ee(e){let t=mt(),n=t?t.hooks:Jr;return n?Gi(n,e):[]}async function Ki(e){let t=mt(),n=t?t.hooks:Jr;n&&await Bi(n,e)}async function Me(e){let t=mt(),n=t?t.hooks:Jr;return n?Hi(n,e):[]}function Qr(){let e=mt();return((e?e.hooks:Jr)?.onRead?.length??0)>0}function Zy(e,t){let n=mt(),r=n?n.commandContext:Ky;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 Ge(e,t){let n=mt(),r=n?n.services:Vy;return r?Vi(r,Zy(e,t)):{handled:!1,result:t,warnings:[]}}import{AsyncLocalStorage as ts}from"node:async_hooks";import{createHash as ab}from"node:crypto";import He from"node:fs";import Tl from"node:os";import ro from"node:path";import{AsyncLocalStorage as Qy}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 eb=new Qy,yl=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function eo(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function $n(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=eo(n.id,128),o=eo(n.parent_id,128);if(r===void 0||!yl.test(r)||o!==void 0&&!yl.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=eo(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function Yi(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=eo(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function tb(e,t,n){let r=eb.getStore(),o=Yi({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=$n(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={...Yi(r?.provenance),...o,...Yi(e?.provenance)},a=$n(e?.episode,!1)??$n(n,!1)??i??$n(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 to(e,t){return tb(e.session_context,t,e.client_info?.episode)??{}}import{existsSync as Xi,promises as uP,readFileSync as nb}from"node:fs";import Qe 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 rb="session.json";function Ji(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function ob(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=Ji(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=>Ji(c,128)),a=t.focused_item_id===void 0||Ji(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function ib(e){return Qe.join(Yr(e),rb)}function sb(e,t){let n=t.PM_PATH?.trim();if(n){let o=Qe.resolve(e,n);if(Xi(Qe.join(o,"settings.json")))return o;let i=Qe.join(o,".agents","pm");if(Xi(Qe.join(i,"settings.json")))return i}let r=Qe.resolve(e);for(let o=0;o<32;o+=1){let i=Qe.join(r,".agents","pm");if(Xi(Qe.join(i,"settings.json")))return i;let s=Qe.dirname(r);if(s===r)break;r=s}}function bl(e){if(!e.key)return;let t=sb(e.cwd,e.env);if(t)try{let n=JSON.parse(nb(ib(t),"utf8"));return ob(n.semantic_attribution?.[e.key])}catch{return}}(function(){try{var e=typeof window<"u"?window:typeof 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 ns=["model","effort","role","topic","version"],io=new ts,cb=new ts,rs=new ts,os=[{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:[]}],Sl=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),lb=Object.freeze({...Sl,max_bytes:4194304}),Zi=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function db(e){let t=jn(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"?lb:Sl,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 ub=Object.freeze(os.filter(e=>e.harness!=="ci").map(db).sort((e,t)=>e.harness.localeCompare(t.harness))),fb=new Map,pb=new Map;function H(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 jn(e){let t=e.harness.trim().toLowerCase();if(!Zi.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])=>Zi.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"&&Zi.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 mb=os.map(jn);function oo(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(r=>r.length>0).includes(t)||e.trim().toLowerCase()===t}function Al(e=[]){let t=new Map(os.filter(o=>o.harness!=="ci").map(o=>[o.harness,jn(o)]));for(let{adapter:o}of fb.values())t.set(o.harness,jn(o.descriptor));let n=[...t.values(),...mb.filter(o=>o.harness==="ci"),...[...pb.values()].map(o=>o.descriptor),...rs.getStore()?.descriptors??[],...e.map(jn)],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 is(e,t){for(let n of t??[]){let r=H(e[n]);if(r)return r.slice(0,256)}}function _b(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 xl(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 H(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return H(i.slice(s.length+1))?.slice(0,256)}}var gb=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function jt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return gb.has(n)?n:void 0}function Qi(e,t){return H(e?.[t])?.slice(0,256)}var hb=1048576,wl=4194304,no=new Map,vl=Object.freeze({}),es=new Map,El=Object.freeze({});function kl(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function yb(e){let t;try{t=JSON.parse(e)}catch{return El}let n=kl(t);if(!n)return El;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=H(a.value.model)?.slice(0,256),s??=H(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let l=kl(c);l&&r.push({value:l,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function bb(e,t,n){let r=H(n.CLAUDE_CODE_SESSION_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let i=ro.resolve(t.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),s=ro.join(t.home_dir??Tl.homedir(),".claude","projects",i,`${r}.jsonl`);try{let a=He.openSync(s,"r");try{let c=He.fstatSync(a),l=`${s}\0${c.size}\0${c.mtimeMs}`,d=es.get(l);if(d)return d[e];let u=Math.min(c.size,hb),f=Math.min(u,Math.ceil(u/2)),p=Math.min(u-f,c.size-f),_=Buffer.alloc(f);He.readSync(a,_,0,f,0);let y=Buffer.alloc(p);p>0&&He.readSync(a,y,0,p,c.size-p);let b={},E=c.size<=u?Buffer.concat([_,y]).toString("utf8").split(`
11
11
  `):[..._.toString("utf8").split(`
12
- `).slice(0,4096),...g.toString("utf8").split(`
13
- `).slice(-4096)];for(let I of E){if(I.length===0||I.length>262144)continue;let T=ub(I);if(b.model??=T.model,b.version??=T.version,b.model&&b.version)break}let v=Object.freeze(b);return Zi.clear(),Zi.set(l,v),v[e]}finally{Ve.closeSync(a)}}catch{return}}function pb(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=Ve.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=no.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 mb(e){if(e<=bl)return[{offset:0,length:e}];let t=Math.floor(bl/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function _b(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??=H(o?.model)?.slice(0,256),e.effort??=H(o?.effort)?.slice(0,256)}function gb(e,t){let n={},r=4096;for(let o of mb(t)){let i=Buffer.alloc(o.length);Ve.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
14
- `).reverse().slice(0,r);r-=s.length;for(let a of s)if(_b(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function hb(e,t,n){let r=H(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=no.join(t.home_dir??kl.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=to.get(i);if(s)return s[e];let a=pb(o,r);if(!a){to.set(i,wl);return}try{let c=Ve.openSync(a,"r");try{let l=Ve.fstatSync(c).size,d=gb(c,l);return to.set(i,d),d[e]}finally{Ve.closeSync(c)}}catch{to.set(i,wl);return}}function yb(e,t,n,r){let o=ts.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(H(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return fb(e,t,n);if(s==="codex_session_file")return hb(e,t,n);if(s==="ai_agent_version"){let a=H(n.AI_AGENT);return!a||!r||!ro(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function bb(e,t,n){if(e==="ai_agent_version"){let r=H(n.AI_AGENT);return r!==void 0&&ro(r,t.harness)}return e==="codex_session_file"?H(n.CODEX_THREAD_ID)!==void 0:H(n.CLAUDE_CODE_SESSION_ID)!==void 0}function os(e){return e||(tb.getStore()??{env:process.env,argv:process.argv})}function wb(e,t,n,r){let o=e.environment_keys.some(a=>H(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return ro(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||ro(r,a));return o||i||s}function vb(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 Eb(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function kb(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...es,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=Lt(e,H(n[s])?.slice(0,256)),d=Lt(e,Al(t.argv??[],e)),l=Lt(e,cb(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=Ji(o?.provenance,e),_=Lt(e,rs(n,u[e])),g=Lt(e,Ji(f,e)),b=Lt(e,Ji(t.provenance,e)),E=yb(e,t,n,r);return Eb([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[g,"mcp_client"],[b,"host"],[E,"probe"]])??vb(e,i)??(l?{value:l,source:"argv"}:void 0)}function Tb(e,t){if(!(!e||!t))return eb("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Sb(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...es,...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=kb(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 is(e){let t=os(e),n=t.env??{},r=Sl(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(_=>wb(_,n,o,i)),a=eo(t,n),c=[rs(n,s?.session_environment_keys),H(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=Tb(s?.harness,c),d=yl({cwd:t.cwd??process.cwd(),env:n,key:l}),u=Sb(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 Ab(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=bb(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 ss(e){let t=os(e),n=is(t),r=Sl(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&ts.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(H(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=eo(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,rs(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,Al(t.argv??[],"role")].some(l=>{let d=H(l)?.slice(0,256);return d!==void 0&&Lt("role",d)===void 0}),c=Object.fromEntries(es.map(l=>[l,Ab(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function xb(e,t,n){let r=os(n),o=is(r);if(e!==void 0){let s=H(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=H(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=H(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function xl(e){let t=oo.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Cl(e){let t=oo.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 as(e){let t=oo.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function $e(e,t){let n=xb(e,t);return oo.enterWith(n),n.author}import cs from"node:fs/promises";import ln from"node:path";import{createRequire as Cb}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]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function ft(e,t){let n=await J(e);if(n===null)return[];if(await Fe({path:e,scope:"project"}),n.trim()==="")return[];let r=Me(n);if(r)throw new y(`History for ${t} contains merge conflict markers at line ${r.line} (${r.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let o=[];for(let[i,s]of n.split(/\r?\n/).entries()){let a=s.trim();if(a)try{o.push(JSON.parse(a))}catch{throw new y(`History for ${t} contains invalid JSON at line ${i+1}. Repair or restore the history stream and retry.`,h.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]="a84b308f-7eef-535c-9531-b33b0775c651")}catch{}})();var Ib="history-event-index.sqlite",Ob="2";function Il(e){return ln.join(e,"runtime",Ib)}function Rb(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function Nb(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?Rb(t):null}var io;function Db(){return io!==void 0||(io=Nb(process.versions.node,Cb(import.meta.url))),io}function Pb(e,t){e.prepare(`INSERT INTO events(
12
+ `).slice(0,4096),...y.toString("utf8").split(`
13
+ `).slice(-4096)];for(let C of E){if(C.length===0||C.length>262144)continue;let k=yb(C);if(b.model??=k.model,b.version??=k.version,b.model&&b.version)break}let v=Object.freeze(b);return es.clear(),es.set(l,v),v[e]}finally{He.closeSync(a)}}catch{return}}function wb(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=He.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=ro.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 vb(e){if(e<=wl)return[{offset:0,length:e}];let t=Math.floor(wl/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function Eb(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??=H(o?.model)?.slice(0,256),e.effort??=H(o?.effort)?.slice(0,256)}function kb(e,t){let n={},r=4096;for(let o of vb(t)){let i=Buffer.alloc(o.length);He.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
14
+ `).reverse().slice(0,r);r-=s.length;for(let a of s)if(Eb(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function Tb(e,t,n){let r=H(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=ro.join(t.home_dir??Tl.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=no.get(i);if(s)return s[e];let a=wb(o,r);if(!a){no.set(i,vl);return}try{let c=He.openSync(a,"r");try{let l=He.fstatSync(c).size,d=kb(c,l);return no.set(i,d),d[e]}finally{He.closeSync(c)}}catch{no.set(i,vl);return}}function Sb(e,t,n,r){let o=rs.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(H(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let s=r?.provenance_resolvers[e];if(s==="claude_session_file")return bb(e,t,n);if(s==="codex_session_file")return Tb(e,t,n);if(s==="ai_agent_version"){let a=H(n.AI_AGENT);return!a||!r||!oo(a,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(a)?.[1]?.slice(0,256)}}function Ab(e,t,n){if(e==="ai_agent_version"){let r=H(n.AI_AGENT);return r!==void 0&&oo(r,t.harness)}return e==="codex_session_file"?H(n.CODEX_THREAD_ID)!==void 0:H(n.CLAUDE_CODE_SESSION_ID)!==void 0}function ss(e){return e||(cb.getStore()??{env:process.env,argv:process.argv})}function xb(e,t,n,r){let o=e.environment_keys.some(a=>H(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let l=c.replaceAll("\\","/");return oo(l.slice(l.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||oo(r,a));return o||i||s}function Cb(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 Ib(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function Ob(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...ns,...Object.keys(r?.provenance_environment_keys??{})]),c,l,d;a.has(e)&&(c=jt(e,H(n[s])?.slice(0,256)),d=jt(e,xl(t.argv??[],e)),l=jt(e,_b(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=Qi(o?.provenance,e),_=jt(e,is(n,u[e])),y=jt(e,Qi(f,e)),b=jt(e,Qi(t.provenance,e)),E=Sb(e,t,n,r);return Ib([[c,"override"],[p,"session"],[d,"argv"],[_,"environment"],[y,"mcp_client"],[b,"host"],[E,"probe"]])??Cb(e,i)??(l?{value:l,source:"argv"}:void 0)}function Rb(e,t){if(!(!e||!t))return ab("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function Nb(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...ns,...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=Ob(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 as(e){let t=ss(e),n=t.env??{},r=Al(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(_=>xb(_,n,o,i)),a=to(t,n),c=[is(n,s?.session_environment_keys),H(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),l=Rb(s?.harness,c),d=bl({cwd:t.cwd??process.cwd(),env:n,key:l}),u=Nb(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 Db(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=Ab(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 cs(e){let t=ss(e),n=as(t),r=Al(t.descriptors).find(l=>l.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&rs.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(H(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=to(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,is(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,xl(t.argv??[],"role")].some(l=>{let d=H(l)?.slice(0,256);return d!==void 0&&jt("role",d)===void 0}),c=Object.fromEntries(ns.map(l=>[l,Db(l,n,r,o,i,l==="role"&&a)]));return{...n,provenance_outcomes:c}}function Pb(e,t,n){let r=ss(n),o=as(r);if(e!==void 0){let s=H(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=H(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=H(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Cl(e){let t=io.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Il(e){let t=io.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 ls(e){let t=io.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Fe(e,t){let n=Pb(e,t);return io.enterWith(n),n.author}import ds from"node:fs/promises";import un from"node:path";import{createRequire as Lb}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="aa65b74d-ef5d-57ed-b613-3034da52a8ba")}catch{}})();async function _t(e,t){let n=await Q(e);if(n===null)return[];if(await Me({path:e,scope:"project"}),n.trim()==="")return[];let r=Le(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]="a84b308f-7eef-535c-9531-b33b0775c651")}catch{}})();var Mb="history-event-index.sqlite",Fb="2";function Ol(e){return un.join(e,"runtime",Mb)}function $b(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}function jb(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?$b(t):null}var so;function Ub(){return so!==void 0||(so=jb(process.versions.node,Lb(import.meta.url))),so}function zb(e,t){e.prepare(`INSERT INTO events(
15
15
  stream_id, stream_offset, ts, author, agent_harness,
16
16
  agent_instance, op, entry_json
17
- ) 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 Ol(e,t){let n=ln.dirname(ln.dirname(e)),r=Il(n);try{await cs.access(r)}catch{return}let o=Db();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Ob)throw new TypeError("Unsupported history event index version");let a=ln.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);Pb(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await cs.rm(r,{force:!0})}}async function so(e){await cs.rm(Il(ln.dirname(ln.dirname(e))),{force:!0})}import ms from"node:fs/promises";import dn 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]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();import{AsyncLocalStorage as bw}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]="288a7da9-888b-527d-88fb-4711917cec5b")}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]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();function Rl(e,t,n){if(e&&t)throw new y(`${n} cannot be combined with --full`,h.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]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var Lb=1,Mb=4096;var PP=Object.freeze({version:Lb,max_length:Mb});(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 ao=[...[["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"}))],jb=Object.fromEntries(ao.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));(function(){try{var e=typeof window<"u"?window:typeof 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 Ub=[...wn],zb=[...wr],qb=[...si],Bb=[...ai],Gb=[...ci],Hb=[...li],co=["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"];var Nl=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Dl=["upgrade"],Pl=["reopen"],Ll={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},pt=Object.freeze(co.flatMap(e=>e in Ll?[]:e==="extension"||e==="package"?[...Nl.map(t=>`${e}-${t}`),...e==="package"?Dl.map(t=>`package-${t}`):[],e]:e==="item"?Pl.map(t=>`item-${t}`):[e])),Ml=Object.freeze(ao.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&pt.includes(e.alias)).map(e=>e.alias)),Vb=Object.freeze(pt.filter(e=>!Ml.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 Fl=["full","compact","brief","summary","counts"];var $l=["error","warning","validation_summary","recovery_bundle"],jl=["full","omit_explanation","limit_collections","compact_recovery","action_only"],Wb=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"]),Kb=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),Yb=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),Xb={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},Jb=3,Zb=2,Qb=192,ew={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},Ul=$l.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:ew[e],minimum_max_estimated_tokens:Qb,degradation_ladder:jl,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),GP=new Map(Ul.map(e=>[e.diagnostic_class,e]));function zl(e){let[t=""]=e.trim().split(/\s+/u);return Wb.has(t)?"mutation":Kb.has(t)?"discovery":Yb.has(t)?"governance":"read"}function ql(e,t=zl(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=Xb[t];return Bl({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*Jb/Zb)},degradation_ladder:Fl,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Bl(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 Gl=co.map(e=>ql(e)),HP=new Map(Gl.map(e=>[e.command,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]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var nw=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"]),rw=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:nw}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});(function(){try{var e=typeof window<"u"?window:typeof 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 Hl=256,lo=1e4,iw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,sw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var oL=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&iw.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Hl,reason:`token_budget must be a safe integer of at least ${Hl}.`},{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<=lo&&e.seen_item_ids.every(t=>typeof t=="string"&&sw.test(t)),reason:`seen_item_ids must contain at most ${lo} portable item identifiers.`}];(function(){try{var e=typeof window<"u"?window:typeof 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 Vl=["include","amount","cost","encoding"],Wl=["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"],pw=["canonical","legacy","intent","default"],ls={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Kl=Object.freeze(Vl.map(e=>ls[e])),Yl=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Xl={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:{}},Jl=new Set(["--collapse","--fields","--section"]),ds=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 Zl(e){return e.slice(2).replaceAll("-","_")}function mw(e,t){let n=ds[e];if(n!==void 0)return n;let r=t==="include"?Jl.has(e)?"<csv>":Zl(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${ls[t]} ${r}.`}function _w(e){let t=Xl[e],n=Object.freeze(Object.fromEntries(Vl.map(r=>[r,Object.freeze({dimension:r,canonical_option:ls[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:ds[o]===void 0?"replacement":"behavior_preserving",migration_hint:mw(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:pw,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...hw(e).keys()])})}var gw=Object.freeze(Wl.map(_w)),AL=new Map(gw.map(e=>[e.command,e]));function Ln(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 Wl.includes(i)?i:void 0}function hw(e){let t=Ln(e);return t?new Map((Xl[t].include??[]).filter(n=>!Jl.has(n)&&ds[n]===void 0).map(n=>[Zl(n),yw(n)])):new Map}function yw(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}(function(){try{var e=typeof window<"u"?window:typeof 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 zL=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"}]),qL=new bw;(function(){try{var e=typeof window<"u"?window:typeof 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{}})();import{encode as lM}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 dM=new Set(Object.values(h));var Ql=!1;function us(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function vw(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function Ew(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function fs(e){if(e==="stdout"){vw();return}Ew()}function ed(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function kw(){Ql||(Ql=!0,process.stdout.on("error",e=>{if(us(e)){fs("stdout");return}ed(e)}),process.stderr.on("error",e=>{if(us(e)){fs("stderr");return}ed(e)}))}function Tw(e,t){kw();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(us(n))return fs(e),!1;throw n}}function ps(e){return Tw("stderr",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]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var Sw=dn.join("runtime","history-drift-cache.json"),nd={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 rd(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function _s(e){let t=dn.join(e,Sw),n=!1,r="invalid_cache_path";try{n=(await ms.stat(await ms.realpath(e))).isDirectory()}catch(o){let i=rd(o);r=i===void 0?"unknown":nd[i]??"filesystem_error"}if(!n){ps(`[pm] warning: history_drift_cache_invalidation_failed:${r}
18
- `);return}try{await ms.rm(t,{force:!0})}catch(o){let i=rd(o);if(X(o))return;let s=i===void 0?"unknown":nd[i]??"filesystem_error";ps(`[pm] warning: history_drift_cache_invalidation_failed:${s}
19
- `)}}async function Qe(e){let t=dn.dirname(dn.resolve(e));dn.basename(t)==="history"&&await _s(dn.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 je=3,Ce=[1,2,3];function uo(e,t){return(e??"").localeCompare(t??"")}function od(e,t){return(e??0)-(t??0)}function mt(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function Aw(e,t){return[e.scope.localeCompare(t.scope),uo(e.path,t.path),uo(e.command,t.command),od(e.timeout_seconds,t.timeout_seconds),uo(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,mt(e.env_clear,t.env_clear,[]),mt(e.env_set,t.env_set,{}),mt(e.assert_stdout_contains,t.assert_stdout_contains,[]),mt(e.assert_stdout_regex,t.assert_stdout_regex,[]),mt(e.assert_stderr_contains,t.assert_stderr_contains,[]),mt(e.assert_stderr_regex,t.assert_stderr_regex,[]),od(e.assert_stdout_min_lines,t.assert_stdout_min_lines),mt(e.assert_json_field_equals,t.assert_json_field_equals,{}),mt(e.assert_json_field_gte,t.assert_json_field_gte,{}),uo(e.note,t.note)].find(r=>r!==0)??0}function xw(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function Cw(e,t){let n=xw(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 Iw(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!Cw(r,o.path)?{...o,op:"add"}:o;n.push(i),r=ld.applyPatch(r,[i],!0,!0).newDocument}return n}function gs(e,t){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=be(e),o=t===1&&r.metadata.tests?{...r.metadata,tests:[...r.metadata.tests].sort(Aw)}:r.metadata;return{front_matter:st(o,Te),body:r.body}}function id(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=be(e);return{metadata:st(n.metadata,Te),body:n.body}}function Mn(e,t){if(!Ce.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return ce(O(gs(e,t)))}function Fn(e){let t=gs(e.before,je),n=gs(e.after,je),r=id(e.before),o=id(e.after),i=ld.compare(r,o),s=Iw(r,i),a=Cl(e.author),c=a.harness?Object.fromEntries(Object.entries(ss().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??xl(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:ce(O(t)),after_hash:ce(O(n)),item_hash_version:je,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function sd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ow(e){let t=e.ts.trim();return t.length>0?t:q()}function ad(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function fo(e,t){let n=Ow(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(sd(r))return JSON.stringify(ad(r,n))}catch{}return e}return sd(e)?JSON.stringify(ad(e,n)):JSON.stringify(e)}async function po(e,t){let n=await He("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await Qt(e,fo(n.result,t)),await Qe(e),await so(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 Qt(o,fo(r.line,t)),await Qe(o),await so(o);return}await Qt(o,fo(r.entry??t,t)),await Qe(o),await so(o);return}}await Qt(e,fo(t,t)),await Qe(e),await Ol(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]="c823af51-0cfd-536b-8f85-1f3e72db1c86")}catch{}})();var ys={metadata:{},body:""};function $n(){return structuredClone(ys)}function Ie(e,t=je){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return Mn(jn(e),t)}catch{}return ce(O({replay_fallback:!0,metadata:e.metadata,body:e.body}))}function jn(e){return{metadata:e.metadata,body:e.body}}function bs(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=be(e);return{metadata:st(t.metadata,Te),body:t.body}}function dd(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function Rw(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Un(e){return Array.isArray(e)?e.filter(Rw).map(t=>({...t,path:dd(t.path),from:typeof t.from=="string"?dd(t.from):void 0})):[]}function Nw(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 Mt(e,t){try{let n=Un(t),r=hs.applyPatch(structuredClone(e),n,!0,!1).newDocument;return Nw(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 Dw(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Ce.includes(t)))]}function fd(e){return e!==void 0&&!Ce.includes(e)}function Pw(e,t){return e!==void 0?[e]:t===void 0?[...Ce]:[t]}function Ft(e){let t=$n(),n,r,o=[];for(let i=0;i<e.length;i+=1){let s=e[i],a=s.item_hash_version;if(fd(a)){o.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${i+1}`);let f=Mt(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=Mt(t,s.patch);if(!c.ok)return{ok:!1,errors:[...o,`verify_failed:patch_apply_failed:entry_${i+1}`]};let d=Pw(a,r).filter(f=>Ie(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=>Ie(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 $t(e){let t=Ft(e);return{ok:t.ok,errors:t.errors}}function ud(e,t){try{return{ok:!0,document:hs.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function Lw(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Un(t)){let c=ud(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=ud(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 ws(e){let t=Dw(e);if(t.length===1)return t[0];let n=Ft(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:je}function mo(e,t=ws(e)){let n=e.findIndex(u=>fd(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=$n(),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=Ie(r,t),_=Mt(r,f.patch),g,b,E=!1,v=0,I=0;if(_.ok)g=_.document,b=f.patch;else{let D=Lw(r,f.patch);g=D.document,b=hs.compare(r,g),E=!0,v=D.convertedReplaceToAdd,I=D.skippedOps,c+=v,l+=I,a+=1}let T=Ie(g,t),A=p!==f.before_hash||T!==f.after_hash;A&&(s+=1);let L={...f,patch:b,before_hash:p,after_hash:T};d?L.item_hash_version=t:delete L.item_hash_version,o.push(L),i.push({index:u+1,rehashed:A,patch_repaired:E,converted_replace_to_add:v,skipped_ops:I}),r=g}return{entries:o,finalDocument:r,entriesRehashed:s,entriesPatchRepaired:a,convertedReplaceToAdd:c,skippedOps:l,details:i,itemHashVersion:t,explicitItemHashVersion:d}}function _t(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
17
+ ) 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 Rl(e,t){let n=un.dirname(un.dirname(e)),r=Ol(n);try{await ds.access(r)}catch{return}let o=Ub();if(!o)return;let i;try{if(i=new o(r),i.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==Fb)throw new TypeError("Unsupported history event index version");let a=un.basename(e,".jsonl"),c=i.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(a);zb(i,{stream_id:a,stream_offset:Number(c.value),entry:t}),i.close()}catch{i?.close(),await ds.rm(r,{force:!0})}}async function ao(e){await ds.rm(Ol(un.dirname(un.dirname(e))),{force:!0})}import gs from"node:fs/promises";import fn 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]="a3e0573a-01fd-54fb-a568-51c5287b696c")}catch{}})();import{AsyncLocalStorage as Aw}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]="288a7da9-888b-527d-88fb-4711917cec5b")}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]="8ffd2cd5-8b7e-5ae1-a0c6-aab488edb73c")}catch{}})();function Nl(e,t,n){if(e&&t)throw new h(`${n} cannot be combined with --full`,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]="d3329fac-693d-566c-a30a-43f8fb37938f")}catch{}})();var qb=1,Bb=4096;var BP=Object.freeze({version:qb,max_length:Bb});(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 co=[...[["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"}))],Vb=Object.fromEntries(co.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));(function(){try{var e=typeof window<"u"?window:typeof 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 Wb=[...Tn],Kb=[...Er],Yb=[...li],Xb=[...di],Jb=[...ui],Zb=[...fi],lo=["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"];var Dl=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Pl=["upgrade"],Ll=["reopen"],Ml={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},gt=Object.freeze(lo.flatMap(e=>e in Ml?[]:e==="extension"||e==="package"?[...Dl.map(t=>`${e}-${t}`),...e==="package"?Pl.map(t=>`package-${t}`):[],e]:e==="item"?Ll.map(t=>`item-${t}`):[e])),Fl=Object.freeze(co.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&gt.includes(e.alias)).map(e=>e.alias)),Qb=Object.freeze(gt.filter(e=>!Fl.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 $l=["full","compact","brief","summary","counts"];var jl=["error","warning","validation_summary","recovery_bundle"],Ul=["full","omit_explanation","limit_collections","compact_recovery","action_only"],ew=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"]),tw=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),nw=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),rw={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},ow=3,iw=2,sw=192,aw={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},zl=jl.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:aw[e],minimum_max_estimated_tokens:sw,degradation_ladder:Ul,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),QP=new Map(zl.map(e=>[e.diagnostic_class,e]));function ql(e){let[t=""]=e.trim().split(/\s+/u);return ew.has(t)?"mutation":tw.has(t)?"discovery":nw.has(t)?"governance":"read"}function Bl(e,t=ql(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=rw[t];return Gl({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*ow/iw)},degradation_ladder:$l,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function Gl(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 Hl=lo.map(e=>Bl(e)),eL=new Map(Hl.map(e=>[e.command,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]="9e63b4b0-09a5-50bf-9f56-5f239c75ffe5")}catch{}})();var lw=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"]),dw=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:lw}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});(function(){try{var e=typeof window<"u"?window:typeof 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 Vl=256,uo=1e4,fw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,pw=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u;var pL=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&fw.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Vl,reason:`token_budget must be a safe integer of at least ${Vl}.`},{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<=uo&&e.seen_item_ids.every(t=>typeof t=="string"&&pw.test(t)),reason:`seen_item_ids must contain at most ${uo} portable item identifiers.`}];(function(){try{var e=typeof window<"u"?window:typeof 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 Wl=["include","amount","cost","encoding"],Kl=["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"],ww=["canonical","legacy","intent","default"],us={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"};var Yl=Object.freeze(Wl.map(e=>us[e])),Xl=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Jl={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:{}},Zl=new Set(["--collapse","--fields","--section"]),fs=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 Ql(e){return e.slice(2).replaceAll("-","_")}function vw(e,t){let n=fs[e];if(n!==void 0)return n;let r=t==="include"?Zl.has(e)?"<csv>":Ql(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${us[t]} ${r}.`}function Ew(e){let t=Jl[e],n=Object.freeze(Object.fromEntries(Wl.map(r=>[r,Object.freeze({dimension:r,canonical_option:us[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:fs[o]===void 0?"replacement":"behavior_preserving",migration_hint:vw(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:ww,budget_retention_policy:e==="assurance"?"verdict_priority":"ordered_prefix",projection_modes:Object.freeze([...Tw(e).keys()])})}var kw=Object.freeze(Kl.map(Ew)),LL=new Map(kw.map(e=>[e.command,e]));function Un(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 Kl.includes(i)?i:void 0}function Tw(e){let t=Un(e);return t?new Map((Jl[t].include??[]).filter(n=>!Zl.has(n)&&fs[n]===void 0).map(n=>[Ql(n),Sw(n)])):new Map}function Sw(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}(function(){try{var e=typeof window<"u"?window:typeof 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 XL=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"}]),JL=new Aw;(function(){try{var e=typeof window<"u"?window:typeof 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{}})();import{encode as yM}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 bM=new Set(Object.values(g));var ed=!1;function ps(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function Cw(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.SUCCESS)}function Iw(){(process.exitCode===void 0||process.exitCode===g.SUCCESS)&&(process.exitCode=g.GENERIC_FAILURE)}function ms(e){if(e==="stdout"){Cw();return}Iw()}function td(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function Ow(){ed||(ed=!0,process.stdout.on("error",e=>{if(ps(e)){ms("stdout");return}td(e)}),process.stderr.on("error",e=>{if(ps(e)){ms("stderr");return}td(e)}))}function Rw(e,t){Ow();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(ps(n))return ms(e),!1;throw n}}function _s(e){return Rw("stderr",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]="5121b339-6594-58ec-b479-11cbf7dafd27")}catch{}})();var Nw=fn.join("runtime","history-drift-cache.json"),rd={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 od(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function hs(e){let t=fn.join(e,Nw),n=!1,r="invalid_cache_path";try{n=(await gs.stat(await gs.realpath(e))).isDirectory()}catch(o){let i=od(o);r=i===void 0?"unknown":rd[i]??"filesystem_error"}if(!n){_s(`[pm] warning: history_drift_cache_invalidation_failed:${r}
18
+ `);return}try{await gs.rm(t,{force:!0})}catch(o){let i=od(o);if(K(o))return;let s=i===void 0?"unknown":rd[i]??"filesystem_error";_s(`[pm] warning: history_drift_cache_invalidation_failed:${s}
19
+ `)}}async function et(e){let t=fn.dirname(fn.resolve(e));fn.basename(t)==="history"&&await hs(fn.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 Ve=3,Ie=[1,2,3];function fo(e,t){return(e??"").localeCompare(t??"")}function id(e,t){return(e??0)-(t??0)}function ht(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function Dw(e,t){return[e.scope.localeCompare(t.scope),fo(e.path,t.path),fo(e.command,t.command),id(e.timeout_seconds,t.timeout_seconds),fo(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,ht(e.env_clear,t.env_clear,[]),ht(e.env_set,t.env_set,{}),ht(e.assert_stdout_contains,t.assert_stdout_contains,[]),ht(e.assert_stdout_regex,t.assert_stdout_regex,[]),ht(e.assert_stderr_contains,t.assert_stderr_contains,[]),ht(e.assert_stderr_regex,t.assert_stderr_regex,[]),id(e.assert_stdout_min_lines,t.assert_stdout_min_lines),ht(e.assert_json_field_equals,t.assert_json_field_equals,{}),ht(e.assert_json_field_gte,t.assert_json_field_gte,{}),fo(e.note,t.note)].find(r=>r!==0)??0}function Pw(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function Lw(e,t){let n=Pw(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 Mw(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!Lw(r,o.path)?{...o,op:"add"}:o;n.push(i),r=dd.applyPatch(r,[i],!0,!0).newDocument}return n}function mo(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let o=we(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(Dw)}:s;return{front_matter:lt(a,Se),body:o.body}}function sd(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let n=we(e);return{metadata:lt(n.metadata,Se),body:n.body}}function ud(e,t){if(!Ie.some(n=>n===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return ae(R(mo(e,t)))}function _o(e,t){let n=ud(e,t);return t===2?[n,ae(R(mo(e,t,!0)))]:[n]}function zn(e){let t=mo(e.before,Ve),n=mo(e.after,Ve),r=sd(e.before),o=sd(e.after),i=dd.compare(r,o),s=Mw(r,i),a=Il(e.author),c=a.harness?Object.fromEntries(Object.entries(cs().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??Cl(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:ae(R(t)),after_hash:ae(R(n)),item_hash_version:Ve,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}}}function ad(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Fw(e){let t=e.ts.trim();return t.length>0?t:q()}function cd(e,t){let n=e.ts;return typeof n=="string"&&n.trim().length>0?e:{...e,ts:t}}function po(e,t){let n=Fw(t);if(typeof e=="string"){try{let r=JSON.parse(e);if(ad(r))return JSON.stringify(cd(r,n))}catch{}return e}return ad(e)?JSON.stringify(cd(e,n)):JSON.stringify(e)}async function go(e,t){let n=await Ge("history_append",{history_path:e,entry:t});if(n.handled){if(n.result===!1)return;if(typeof n.result=="string"){await en(e,po(n.result,t)),await et(e),await ao(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 en(o,po(r.line,t)),await et(o),await ao(o);return}await en(o,po(r.entry??t,t)),await et(o),await ao(o);return}}await en(e,po(t,t)),await et(e),await Rl(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]="c9488ed4-8228-5e7c-9717-69dd7a3275c4")}catch{}})();var bs={metadata:{},body:""};function qn(){return structuredClone(bs)}function yt(e,t){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return _o(Bn(e),t)}catch{}let n=ae(R({replay_fallback:!0,metadata:e.metadata,body:e.body}));return t===2?[n,n]:[n]}function md(e,t,n,r){let o=yt(e,n),i=yt(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 Bn(e){return{metadata:e.metadata,body:e.body}}function ws(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=we(e);return{metadata:lt(t.metadata,Se),body:t.body}}function fd(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function $w(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function Gn(e){return Array.isArray(e)?e.filter($w).map(t=>({...t,path:fd(t.path),from:typeof t.from=="string"?fd(t.from):void 0})):[]}function jw(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 pn(e,t){try{let n=Gn(t),r=ys.applyPatch(structuredClone(e),n,!0,!1).newDocument;return jw(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 Uw(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Ie.includes(t)))]}function _d(e){return e!==void 0&&!Ie.includes(e)}function zw(e,t){return e!==void 0?[e]:t===void 0?[...Ie]:[t]}function Ut(e){let t=qn(),n,r,o=[];for(let i=0;i<e.length;i+=1){let s=e[i],a=s.item_hash_version,c=_d(a);c&&o.push(`verify_failed:unsupported_item_hash_version:${String(a)}:entry_${i+1}`);let l=pn(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=zw(a,r).map(_=>({version:_,match:md(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 zt(e){let t=Ut(e);return{ok:t.ok,errors:t.errors}}function pd(e,t){try{return{ok:!0,document:ys.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function qw(e,t){let n=structuredClone(e),r=0,o=0;for(let a of Gn(t)){let c=pd(n,a);if(c.ok){n=c.document;continue}if(a.op==="replace"){let l=pd(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 vs(e){let t=Uw(e);if(t.length===1)return t[0];let n=Ut(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Ve}function ho(e,t=vs(e),n={}){let r=e.findIndex(p=>_d(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=qn(),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=pn(o,_.patch),b,E,v=!1,C=0,k=0;if(y.ok)b=y.document,E=_.patch;else{let J=qw(o,_.patch);b=J.document,E=ys.compare(o,b),v=!0,C=J.convertedReplaceToAdd,k=J.skippedOps,l+=C,d+=k,c+=1}let S=md(o,b,t,_);u===void 0||n.continuousHashSurface!==!0?u=[S.pairIndex,S.beforeIndex,S.afterIndex,Math.min(u??0,S.beforeHashes.length-1)].find(J=>J>=0):u=Math.min(u,S.beforeHashes.length-1);let P=S.beforeHashes[u],M=S.afterHashes[u],L=P!==_.before_hash||M!==_.after_hash;L&&(a+=1);let V={..._,patch:E,before_hash:P,after_hash:M};f?V.item_hash_version=t:delete V.item_hash_version,i.push(V),s.push({index:p+1,rehashed:L,patch_repaired:v,converted_replace_to_add:C,skipped_ops:k}),o=b}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:l,skippedOps:d,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function bt(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
20
20
  `)}
21
- `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="393f6460-bf8b-5479-8e3e-cac6f2680823")}catch{}})();function vs(e,t){let n=Me(e);if(n)throw new y(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,h.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new y(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,h.GENERIC_FAILURE)}}return r}function gt(e){return O({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Mw(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&gt(e[r])===gt(t[r]);)r+=1;return r}function xs(e,t,n){vs(e,"base");let r=vs(t,"ours"),o=vs(n,"theirs"),i=Mw(r,o);if(i===r.length&&i===o.length)return{merged:_t(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:_t(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:_t(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let s=r.slice(i),a=new Set(s.map(gt)),c=o.slice(i).filter(u=>!a.has(gt(u))),l=[...s,...c].sort((u,f)=>{let p=me(u.ts,f.ts);if(p!==0)return p;let _=a.has(gt(u)),g=a.has(gt(f));return _!==g?Number(g)-Number(_):gt(u).localeCompare(gt(f))}),d=mo([...r.slice(0,i),...l]);return{merged:_t(d.entries),strategy:"union_reanchor",common_entries:i,entries_from_ours:s.length,entries_from_theirs:c.length,entries_total:d.entries.length,reanchored:!0}}function Es(e,t){let n=Me(e);if(n)throw new y(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,h.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new y(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,h.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new y(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,h.GENERIC_FAILURE);r.push(a)}return r}function _o(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
21
+ `}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7e8fcddf-09fe-5979-b23a-78915bf7f896")}catch{}})();function Es(e,t){let n=Le(e);if(n)throw new h(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(s)try{let a=JSON.parse(s);if(typeof a!="object"||a===null||Array.isArray(a))throw new TypeError("history entry must be an object");r.push(a)}catch{throw new h(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,g.GENERIC_FAILURE)}}return r}function wt(e){return R({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Bw(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&wt(e[r])===wt(t[r]);)r+=1;return r}function Cs(e,t,n){Es(e,"base");let r=Es(t,"ours"),o=Es(n,"theirs"),i=Bw(r,o);if(i===r.length&&i===o.length)return{merged:bt(r),strategy:"identical",common_entries:i,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===o.length)return{merged:bt(r),strategy:"fast_forward_ours",common_entries:i,entries_from_ours:r.length-i,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(i===r.length)return{merged:bt(o),strategy:"fast_forward_theirs",common_entries:i,entries_from_ours:0,entries_from_theirs:o.length-i,entries_total:o.length,reanchored:!1};let s=r.slice(i),a=new Set(s.map(wt)),c=o.slice(i).filter(u=>!a.has(wt(u))),l=[...s,...c].sort((u,f)=>{let p=me(u.ts,f.ts);if(p!==0)return p;let _=a.has(wt(u)),y=a.has(wt(f));return _!==y?Number(y)-Number(_):wt(u).localeCompare(wt(f))}),d=ho([...r.slice(0,i),...l],void 0,{continuousHashSurface:!0});if(d.skippedOps>0)throw new h(`History union cannot preserve ${d.skippedOps} patch operation(s) after deterministic suffix ordering; leave the file unresolved for manual recovery.`,g.GENERIC_FAILURE);return{merged:bt(d.entries),strategy:"union_reanchor",common_entries:i,entries_from_ours:s.length,entries_from_theirs:c.length,entries_total:d.entries.length,reanchored:!0}}function ks(e,t){let n=Le(e);if(n)throw new h(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,g.GENERIC_FAILURE);let r=[];for(let[o,i]of e.split(/\r?\n/).entries()){let s=i.trim();if(!s)continue;let a;try{a=JSON.parse(s)}catch{throw new h(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,g.GENERIC_FAILURE)}if(typeof a!="object"||a===null||Array.isArray(a)||typeof a.eventId!="string"||typeof a.sequence!="number")throw new h(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,g.GENERIC_FAILURE);r.push(a)}return r}function yo(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
22
22
  `)}
23
- `}function Fw(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Cs(e,t,n){Es(e,"base");let r=Es(t,"ours"),o=Es(n,"theirs"),i=Math.min(r.length,o.length),s=0;for(;s<i&&r[s].eventId===o[s].eventId;)s+=1;if(s===r.length&&s===o.length)return{merged:_o(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:_o(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:_o(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(f=>f.eventId)),l=o.slice(s).filter(f=>!c.has(f.eventId)),d=[...a,...l].sort((f,p)=>{if(f.timestamp!==void 0&&p.timestamp!==void 0){let b=me(f.timestamp,p.timestamp);if(b!==0)return b}else{if(f.timestamp===void 0&&p.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let _=c.has(f.eventId),g=c.has(p.eventId);return _!==g?Number(g)-Number(_):0}),u=Fw([...r.slice(0,s),...d]);return{merged:_o(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var pd=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],md=["updated_at"];function jt(e,t){return O(e??null)===O(t??null)}function $w(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(d=>O(d))),i=r(t),s=new Set(i.map(d=>O(d))),a=r(n),c=new Set(a.map(d=>O(d))),l=i.filter(d=>{let u=O(d);return!o.has(u)||c.has(u)});for(let d of a){let u=O(d);!s.has(u)&&!o.has(u)&&l.push(d)}return l}function zn(e){if(typeof e!="object"||e===null||Array.isArray(e))return O(e);let{provenance:t,...n}=e;return O(n)}function jw(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function Uw(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(zn)),i=r(t),s=new Set(i.map(zn)),a=r(n),c=new Set(a.map(zn)),l=i.filter(d=>{let u=zn(d);return!o.has(u)||c.has(u)});for(let d of a){let u=zn(d);!s.has(u)&&!o.has(u)&&l.push(jw(d))}return l}function zw(e,t){return me(String(e),String(t))>=0?e:t}function _d(e,t,n,r){return jt(t,n)?{value:t,from_theirs:!1,conflict:!1}:jt(e,t)?{value:n,from_theirs:!0,conflict:!1}:jt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function gd(e,t,n,r,o){let i=_d(e,t,n,r);if(!i.conflict||o==="preferred_side")return i;let s=O(n).localeCompare(O(t))<0;return{value:s?n:t,from_theirs:s,conflict:!0}}function ks(e){return{...e.metadata}}function Ts(e,t,n){try{return be(xe(e,n),n)}catch(r){throw new y(`Item merge input (${t}) is not a readable item document: ${String(r)}`,h.GENERIC_FAILURE)}}function qw(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?Uw(e.baseValue,e.oursValue,e.theirsValue):$w(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,jt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Bw(e){let t=gd(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function Gw(e,t,n,r,o){let i=new Set(pd),s=new Set(md),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,d)=>l.localeCompare(d)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let l of a){let d=e[l],u=t[l],f=n[l];if(!qw({field:l,baseValue:d,oursValue:u,theirsValue:f,unionFieldSet:i,accumulator:c})){if(s.has(l)){c.merged[l]=zw(u,f);continue}Bw({field:l,baseValue:d,oursValue:u,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function Is(e,t,n,r={}){let o=r.preferred??"ours",i=r.conflictResolution??"preferred_side",s=e.trim().length>0,a=Ts(t,"ours",r),c=Ts(n,"theirs",r),l=s?Ts(e,"base",r):a,d=s?ks(l):{},u=ks(a),f=ks(c),{merged:p,conflictFields:_,fieldsFromTheirs:g,unionFields:b,conflictDecisions:E}=Gw(d,u,f,o,i),v=gd(s?l.body:"",a.body,c.body,o,i);return v.conflict?(_.push("body"),E.push({field:"body",base:s?l.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&g.push("body"),{merged:Ot({metadata:p,body:v.value},r),conflict_fields:_,fields_from_theirs:g,union_fields:b,conflict_decisions:E,requested_preference:o,conflict_resolution:i}}function Ss(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function As(e,t){let n=Me(e);if(n)throw new y(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,h.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new y(`JSON merge input (${t}) is not valid JSON.`,h.GENERIC_FAILURE)}}function Hw(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=l=>{let d=new Map;for(let u of l){let f=O(u);d.set(f,(d.get(f)??0)+1)}return d},o=r(e),i=r(t),s=r(n);for(let[l,d]of o)if((i.get(l)??0)<d||(s.get(l)??0)<d)return null;let a=new Map(i),c=[];for(let l of n){let d=O(l),u=a.get(d)??0;u>0?a.set(d,u-1):c.push(l)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Vw(e,t,n,r,o,i,s){if(!Ss(t)||!Ss(n))return null;let a=Ss(e)?e:{},c={},l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u));for(let d of l){let u=o.length>0?`${o}.${d}`:d,f=Ww(a,t,n,d,r,u,i,s);f!==void 0&&(c[d]=f)}return c}function hd(e,t,n,r,o,i,s){if(jt(t,n))return t;let a=Hw(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(o),a.merged;let c=Vw(e,t,n,r,o,i,s);if(c!==null)return c;let l=_d(e,t,n,r);return l.conflict?i.push(o):l.from_theirs&&s.push(o),l.value}function Ww(e,t,n,r,o,i,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),l=Object.prototype.hasOwnProperty.call(n,r),d=Object.prototype.hasOwnProperty.call(e,r);if(c&&l)return hd(e[r],t[r],n[r],o,i,s,a);if(c){if(d&&jt(e[r],t[r])){a.push(i);return}return d?(s.push(i),o==="theirs"?void 0:t[r]):t[r]}if(!(d&&jt(e[r],n[r])))return d?(s.push(i),o==="theirs"?n[r]:void 0):(a.push(i),n[r])}function Os(e,t,n,r={}){let o=r.preferred??"ours",i=As(e,"base"),s=As(t,"ours"),a=As(n,"theirs"),c=[],l=[],d=hd(i,s,a,o,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
24
- `,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as Zw}from"node:child_process";import{randomUUID as Qw}from"node:crypto";import{readdir as ev}from"node:fs/promises";import oe from"node:path";import{promisify as tv}from"node:util";import{constants as yd}from"node:fs";import{lstat as Kw,open as Yw}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]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var Xw={lstat:Kw,open:Yw};function Jw(e){return e.O_NOFOLLOW??0}async function bd(e,t,n=Xw){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let o=await n.open(e,yd.O_RDONLY|Jw(yd));try{let i=await o.stat();if(!i.isFile()||i.size>t)return null;let s=Buffer.alloc(i.size),a=0;for(;a<s.length;){let{bytesRead:l}=await o.read(s,a,s.length-a,a);if(l===0)break;a+=l}return(await o.stat()).size===i.size&&a===i.size?s.toString("utf8",0,a):null}finally{await o.close()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="145a6d31-5e14-5b0b-95fb-6f837d11e2f4")}catch{}})();var nv=tv(Zw),rv=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,ov=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Ns=2048,iv=16*1024*1024,sv=64,av=1e5,cv=new Set(["version","id","item_path","item_id","requested_preference","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","evidence_source"]),lv=new Set(["field","base","ours","theirs","retained","discarded"]);async function Ds(e){try{let{stdout:t}=await nv("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Td(e,t){let n=oe.dirname(oe.resolve(e,t));for(let r=0;r<12;r+=1){if(await B(oe.join(n,"settings.json")))return n;let o=oe.dirname(n);if(o===n)break;n=o}return null}function Ps(e){return oe.join(e,"merge-receipts")}function un(e){return`${e}.json`}function Bn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sd(e,t){return Object.keys(e).every(n=>t.has(n))}function wd(e){return Array.isArray(e)&&e.length<=Ns&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function qn(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>av||r.depth>sv)return!1;if(Array.isArray(r.value))for(let o of r.value)t.push({value:o,depth:r.depth+1});else if(Bn(r.value))for(let o of Object.values(r.value))t.push({value:o,depth:r.depth+1})}return!0}function dv(e){return Bn(e)&&Sd(e,lv)&&typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&Object.hasOwn(e,"base")&&Object.hasOwn(e,"ours")&&Object.hasOwn(e,"theirs")&&Object.hasOwn(e,"retained")&&Object.hasOwn(e,"discarded")&&qn(e.base)&&qn(e.ours)&&qn(e.theirs)&&qn(e.retained)&&qn(e.discarded)}function uv(e){if(!Bn(e))return!1;let t=Object.entries(e);return t.length<=Ns&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function fv(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||oe.posix.isAbsolute(e))return!1;let n=oe.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&oe.posix.basename(n,oe.posix.extname(n))===t}function pv(e){return!Sd(e,cv)||e.version!==1?!1:typeof e.id=="string"&&rv.test(e.id)&&typeof e.item_id=="string"&&ov.test(e.item_id)&&fv(e.item_path,e.item_id)}function mv(e){return!wd(e.fields_from_theirs)||!wd(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Ns||!e.decisions.every(dv)?!1:e.merged_field_hashes===void 0||uv(e.merged_field_hashes)}function _v(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order"],r=[void 0,"clone_local","hash_only"],o=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&o.includes(e.evidence_source)}function gv(e){return typeof e.created_at=="string"&&En(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&En(e.reconciled_at))}function hv(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&Ed(t.retained)&&Ed(t.discarded))}function Ls(e,t){return!Bn(e)||!pv(e)||!mv(e)||!_v(e)||!gv(e)?!1:t!=="durable"||hv(e)}async function Ad(e){return bd(e,iv)}async function vd(e){let t;try{t=await(e.readReceipt??Ad)(e.receiptPath)}catch(i){if(kn(i))return null;throw i}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Ls(n,e.evidenceSource)||n.id!==e.receiptId||oe.basename(e.receiptPath)!==un(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...o}=n;return{path:e.receiptPath,fingerprint:go(n),content:`${JSON.stringify({...o,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
25
- `}}function go(e){return ce(O({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,decisions:We(e).decisions}))}function yv(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function We(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Rs(t.retained)??ce(O(t.retained)),discarded_hash:Rs(t.discarded)??ce(O(t.discarded))}))}}function Rs(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Ed(e){return Bn(e)&&Object.keys(e).length===1&&Rs(e)!==void 0}async function xd(e){let t=await Ds(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,o=oe.basename(r,oe.extname(r)),i={version:1,id:Qw(),item_path:r.replaceAll("\\","/"),item_id:o,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions),state:"pending",created_at:q(),value_availability:"clone_local"};await at(t),await $(oe.join(t,un(i.id)),`${JSON.stringify(i,null,2)}
26
- `);let s=await Td(e.cwd,i.item_path);if(s!==null){let a=Ps(s),c=We(i),l={...i,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await at(a),await $(oe.join(a,un(i.id)),`${JSON.stringify(l,null,2)}
27
- `)}return i}async function kd(e,t){if(!await B(e))return{receipts:[],invalid_evidence_count:0};let n;try{n=await ev(e)}catch{return{receipts:[],invalid_evidence_count:1}}let r=[],o=0;for(let i of n.sort((s,a)=>s.localeCompare(a)))if(i.endsWith(".json"))try{let s=oe.join(e,i),a=await Ad(s);if(a===null){o+=1;continue}let c=JSON.parse(a);if(!Ls(c,t)||i!==un(c.id)){o+=1;continue}let{preferred:l,evidence_source:d,...u}=c,f={...u,requested_preference:c.requested_preference??l??"ours",conflict_resolution:c.conflict_resolution??"preferred_side",evidence_source:t};r.push(f)}catch{o+=1}return{receipts:r,invalid_evidence_count:o}}async function Ut(e,t={}){let n=await Ds(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await kd(n,"clone_local"),o=t.pmRoot??oe.join(e,".agents","pm"),i=await kd(Ps(o),"durable"),s=new Map(i.receipts.map(c=>[c.id,c])),a=0;for(let c of r.receipts){let l=s.get(c.id);if(l!==void 0&&go(l)!==go(c)){s.delete(c.id),a+=1;continue}s.set(c.id,l===void 0?c:yv(c,l))}return{receipts:[...s.values()].filter(c=>(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)).sort((c,l)=>c.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+i.invalid_evidence_count+a}}async function Cd(e,t={}){return(await Ut(e,t)).receipts}function Id(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Ms(e,t,n={}){let r=await Ds(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let o=t.evidence_source??"clone_local";if(!Ls(t,o))throw new Error("Merge receipt trusted settlement input failed schema validation.");let i=q(),s=oe.join(r,un(t.id)),a=await Td(e,t.item_path),c=a===null?null:oe.join(Ps(a),un(t.id)),d=(await Promise.all([vd({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:i}),...c===null?[]:[vd({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:i})]])).filter(f=>f!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=go(t);if(new Set([u,...d.map(f=>f.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let f of d)await $(f.path,f.content)}async function bv(e){let t=await Cd(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:q()}}import{readFile as JE,writeFile as ZE}from"node:fs/promises";import QE 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]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var zt=new Set(Te),wv=Object.freeze({get size(){return zt.size},has(e){return zt.has(e)},entries(){return zt.entries()},keys(){return zt.keys()},values(){return zt.values()},forEach(e,t){zt.forEach(n=>e.call(t,n,n,wv))},[Symbol.iterator](){return zt.values()}});function vv(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ev(e){return typeof e!="string"?null:Li(e)}function kv(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=vv(r.name),i=Ev(r.type);if(!o||!i)continue;let s=t.get(o);if(s&&s.type!==i)throw new y(`Extension item field "${o}" is declared with conflicting types: ${s.type}, ${i}`,h.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 et(e){return[...kv(e).keys()].sort((t,n)=>t.localeCompare(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]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var se={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:se,P=e=>typeof e=="boolean"?{ok:!0,value:e}:se;function j(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?se:{ok:!0,value:t}}function M(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:se}function S(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return se;let r=[];for(let o of n){let i=e(o);if(!i.ok)return se;r.push(i.value)}return{ok:!0,value:r}}}function $s(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}:se}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function ho(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return se;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return se;n[r]=i.value}return{ok:!0,value:n}}}function R(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return se;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return se;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var Tv=R({key:w,values:S(w),required:m(P),aliases:m(S(w)),description:m(w)}),Sv=R({command:M("create","update"),option:w,required:m(P),visible:m(P),enabled:m(P)}),Av=R({name:w,description:m(w),default_status:m(w),folder:m(w),aliases:m(S(w)),required_create_fields:m(S(w)),required_create_repeatables:m(S(w)),options:m(S(Tv)),command_option_policies:m(S(Sv))}),xv=R({id:w,aliases:m(S(w)),roles:m(S(M(...kr))),description:m(w),order:m(j())}),Cv=R({key:w,metadata_key:m(w),front_matter_key:m(w),cli_flag:m(w),cli_aliases:m(S(w)),description:m(w),type:m(M(...Jt)),commands:m(S(M(...Tr))),repeatable:m(P),required:m(P),required_on_create:m(P),required_types:m(S(w)),allow_unset:m(P)}),Iv=e=>{if(!Array.isArray(e)||e.length!==2)return se;let[t,n]=e;return typeof t!="string"||typeof n!="string"?se:{ok:!0,value:[t,n]}},Ov=R({type:w,allowed_transitions:S(Iv)}),Rv=m(R({version:m(j({int:!0})),files:m(R({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(S(xv)),fields:m(S(Cv)),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(S(Ov)),unknown_field_policy:m(M(...Sr))})),Nv=m(R({preset:m(M(...bc)),ownership_enforcement:m(M("none","warn","strict")),create_mode_default:m(M("progressive","strict")),close_validation_default:m(M("off","warn","strict")),require_close_reason:m(P),parent_reference:m(M("warn","strict_error")),metadata_profile:m(M("core","strict","custom")),force_required_for_stale_lock:m(P),create_default_type:m(w),workflow_enforcement:m(M("off","warn","strict")),duplicate_detection_mode:m(M("off","advisory","strict")),duplicate_detection_threshold:m(j({min:0,max:1})),duplicate_detection_limit:m(j({int:!0,min:0,max:20}))})),Dv=R({name:w,disabled:m(P),require_trusted:m(P),require_provenance:m(P),sandbox_profile:m(M("none","restricted","strict")),allowed_capabilities:m(S(w)),blocked_capabilities:m(S(w)),allowed_surfaces:m(S(w)),blocked_surfaces:m(S(w)),allowed_commands:m(S(w)),blocked_commands:m(S(w)),allowed_actions:m(S(w)),blocked_actions:m(S(w)),allowed_services:m(S(w)),blocked_services:m(S(w))}),Fs=M("block","warn"),Pv=e=>typeof e=="string"?Fs(e):R({global:m(Fs),project:m(Fs)})(e),Lv=m(R({mode:m(M("off","warn","enforce")),trust_mode:m(M("off","warn","enforce")),pm_max_version_exceeded_mode:m(Pv),require_provenance:m(P),trusted_extensions:m(S(w)),default_sandbox_profile:m(M("none","restricted","strict")),allowed_extensions:m(S(w)),blocked_extensions:m(S(w)),allowed_capabilities:m(S(w)),blocked_capabilities:m(S(w)),allowed_surfaces:m(S(w)),blocked_surfaces:m(S(w)),allowed_commands:m(S(w)),blocked_commands:m(S(w)),allowed_actions:m(S(w)),blocked_actions:m(S(w)),allowed_services:m(S(w)),blocked_services:m(S(w)),extension_overrides:m(S(Dv))})),qt=$s(128),Mv=R({harness:$s(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(S(qt,64)),model_environment_keys:m(S(qt,64)),session_environment_keys:m(S(qt,64)),provenance_environment_keys:m(ho(S(qt,64))),provenance_resolvers:m(ho(M("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(S(qt,64)),argv_markers:m(S(qt,64)),client_names:m(S(qt,64))}),Fv=R({version:j({int:!0}),id_prefix:w,ids:m(R({token_length:m(j({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(R({probes_enabled:m(P),identity_vocabulary:m(R({version:j({int:!0,positive:!0}),aliases:ho($s(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:S(Mv)})),mutation_guard:m(R({require_attributed_author:m(P),secret_guard:m(M("off","advise","block")),stale_in_progress_hours:m(j({int:!0,positive:!0}))})),item_format:m(M("toon","json_markdown")),locks:R({ttl_seconds:j({int:!0}),wait_ms:m(j({int:!0,min:0}))}),checkpoints:m(R({retention_days:m(j({int:!0,positive:!0}))})),output:R({default_format:M("toon","json")}),ux:m(R({deprecation_hints:m(P)})),history:m(R({missing_stream:M("auto_create","strict_error"),compact_policy:m(R({enabled:m(P),max_entries:m(j({int:!0,positive:!0})),trigger:m(M("health_warn","auto"))}))})),validation:m(R({sprint_release_format:M("warn","strict_error"),parent_reference:m(M("warn","strict_error")),metadata_profile:m(M("core","strict","custom")),metadata_required_fields:m(S(w)),lifecycle_stale_blocker_reason_patterns:m(S(w)),lifecycle_closure_like_blocked_reason_patterns:m(S(w)),lifecycle_closure_like_resolution_patterns:m(S(w)),lifecycle_closure_like_actual_result_patterns:m(S(w)),estimate_defaults_by_type:m(ho(j({int:!0,positive:!0})))})),governance:Nv,workflow:m(R({definition_of_done:S(w)})),testing:m(R({record_results_to_items:P,allow_untrusted_linked_tests:m(P)})),telemetry:m(R({enabled:P,first_run_prompt_completed:m(P),capture_level:m(M("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(j({int:!0,positive:!0}))})),agent_guidance:m(R({prompt_completed:m(P),declined:m(P),declined_at:m(w),template_version:m(j({int:!0,positive:!0})),last_checked_files:m(S(w))})),item_types:m(R({definitions:S(Av)})),schema:Rv,context:m(R({default_depth:m(M("brief","standard","deep")),activity_limit:m(j({int:!0,positive:!0})),stale_threshold_days:m(j({int:!0,positive:!0})),sections:m(R({hierarchy:m(P),activity:m(P),progress:m(P),recently_created:m(P),unparented:m(P),blockers:m(P),files:m(P),workload:m(P),staleness:m(P),tests:m(P)}))})),extensions:R({enabled:S(w),disabled:S(w),policy:Lv}),search:R({score_threshold:j(),hybrid_semantic_weight:m(j()),max_results:j({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(j()),embedding_batch_size:j({int:!0}),embedding_timeout_ms:m(j({int:!0})),scanner_max_batch_retries:j({int:!0}),provider:m(w),corpus_fields:m(S(w)),mutation_refresh_policy:m(M("cache_only","semantic_configured","semantic_auto")),query_expansion:m(R({enabled:m(P),provider:m(w)})),rerank:m(R({enabled:m(P),model:m(w),top_k:m(j({int:!0,positive:!0}))})),bm25:m(R({k1:m(j()),b:m(j())}))}),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 Od(e){let t=Fv(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Gn from"node:path";import tt from"node:fs/promises";import js from"node:path";import{randomUUID as $v}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 jv(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 Pd(e){try{let t=await tt.readFile(e,"utf8");return await Fe({path:e,scope:"project"}),jv(t)}catch(t){return X(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function Us(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Ld(e,t){await ve({path:e,scope:"project",op:t})}function Uv(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:q(),ttl_seconds:n}}async function zv(e,t,n,r){await tt.mkdir(js.dirname(e),{recursive:!0});let o=await tt.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Uv(t,n,r),null,2)}
28
- `,"utf8")}finally{await o.close()}await Ld(e,"lock:create")}async function Md(e,t){try{return await tt.unlink(e),await Ld(e,t),!0}catch{return!1}}function Fd(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 qv(e){return e?.owner?` (owner ${e.owner})`:""}var Bv=25,Gv=200,Hv=250,Vv=3,Wv=".stale-cleanup",$d="owner.json",Kv=1e4,Yv=5*6e4;function Rd(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 Xv(e){let t=process.env.PM_LOCK_WAIT_MS,n=Rd(t);if(n!==void 0)return n;let r=Rd(e);return r!==void 0?r:0}function Jv(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function jd(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new y(`Item ${e} is locked${qv(t)}${r}`,h.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:Hv}})}function Zv(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 Qv(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new y(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function eE(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 Ud(e){try{return eE(await tt.readFile(js.join(e,$d),"utf8"))}catch{return null}}function tE(e){try{return process.kill(e,0),!0}catch(t){return!Us(t,"ESRCH")}}async function zs(e){try{return await tt.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Nd(e,t){let n=await Ud(e);n===null||n.token!==t||await zs(e)}async function Dd(e){try{await tt.mkdir(e)}catch(n){return Us(n,"EEXIST"),null}let t={pid:process.pid,token:$v()};try{await tt.writeFile(js.join(e,$d),`${JSON.stringify(t)}
29
- `,"utf8")}catch{return await zs(e),null}return t}async function nE(e){let t;try{let r=await tt.stat(e);if(t=Date.now()-r.mtimeMs,t<=Kv)return!1}catch(r){return X(r)}let n=await Ud(e);return n!==null&&tE(n.pid)&&t<=Yv?!1:zs(e)}async function rE(e,t){let n=`${e}${Wv}`,r=await Dd(n);if(r!==null)return async()=>Nd(n,r.token);if(!await nE(n))return null;let o=await Dd(n);return o===null?null:async()=>Nd(n,o.token)}async function oE(e){let t=await rE(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await Pd(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!Fd(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Qv(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=Vv)throw jd(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await Md(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function Ue(e,t,n,r,o=!1,i=!0,s){let a=await He("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=Zv(a.result);if(p)return async()=>{await Promise.resolve(p()),await He("lock_release",{pm_root:e,id:t,owner:r})}}let c=al(e,t),l=Xv(s),d=Date.now(),u=0,f=Bv;for(;;)try{return await zv(c,t,r,n),async()=>{await Md(c,"lock:release"),await He("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!Us(p,"EEXIST"))throw new y(`Failed to acquire lock for ${t}: ${Xe(p)}`,h.GENERIC_FAILURE);let _=await Pd(c);if(Fd(_.info,n)){let b=await oE({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 g=Date.now()-d;if(l===0||g>=l)throw jd(t,_.info,l===0?0:g);await Jv(Math.min(f,l-g)),f=Math.min(f*2,Gv)}}(function(){try{var e=typeof window<"u"?window:typeof 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 de="_workspace";function yo(e){return Gn.join(e,"history",`${de}.jsonl`)}function iE(e,t=e.length){let n=$n();for(let r of e.slice(0,t))n=Mt(n,r.patch).document;return jn(n)}function sE(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function aE(e){throw new y(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function cE(e,t){let n=Gn.resolve(t),r=Gn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Gn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function qs(e){let t=await ft(yo(e),de),n=$t(t);n.ok||aE(n.errors);let r=sE(t.length===0?mi:iE(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=cE(e,Gn.resolve(e,c));if(l=await J(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(O(u)===O(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}}(function(){try{var e=typeof window<"u"?window:typeof 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 lE={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},zd=120;function Bs(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Bd(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var dE=Bd(lE),qd=new WeakMap;function uE(e){let t=qd.get(e);if(t)return t;let n=Bd(e);return qd.set(e,n),n}function Gd(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return zd;if(t){let o=uE(t).get(n);if(Bs(o))return Math.floor(o)}let r=dE.get(n);return Bs(r)?Math.floor(r):zd}function Hd(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||!Bs(r)||(t[o]=Math.floor(r))}return t}import{stat as fE}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 bo=new Map;function Vd(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function pE(e){try{let t=await fE(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=Vd(e),n=await Promise.all(t.map(r=>pE(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Hn(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 Wd(e){return bo.get(e)}function wo(e,t){let n=Vd(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));bo.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Bt(e){if(e){bo.delete(e);return}bo.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 Xd=Symbol("pm.settings.persist_source"),_E=128,gE=new Set(["off","advisory","strict"]);function Kd(e){return structuredClone(fi[e])}function hE(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:re.governance.preset}function yE(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),gE.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 Gt(e){let t=e.governance??{},n=hE(t.preset),r=yE(t);if(n==="custom"){let s=Kd("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=Kd(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Jd(){return structuredClone(re)}function bE(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:re.search.mutation_refresh_policy}function wE(e){return typeof e=="boolean"?e:re.search.query_expansion.enabled}function vE(e){return typeof e!="string"?re.search.query_expansion.provider:e.trim()}function EE(e){return typeof e=="boolean"?e:re.search.rerank.enabled}function kE(e){return typeof e!="string"?re.search.rerank.model:e.trim()}function TE(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:re.search.rerank.top_k}function SE(e){if(typeof e!="string")return re.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,_E);return n.length>0?n:re.vector_store.collection_name}function Gs(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function AE(e,t){let n=e.schema,r=Gs(n?.statuses),o=Gs(n?.fields),i=Gs(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:ko(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:ko(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 Zd(e,t){Object.defineProperty(e,Xd,{value:t,writable:!0,configurable:!0,enumerable:!1})}function xE(e){let t=e[Xd];if(!(!t||typeof t!="object"))return t}function Eo(e){let t=structuredClone(e.settings),n=xE(e.settings);return n&&Zd(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function CE(e,t,n){let r=ct(t);return[n,ye(e,r.files.types,_e.types),ye(e,r.files.statuses,_e.statuses),ye(e,r.files.fields,_e.fields),ye(e,r.files.workflows,_e.workflows)]}async function IE(e,t,n){let r=await ht(t);wo(e,{tracked_paths:t,signatures:r,value:Eo(n)})}async function OE(e,t,n){try{await IE(e,t,n)}catch{Bt(e)}}function Yd(e,t){return e.find(n=>n.path===t)}function RE(e,t,n){for(let r of n){let o=Yd(e,r),i=Yd(t,r);if(!o||!i||!Hn([o],[i]))return!1}return!0}async function Hs(e,t,n,r,o){try{let i=await ht(t);if(!RE(r,i,o)){Bt(e);return}wo(e,{tracked_paths:t,signatures:i,value:Eo(n)})}catch{Bt(e)}}function Vn(e){return{settings:Jd(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function NE(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function DE(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function PE(e){let t=re.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:DE(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 LE(e){return e==="off"||e==="warn"||e==="enforce"?e:re.extensions.policy.mode}function ME(e){return e==="off"||e==="warn"||e==="enforce"?e:re.extensions.policy.trust_mode}function Qd(e){return e==="none"||e==="restricted"||e==="strict"?e:re.extensions.policy.default_sandbox_profile}function FE(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=Qd(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 $E(e){let t=new Map;for(let n of e??[]){let r=FE(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Vs(e){return e==="block"||e==="warn"?e:void 0}function jE(e){if(typeof e=="string")return Vs(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Vs(e.global),n=Vs(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function Ee(e,t){return ze(e?.[t]??re.extensions.policy[t])}function UE(e){let t=jE(e?.pm_max_version_exceeded_mode);return{mode:LE(e?.mode),trust_mode:ME(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:Ee(e,"trusted_extensions"),default_sandbox_profile:Qd(e?.default_sandbox_profile),allowed_extensions:Ee(e,"allowed_extensions"),blocked_extensions:Ee(e,"blocked_extensions"),allowed_capabilities:Ee(e,"allowed_capabilities"),blocked_capabilities:Ee(e,"blocked_capabilities"),allowed_surfaces:Ee(e,"allowed_surfaces"),blocked_surfaces:Ee(e,"blocked_surfaces"),allowed_commands:Ee(e,"allowed_commands"),blocked_commands:Ee(e,"blocked_commands"),allowed_actions:Ee(e,"allowed_actions"),blocked_actions:Ee(e,"blocked_actions"),allowed_services:Ee(e,"allowed_services"),blocked_services:Ee(e,"blocked_services"),extension_overrides:$E(e?.extension_overrides??re.extensions.policy.extension_overrides)}}function zE(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 vo(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qE(e){return Array.isArray(e)?e:[]}function BE(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:zE(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:vo(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:vo(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:vo(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:vo(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Hd(e.validation?.estimate_defaults_by_type)}}function GE(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 HE(e,t){return{...t.search,...e.search,mutation_refresh_policy:bE(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:wE(e.search?.query_expansion?.enabled),provider:vE(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:EE(e.search?.rerank?.enabled),model:kE(e.search?.rerank?.model),top_k:TE(e.search?.rerank?.top_k)}}}function VE(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:SE(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function WE(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function KE(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 YE(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function ko(e){let t=(e??[]).map(r=>Br(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 XE(e){let t=Jd(),n=Gt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:WE(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:BE(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:GE(e,t),agent_guidance:PE(e.agent_guidance??t.agent_guidance),item_types:{definitions:ko(e.item_types?.definitions)},schema:ct(e.schema??t.schema),context:KE(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:UE(e.extensions.policy??t.extensions.policy)},search:HE(e,t),providers:YE(e,t),vector_store:VE(e,t)}}async function Wn(e){let t=we(e),n=[t];await Fe({path:t,scope:"project"});let r=Wd(e);if(r){let l=await ht(r.tracked_paths);if(Hn(l,r.signatures))return Eo(r.value)}let o=await ht([t]),i;try{i=await J(t)}catch{return Vn("settings_read_fs_error")}if(i===null){let l=Vn();return await Hs(e,[t],l,o,[t]),l}let s=await ht([t]);if(!Hn(o,s))return Bt(e),Wn(e);let a;try{a=JSON.parse(i)}catch{let l=Vn("settings_read_invalid_json");return await Hs(e,[t],l,s,[t]),l}let c=Od(a);if(!c.success){let l=Vn("settings_read_invalid_schema");return await Hs(e,[t],l,s,[t]),l}try{let l=XE(c.data),d=CE(e,l.schema,t);n=d;let u=await ht(d),f=await Pc(e,l.schema),p=await Lc(e,l.schema),_=await ht(d),g={...l,item_types:{definitions:ko([...l.item_types.definitions,...qE(p.type_definitions_from_file)])},schema:p.schema};Zd(g,AE(c.data,g));let b={settings:g,metadata:{has_explicit_item_format:NE(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?Hn(u,_)?wo(e,{tracked_paths:d,signatures:_,value:Eo(b)}):Bt(e):Bt(e),b}catch{let l=Vn("settings_read_merge_failed");return await OE(e,n,l),l}}async function Q(e){return(await Wn(e)).settings}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8046a5-06aa-58f8-b347-e757086082d1")}catch{}})();var Ks=["item","history","relationship","json"];function ek(e){let t=e.trim().toLowerCase();if(Ks.includes(t))return t;throw new y(`Unknown merge artifact "${e}". Supported values: ${Ks.join(", ")}.`,h.USAGE)}function tk(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new y(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,h.USAGE)}async function Ws(e,t){try{return await JE(e,"utf8")}catch{throw new y(`Cannot read merge ${t} file at ${e}.`,h.NOT_FOUND)}}async function nk(e){let t=ne(process.cwd(),e.path);return await B(we(t))?Q(t):null}function rk(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function ok(e,t){let n=ek(e.artifact),r=tk(e.prefer),o=QE.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Ws(e.basePath,"base"),Ws(e.oursPath,"ours"),Ws(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=xs(i,s,a);c=p.merged,u.history={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="relationship"){let p=Cs(i,s,a);c=p.merged,u.relationship={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="item"){let p=await nk(t),_=rk(e.itemPath??o,p),g=et(V()),b=Is(i,s,a,{format:_,schema:p?.schema,extensionFieldNames:g,preferred:r,conflictResolution:"stable_value_order"});if(c=b.merged,d.push(...b.conflict_fields),u.item={fields_from_theirs:b.fields_from_theirs,union_fields:b.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0){let E=xe(c,{format:_,schema:p?.schema,extensionFieldNames:g}),v=E.metadata,I=[...new Set([...b.fields_from_theirs,...b.union_fields,...b.conflict_decisions.map(T=>T.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:b.fields_from_theirs,unionFields:b.union_fields,mergedFieldHashes:Object.fromEntries(I.map(T=>[T,ce(O(T==="body"?E.body:v[T]))])),decisions:b.conflict_decisions}}}else{let p=Os(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await ZE(o,c,"utf8"),l!==void 0){let p=await xd(l);p!==null&&(u.receipt=We(p))}let f=[];if(d.length>0){let p=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${d.join(", ")}; the item driver kept the direction-independent stable value. ${p} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:d,...u,guidance:f,generated_at:q()}}import Xs from"node:fs/promises";import To 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 yt(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Js(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 So(e){return new y(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function Ys(e){return new y(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function ik(e){let t=To.resolve(e),n=To.parse(t).root,r=To.dirname(t);for(;r!==n;){let o;try{o=await Xs.stat(r)}catch(i){if(yt(i,"ENOTDIR"))throw So(e);if(!yt(i,"ENOENT"))throw i;r=To.dirname(r);continue}if(!o.isDirectory())throw So(e);return}}async function Kn(e){let t;try{t=await Xs.stat(e)}catch(n){throw yt(n,"ENOENT")?(await ik(e),new y(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:Js(e)})):yt(n,"ENOTDIR")?So(e):yt(n,"EACCES")||yt(n,"EPERM")?Ys(e):n}if(!t.isDirectory())throw So(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Ys(e);try{await(await Xs.opendir(e)).close()}catch(n){throw yt(n,"EACCES")||yt(n,"EPERM")?Ys(e):n}}async function Oe(e){if(await Kn(e),!await B(we(e)))throw new y(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:Js(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]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{readFile as xo,realpath as Zs,writeFile as lk}from"node:fs/promises";import{execFile as dk}from"node:child_process";import K from"node:path";import{promisify as uk}from"node:util";import sk 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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var eu=["runtime/","search/","locks/","transactions/","checkpoints/"];function tu(e){let t=e.replaceAll("\\","/");return sk.isAbsolute(e)||t===".."||t.startsWith("../")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var ak="PM_SOURCE_CONTEXT_ACCESS",ck="PM_ALLOW_SOURCE_CONTEXT_WRITES";function nu(e){let t=e[ak],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[ck]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||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]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var Qs=uk(dk),Yn="# pm-cli:merge-drivers:start",ea="# pm-cli:merge-drivers:end",Ht="# pm-cli:merge-drivers:v2:start",Ao="# pm-cli:merge-drivers:v2:end",fk="merge-fence";function ru(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function su(){let e=on(import.meta.url,["../../.."]);return`${ru(process.execPath)} ${ru(K.join(e,"dist","cli.js"))}`}var au=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function cu(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=nu(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=ne(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:K.resolve(r),workspace_start:K.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?ne(e.cwd,".agents/pm"):ne(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function bt(e){try{let{stdout:t}=await Qs("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Zs(t.trim())}catch{return null}}async function lu(e){let t=await bt(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function ta(e,t){return K.relative(e,t).replaceAll("\\","/")}function Ke(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function ou(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function pk(e,t){let n=ou(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=ou(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(K.basename(n.value))||K.basename(r.value)!=="cli.js"||K.basename(K.dirname(r.value))!=="dist"||!await B(n.value)||!await B(r.value))return!1;try{let o=K.dirname(K.dirname(r.value)),i=JSON.parse(await xo(K.join(o,"package.json"),"utf8")),s=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Co(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ke(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ke(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${Ke(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${Ke(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ke(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ke(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ke(`${n}settings.json`)} merge=pm-json`),r.push(`${Ke(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ke(`${n}extensions/**`)} -merge`),r.push(`${Ke(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function iu(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function du(e,t,n){let r=K.join(e,".gitattributes"),o="";try{o=await xo(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&X(l)))throw l}let i=[Ht,...t,Ao].join(`
30
- `),a=iu(iu(o,Ht,Ao),Yn,ea).trimEnd(),c=`${a.length>0?`${a}
23
+ `}function Gw(e){return e.map((t,n)=>({...t,sequence:n+1}))}function Is(e,t,n){ks(e,"base");let r=ks(t,"ours"),o=ks(n,"theirs"),i=Math.min(r.length,o.length),s=0;for(;s<i&&r[s].eventId===o[s].eventId;)s+=1;if(s===r.length&&s===o.length)return{merged:yo(r),strategy:"identical",common_entries:s,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===o.length)return{merged:yo(r),strategy:"fast_forward_ours",common_entries:s,entries_from_ours:r.length-s,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(s===r.length)return{merged:yo(o),strategy:"fast_forward_theirs",common_entries:s,entries_from_ours:0,entries_from_theirs:o.length-s,entries_total:o.length,reanchored:!1};let a=r.slice(s),c=new Set(a.map(f=>f.eventId)),l=o.slice(s).filter(f=>!c.has(f.eventId)),d=[...a,...l].sort((f,p)=>{if(f.timestamp!==void 0&&p.timestamp!==void 0){let b=me(f.timestamp,p.timestamp);if(b!==0)return b}else{if(f.timestamp===void 0&&p.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let _=c.has(f.eventId),y=c.has(p.eventId);return _!==y?Number(y)-Number(_):0}),u=Gw([...r.slice(0,s),...d]);return{merged:yo(u),strategy:"union_reanchor",common_entries:s,entries_from_ours:a.length,entries_from_theirs:l.length,entries_total:u.length,reanchored:!0}}var gd=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],hd=["updated_at"];function qt(e,t){return R(e??null)===R(t??null)}function Hw(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(d=>R(d))),i=r(t),s=new Set(i.map(d=>R(d))),a=r(n),c=new Set(a.map(d=>R(d))),l=i.filter(d=>{let u=R(d);return!o.has(u)||c.has(u)});for(let d of a){let u=R(d);!s.has(u)&&!o.has(u)&&l.push(d)}return l}function Hn(e){if(typeof e!="object"||e===null||Array.isArray(e))return R(e);let{provenance:t,...n}=e;return R(n)}function Vw(e){if(typeof e!="object"||e===null||Array.isArray(e))return e;let t=e;return t.provenance?{...t,provenance:{...t.provenance,source_kind:"merge_union"}}:{...t,provenance:{source_kind:"merge_union"}}}function Ww(e,t,n){let r=d=>Array.isArray(d)?d:[],o=new Set(r(e).map(Hn)),i=r(t),s=new Set(i.map(Hn)),a=r(n),c=new Set(a.map(Hn)),l=i.filter(d=>{let u=Hn(d);return!o.has(u)||c.has(u)});for(let d of a){let u=Hn(d);!s.has(u)&&!o.has(u)&&l.push(Vw(d))}return l}function Kw(e,t){return me(String(e),String(t))>=0?e:t}function yd(e,t,n,r){return qt(t,n)?{value:t,from_theirs:!1,conflict:!1}:qt(e,t)?{value:n,from_theirs:!0,conflict:!1}:qt(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function bd(e,t,n,r,o){let i=yd(e,t,n,r);if(!i.conflict||o==="preferred_side")return i;let s=R(n).localeCompare(R(t))<0;return{value:s?n:t,from_theirs:s,conflict:!0}}function Ts(e){return{...e.metadata}}function Ss(e,t,n){try{return we(Ce(e,n),n)}catch(r){throw new h(`Item merge input (${t}) is not a readable item document: ${String(r)}`,g.GENERIC_FAILURE)}}function Yw(e){if(!e.unionFieldSet.has(e.field))return!1;let t=e.field==="tests"?Ww(e.baseValue,e.oursValue,e.theirsValue):Hw(e.baseValue,e.oursValue,e.theirsValue);return e.accumulator.merged[e.field]=t,qt(t,e.oursValue)||e.accumulator.unionFields.push(e.field),!0}function Xw(e){let t=bd(e.baseValue,e.oursValue,e.theirsValue,e.preferred,e.conflictResolution);t.value!==void 0&&(e.accumulator.merged[e.field]=t.value),t.conflict?(e.accumulator.conflictFields.push(e.field),e.accumulator.conflictDecisions.push({field:e.field,base:e.baseValue,ours:e.oursValue,theirs:e.theirsValue,retained:t.value,discarded:t.from_theirs?e.oursValue:e.theirsValue})):t.from_theirs&&e.accumulator.fieldsFromTheirs.push(e.field)}function Jw(e,t,n,r,o){let i=new Set(gd),s=new Set(hd),a=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((l,d)=>l.localeCompare(d)),c={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let l of a){let d=e[l],u=t[l],f=n[l];if(!Yw({field:l,baseValue:d,oursValue:u,theirsValue:f,unionFieldSet:i,accumulator:c})){if(s.has(l)){c.merged[l]=Kw(u,f);continue}Xw({field:l,baseValue:d,oursValue:u,theirsValue:f,preferred:r,conflictResolution:o,accumulator:c})}}return c}function Os(e,t,n,r={}){let o=r.preferred??"ours",i=r.conflictResolution??"preferred_side",s=e.trim().length>0,a=Ss(t,"ours",r),c=Ss(n,"theirs",r),l=s?Ss(e,"base",r):a,d=s?Ts(l):{},u=Ts(a),f=Ts(c),{merged:p,conflictFields:_,fieldsFromTheirs:y,unionFields:b,conflictDecisions:E}=Jw(d,u,f,o,i),v=bd(s?l.body:"",a.body,c.body,o,i);return v.conflict?(_.push("body"),E.push({field:"body",base:s?l.body:"",ours:a.body,theirs:c.body,retained:v.value,discarded:v.from_theirs?a.body:c.body})):v.from_theirs&&y.push("body"),{merged:Pt({metadata:p,body:v.value},r),conflict_fields:_,fields_from_theirs:y,union_fields:b,conflict_decisions:E,requested_preference:o,conflict_resolution:i}}function As(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function xs(e,t){let n=Le(e);if(n)throw new h(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,g.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new h(`JSON merge input (${t}) is not valid JSON.`,g.GENERIC_FAILURE)}}function Zw(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=l=>{let d=new Map;for(let u of l){let f=R(u);d.set(f,(d.get(f)??0)+1)}return d},o=r(e),i=r(t),s=r(n);for(let[l,d]of o)if((i.get(l)??0)<d||(s.get(l)??0)<d)return null;let a=new Map(i),c=[];for(let l of n){let d=R(l),u=a.get(d)??0;u>0?a.set(d,u-1):c.push(l)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Qw(e,t,n,r,o,i,s){if(!As(t)||!As(n))return null;let a=As(e)?e:{},c={},l=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((d,u)=>d.localeCompare(u));for(let d of l){let u=o.length>0?`${o}.${d}`:d,f=ev(a,t,n,d,r,u,i,s);f!==void 0&&(c[d]=f)}return c}function wd(e,t,n,r,o,i,s){if(qt(t,n))return t;let a=Zw(e,t,n);if(a!==null)return a.acceptedTheirs&&s.push(o),a.merged;let c=Qw(e,t,n,r,o,i,s);if(c!==null)return c;let l=yd(e,t,n,r);return l.conflict?i.push(o):l.from_theirs&&s.push(o),l.value}function ev(e,t,n,r,o,i,s,a){let c=Object.prototype.hasOwnProperty.call(t,r),l=Object.prototype.hasOwnProperty.call(n,r),d=Object.prototype.hasOwnProperty.call(e,r);if(c&&l)return wd(e[r],t[r],n[r],o,i,s,a);if(c){if(d&&qt(e[r],t[r])){a.push(i);return}return d?(s.push(i),o==="theirs"?void 0:t[r]):t[r]}if(!(d&&qt(e[r],n[r])))return d?(s.push(i),o==="theirs"?n[r]:void 0):(a.push(i),n[r])}function Rs(e,t,n,r={}){let o=r.preferred??"ours",i=xs(e,"base"),s=xs(t,"ours"),a=xs(n,"theirs"),c=[],l=[],d=wd(i,s,a,o,"",c,l);return{merged:`${JSON.stringify(d??null,null,2)}
24
+ `,conflict_paths:c,paths_from_theirs:l,preferred:o}}import{execFile as iv}from"node:child_process";import{randomUUID as sv}from"node:crypto";import{readdir as av}from"node:fs/promises";import ie from"node:path";import{promisify as cv}from"node:util";import{constants as vd}from"node:fs";import{lstat as tv,open as nv}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]="6ece0e15-aff5-5e2d-b18a-16ffaa0fe2ea")}catch{}})();var rv={lstat:tv,open:nv};function ov(e){return e.O_NOFOLLOW??0}async function Ed(e,t,n=rv){let r=await n.lstat(e);if(r.isSymbolicLink()||!r.isFile()||r.size>t)return null;let o=await n.open(e,vd.O_RDONLY|ov(vd));try{let i=await o.stat();if(!i.isFile()||i.size>t)return null;let s=Buffer.alloc(i.size),a=0;for(;a<s.length;){let{bytesRead:l}=await o.read(s,a,s.length-a,a);if(l===0)break;a+=l}return(await o.stat()).size===i.size&&a===i.size?s.toString("utf8",0,a):null}finally{await o.close()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="624fc190-4c46-5a55-b757-72e621aec35d")}catch{}})();var lv=cv(iv),dv=/^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u,uv=/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/u,Ds=2048,fv=16*1024*1024,pv=64,mv=1e5,_v=new Set(["version","id","item_path","item_id","requested_preference","preferred","conflict_resolution","fields_from_theirs","union_fields","merged_field_hashes","decisions","state","created_at","reconciled_at","value_availability","evidence_source"]),gv=new Set(["field","base","ours","theirs","retained","discarded"]);async function Ps(e){try{let{stdout:t}=await lv("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function xd(e,t){let n=ie.dirname(ie.resolve(e,t));for(let r=0;r<12;r+=1){if(await B(ie.join(n,"settings.json")))return n;let o=ie.dirname(n);if(o===n)break;n=o}return null}function Ls(e){return ie.join(e,"merge-receipts")}function mn(e){return`${e}.json`}function Wn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cd(e,t){return Object.keys(e).every(n=>t.has(n))}function kd(e){return Array.isArray(e)&&e.length<=Ds&&e.every(t=>typeof t=="string"&&t.length>0&&t.length<=256)}function Vn(e){let t=[{value:e,depth:0}],n=0;for(;t.length>0;){let r=t.pop();if(n+=1,n>mv||r.depth>pv)return!1;if(Array.isArray(r.value))for(let o of r.value)t.push({value:o,depth:r.depth+1});else if(Wn(r.value))for(let o of Object.values(r.value))t.push({value:o,depth:r.depth+1})}return!0}function hv(e){return Wn(e)&&Cd(e,gv)&&typeof e.field=="string"&&e.field.length>0&&e.field.length<=256&&Object.hasOwn(e,"base")&&Object.hasOwn(e,"ours")&&Object.hasOwn(e,"theirs")&&Object.hasOwn(e,"retained")&&Object.hasOwn(e,"discarded")&&Vn(e.base)&&Vn(e.ours)&&Vn(e.theirs)&&Vn(e.retained)&&Vn(e.discarded)}function yv(e){if(!Wn(e))return!1;let t=Object.entries(e);return t.length<=Ds&&t.every(([n,r])=>n.length>0&&n.length<=256&&typeof r=="string"&&/^[a-f0-9]{64}$/u.test(r))}function bv(e,t){if(typeof e!="string"||e.length===0||e.length>4096||e.includes("\0")||e.includes("\\")||ie.posix.isAbsolute(e))return!1;let n=ie.posix.normalize(e);return n!==".."&&!n.startsWith("../")&&ie.posix.basename(n,ie.posix.extname(n))===t}function wv(e){return!Cd(e,_v)||e.version!==1?!1:typeof e.id=="string"&&dv.test(e.id)&&typeof e.item_id=="string"&&uv.test(e.item_id)&&bv(e.item_path,e.item_id)}function vv(e){return!kd(e.fields_from_theirs)||!kd(e.union_fields)||!Array.isArray(e.decisions)||e.decisions.length>Ds||!e.decisions.every(hv)?!1:e.merged_field_hashes===void 0||yv(e.merged_field_hashes)}function Ev(e){let t=[void 0,"ours","theirs"],n=[void 0,"preferred_side","stable_value_order"],r=[void 0,"clone_local","hash_only"],o=[void 0,"clone_local","durable"];return t.includes(e.requested_preference)&&t.includes(e.preferred)&&n.includes(e.conflict_resolution)&&(e.state==="pending"||e.state==="reconciled")&&r.includes(e.value_availability)&&o.includes(e.evidence_source)}function kv(e){return typeof e.created_at=="string"&&An(e.created_at)&&(e.reconciled_at===void 0||typeof e.reconciled_at=="string"&&An(e.reconciled_at))}function Tv(e){return e.value_availability==="hash_only"&&e.decisions.every(t=>t.base===null&&t.ours===null&&t.theirs===null&&Sd(t.retained)&&Sd(t.discarded))}function Ms(e,t){return!Wn(e)||!wv(e)||!vv(e)||!Ev(e)||!kv(e)?!1:t!=="durable"||Tv(e)}async function Id(e){return Ed(e,fv)}async function Td(e){let t;try{t=await(e.readReceipt??Id)(e.receiptPath)}catch(i){if(xn(i))return null;throw i}if(t===null)throw new Error(`Receipt ${e.receiptId} settlement source is not a bounded regular file.`);let n;try{n=JSON.parse(t)}catch{throw new Error(`Receipt ${e.receiptId} settlement source is not valid JSON.`)}if(!Ms(n,e.evidenceSource)||n.id!==e.receiptId||ie.basename(e.receiptPath)!==mn(n.id))throw new Error(`Receipt ${e.receiptId} settlement source failed schema or identity validation.`);let{evidence_source:r,...o}=n;return{path:e.receiptPath,fingerprint:bo(n),content:`${JSON.stringify({...o,state:"reconciled",reconciled_at:e.reconciledAt},null,2)}
25
+ `}}function bo(e){return ae(R({id:e.id,item_id:e.item_id,item_path:e.item_path,created_at:e.created_at,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution??"preferred_side",fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,merged_field_hashes:e.merged_field_hashes??null,decisions:We(e).decisions}))}function Sv(e,t){if(e.state==="reconciled"&&t.state==="reconciled")return e;let{reconciled_at:n,...r}=e;return{...r,state:"pending"}}function We(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Ns(t.retained)??ae(R(t.retained)),discarded_hash:Ns(t.discarded)??ae(R(t.discarded))}))}}function Ns(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}function Sd(e){return Wn(e)&&Object.keys(e).length===1&&Ns(e)!==void 0}async function Od(e){let t=await Ps(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),r=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,o=ie.basename(r,ie.extname(r)),i={version:1,id:sv(),item_path:r.replaceAll("\\","/"),item_id:o,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],...e.mergedFieldHashes?{merged_field_hashes:{...e.mergedFieldHashes}}:{},decisions:structuredClone(e.decisions),state:"pending",created_at:q(),value_availability:"clone_local"};await dt(t),await j(ie.join(t,mn(i.id)),`${JSON.stringify(i,null,2)}
26
+ `);let s=await xd(e.cwd,i.item_path);if(s!==null){let a=Ls(s),c=We(i),l={...i,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await dt(a),await j(ie.join(a,mn(i.id)),`${JSON.stringify(l,null,2)}
27
+ `)}return i}async function Ad(e,t){let n;try{n=await av(e)}catch(i){return{receipts:[],invalid_evidence_count:K(i)?0:1}}let r=[],o=0;for(let i of n.sort((s,a)=>s.localeCompare(a)))if(i.endsWith(".json"))try{let s=ie.join(e,i),a=await Id(s);if(a===null){o+=1;continue}let c=JSON.parse(a);if(!Ms(c,t)||i!==mn(c.id)){o+=1;continue}let{preferred:l,evidence_source:d,...u}=c,f={...u,requested_preference:c.requested_preference??l??"ours",conflict_resolution:c.conflict_resolution??"preferred_side",evidence_source:t};r.push(f)}catch{o+=1}return{receipts:r,invalid_evidence_count:o}}async function tt(e,t={}){let n=await Ps(e),r=n===null?{receipts:[],invalid_evidence_count:0}:await Ad(n,"clone_local"),o=t.pmRoot??ie.join(e,".agents","pm"),i=await Ad(Ls(o),"durable"),s=new Map(i.receipts.map(c=>[c.id,c])),a=0;for(let c of r.receipts){let l=s.get(c.id);if(l!==void 0&&bo(l)!==bo(c)){s.delete(c.id),a+=1;continue}s.set(c.id,l===void 0?c:Sv(c,l))}return{receipts:[...s.values()].filter(c=>(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)).sort((c,l)=>c.created_at.localeCompare(l.created_at)),invalid_evidence_count:r.invalid_evidence_count+i.invalid_evidence_count+a,clone_local_evidence_resolved:n!==null}}async function Rd(e,t={}){return(await tt(e,t)).receipts}function Nd(e){let t=[],n=[];for(let r of e)(Array.isArray(r.decisions)&&r.decisions.length>0?t:n).push(r);return{pendingDecisions:t,lossless:n}}async function Fs(e,t,n={}){let r=await Ps(e);if(r===null){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let o=t.evidence_source??"clone_local";if(!Ms(t,o))throw new Error("Merge receipt trusted settlement input failed schema validation.");let i=q(),s=ie.join(r,mn(t.id)),a=await xd(e,t.item_path),c=a===null?null:ie.join(Ls(a),mn(t.id)),d=(await Promise.all([Td({receiptPath:s,receiptId:t.id,evidenceSource:"clone_local",reconciledAt:i}),...c===null?[]:[Td({receiptPath:c,receiptId:t.id,evidenceSource:"durable",reconciledAt:i})]])).filter(f=>f!==null);if(d.length===0){if(n.requireExisting===!0)throw new Error(`Receipt ${t.id} disappeared before settlement.`);return}let u=bo(t);if(new Set([u,...d.map(f=>f.fingerprint)]).size!==1)throw new Error(`Receipt ${t.id} settlement copies disagree on immutable merge provenance.`);for(let f of d)await j(f.path,f.content)}async function Av(e){let t=await Rd(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:q()}}async function xv(e){let t=await tt(e.cwd??process.cwd(),{...e,includeLossless:!0}),n=t.clone_local_evidence_resolved===!0&&t.invalid_evidence_count===0;return{ok:n,complete:n,count:t.receipts.length,invalid_evidence_count:t.invalid_evidence_count,clone_local_evidence_resolved:t.clone_local_evidence_resolved,receipts:t.receipts,generated_at:q()}}import{readFile as ik,writeFile as sk}from"node:fs/promises";import ak 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]="ce320988-b999-57c9-a786-a94ac66c5628")}catch{}})();var Bt=new Set(Se),Cv=Object.freeze({get size(){return Bt.size},has(e){return Bt.has(e)},entries(){return Bt.entries()},keys(){return Bt.keys()},values(){return Bt.values()},forEach(e,t){Bt.forEach(n=>e.call(t,n,n,Cv))},[Symbol.iterator](){return Bt.values()}});function Iv(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Ov(e){return typeof e!="string"?null:Fi(e)}function Rv(e){let t=new Map;if(!e)return t;for(let n of e.item_fields)for(let r of n.fields){let o=Iv(r.name),i=Ov(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 nt(e){return[...Rv(e).keys()].sort((t,n)=>t.localeCompare(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]="0e135793-d2ed-505b-b73e-6db55218d8af")}catch{}})();var ce={ok:!1},w=e=>typeof e=="string"?{ok:!0,value:e}:ce,D=e=>typeof e=="boolean"?{ok:!0,value:e}:ce;function U(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?ce:{ok:!0,value:t}}function F(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:ce}function A(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return ce;let r=[];for(let o of n){let i=e(o);if(!i.ok)return ce;r.push(i.value)}return{ok:!0,value:r}}}function js(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}:ce}function m(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function wo(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ce;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return ce;n[r]=i.value}return{ok:!0,value:n}}}function N(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return ce;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return ce;s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var Nv=N({key:w,values:A(w),required:m(D),aliases:m(A(w)),description:m(w)}),Dv=N({command:F("create","update"),option:w,required:m(D),visible:m(D),enabled:m(D)}),Pv=N({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(Nv)),command_option_policies:m(A(Dv))}),Lv=N({id:w,aliases:m(A(w)),roles:m(A(F(...Sr))),description:m(w),order:m(U())}),Mv=N({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(F(...Zt)),commands:m(A(F(...Ar))),repeatable:m(D),required:m(D),required_on_create:m(D),required_types:m(A(w)),allow_unset:m(D)}),Fv=e=>{if(!Array.isArray(e)||e.length!==2)return ce;let[t,n]=e;return typeof t!="string"||typeof n!="string"?ce:{ok:!0,value:[t,n]}},$v=N({type:w,allowed_transitions:A(Fv)}),jv=m(N({version:m(U({int:!0})),files:m(N({types:m(w),statuses:m(w),fields:m(w),workflows:m(w)})),statuses:m(A(Lv)),fields:m(A(Mv)),workflow:m(N({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($v)),unknown_field_policy:m(F(...xr))})),Uv=m(N({preset:m(F(...wc)),ownership_enforcement:m(F("none","warn","strict")),create_mode_default:m(F("progressive","strict")),close_validation_default:m(F("off","warn","strict")),require_close_reason:m(D),parent_reference:m(F("warn","strict_error")),metadata_profile:m(F("core","strict","custom")),force_required_for_stale_lock:m(D),create_default_type:m(w),workflow_enforcement:m(F("off","warn","strict")),duplicate_detection_mode:m(F("off","advisory","strict")),duplicate_detection_threshold:m(U({min:0,max:1})),duplicate_detection_limit:m(U({int:!0,min:0,max:20}))})),zv=N({name:w,disabled:m(D),require_trusted:m(D),require_provenance:m(D),sandbox_profile:m(F("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))}),$s=F("block","warn"),qv=e=>typeof e=="string"?$s(e):N({global:m($s),project:m($s)})(e),Bv=m(N({mode:m(F("off","warn","enforce")),trust_mode:m(F("off","warn","enforce")),pm_max_version_exceeded_mode:m(qv),require_provenance:m(D),trusted_extensions:m(A(w)),default_sandbox_profile:m(F("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(zv))})),Gt=js(128),Gv=N({harness:js(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:m(A(Gt,64)),model_environment_keys:m(A(Gt,64)),session_environment_keys:m(A(Gt,64)),provenance_environment_keys:m(wo(A(Gt,64))),provenance_resolvers:m(wo(F("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:m(A(Gt,64)),argv_markers:m(A(Gt,64)),client_names:m(A(Gt,64))}),Hv=N({version:U({int:!0}),id_prefix:w,ids:m(N({token_length:m(U({int:!0,min:4,max:12}))})),author_default:w,agent_identity:m(N({probes_enabled:m(D),identity_vocabulary:m(N({version:U({int:!0,positive:!0}),aliases:wo(js(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:A(Gv)})),mutation_guard:m(N({require_attributed_author:m(D),secret_guard:m(F("off","advise","block")),stale_in_progress_hours:m(U({int:!0,positive:!0}))})),item_format:m(F("toon","json_markdown")),locks:N({ttl_seconds:U({int:!0}),wait_ms:m(U({int:!0,min:0}))}),checkpoints:m(N({retention_days:m(U({int:!0,positive:!0}))})),output:N({default_format:F("toon","json")}),ux:m(N({deprecation_hints:m(D)})),history:m(N({missing_stream:F("auto_create","strict_error"),compact_policy:m(N({enabled:m(D),max_entries:m(U({int:!0,positive:!0})),trigger:m(F("health_warn","auto"))}))})),validation:m(N({sprint_release_format:F("warn","strict_error"),parent_reference:m(F("warn","strict_error")),metadata_profile:m(F("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(wo(U({int:!0,positive:!0})))})),governance:Uv,workflow:m(N({definition_of_done:A(w)})),testing:m(N({record_results_to_items:D,allow_untrusted_linked_tests:m(D)})),telemetry:m(N({enabled:D,first_run_prompt_completed:m(D),capture_level:m(F("minimal","redacted","max")),endpoint:m(w),installation_id:m(w),retention_days:m(U({int:!0,positive:!0}))})),agent_guidance:m(N({prompt_completed:m(D),declined:m(D),declined_at:m(w),template_version:m(U({int:!0,positive:!0})),last_checked_files:m(A(w))})),item_types:m(N({definitions:A(Pv)})),schema:jv,context:m(N({default_depth:m(F("brief","standard","deep")),activity_limit:m(U({int:!0,positive:!0})),stale_threshold_days:m(U({int:!0,positive:!0})),sections:m(N({hierarchy:m(D),activity:m(D),progress:m(D),recently_created:m(D),unparented:m(D),blockers:m(D),files:m(D),workload:m(D),staleness:m(D),tests:m(D)}))})),extensions:N({enabled:A(w),disabled:A(w),policy:Bv}),search:N({score_threshold:U(),hybrid_semantic_weight:m(U()),max_results:U({int:!0}),embedding_model:w,embedding_corpus_max_characters:m(U()),embedding_batch_size:U({int:!0}),embedding_timeout_ms:m(U({int:!0})),scanner_max_batch_retries:U({int:!0}),provider:m(w),corpus_fields:m(A(w)),mutation_refresh_policy:m(F("cache_only","semantic_configured","semantic_auto")),query_expansion:m(N({enabled:m(D),provider:m(w)})),rerank:m(N({enabled:m(D),model:m(w),top_k:m(U({int:!0,positive:!0}))})),bm25:m(N({k1:m(U()),b:m(U())}))}),providers:N({openai:N({base_url:w,api_key:w,model:w}),ollama:N({base_url:w,model:w})}),vector_store:N({adapter:m(w),collection_name:m(w),qdrant:N({url:w,api_key:w}),lancedb:N({path:w})})});function Dd(e){let t=Hv(e);return t.ok?{success:!0,data:t.value}:{success:!1}}import Kn from"node:path";import rt from"node:fs/promises";import Us from"node:path";import{randomUUID as Vv}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 Wv(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 Fd(e){try{let t=await rt.readFile(e,"utf8");return await Me({path:e,scope:"project"}),Wv(t)}catch(t){return K(t)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function zs(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function $d(e,t){await Ee({path:e,scope:"project",op:t})}function Kv(e,t,n){return{id:e,pid:process.pid,owner:t,created_at:q(),ttl_seconds:n}}async function Yv(e,t,n,r){await rt.mkdir(Us.dirname(e),{recursive:!0});let o=await rt.open(e,"wx");try{await o.writeFile(`${JSON.stringify(Kv(t,n,r),null,2)}
28
+ `,"utf8")}finally{await o.close()}await $d(e,"lock:create")}async function jd(e,t){try{return await rt.unlink(e),await $d(e,t),!0}catch{return!1}}function Ud(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 Xv(e){return e?.owner?` (owner ${e.owner})`:""}var Jv=25,Zv=200,Qv=250,eE=3,tE=".stale-cleanup",zd="owner.json",nE=1e4,rE=5*6e4;function Pd(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 oE(e){let t=process.env.PM_LOCK_WAIT_MS,n=Pd(t);if(n!==void 0)return n;let r=Pd(e);return r!==void 0?r:0}function iE(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}function qd(e,t,n){let r=n>0?` after waiting ${n}ms`:"";return new h(`Item ${e} is locked${Xv(t)}${r}`,g.CONFLICT,{code:"lock_conflict",recovery:{retry_after_ms:Qv}})}function sE(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function aE(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 cE(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 Bd(e){try{return cE(await rt.readFile(Us.join(e,zd),"utf8"))}catch{return null}}function lE(e){try{return process.kill(e,0),!0}catch(t){return!zs(t,"ESRCH")}}async function qs(e){try{return await rt.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function Ld(e,t){let n=await Bd(e);n===null||n.token!==t||await qs(e)}async function Md(e){try{await rt.mkdir(e)}catch(n){return zs(n,"EEXIST"),null}let t={pid:process.pid,token:Vv()};try{await rt.writeFile(Us.join(e,zd),`${JSON.stringify(t)}
29
+ `,"utf8")}catch{return await qs(e),null}return t}async function dE(e){let t;try{let r=await rt.stat(e);if(t=Date.now()-r.mtimeMs,t<=nE)return!1}catch(r){return K(r)}let n=await Bd(e);return n!==null&&lE(n.pid)&&t<=rE?!1:qs(e)}async function uE(e,t){let n=`${e}${tE}`,r=await Md(n);if(r!==null)return async()=>Ld(n,r.token);if(!await dE(n))return null;let o=await Md(n);return o===null?null:async()=>Ld(n,o.token)}async function fE(e){let t=await uE(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await Fd(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};if(!Ud(n.info,e.ttlSeconds))return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(aE(e.id,n,e.force,e.forceRequiredForStaleLock),e.staleRemovals>=eE)throw qd(e.id,n.info,Date.now()-e.startedAtMs);return{lockInfo:n,shouldRetryCreate:await jd(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function $e(e,t,n,r,o=!1,i=!0,s){let a=await Ge("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=sE(a.result);if(p)return async()=>{await Promise.resolve(p()),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}let c=cl(e,t),l=oE(s),d=Date.now(),u=0,f=Jv;for(;;)try{return await Yv(c,t,r,n),async()=>{await jd(c,"lock:release"),await Ge("lock_release",{pm_root:e,id:t,owner:r})}}catch(p){if(!zs(p,"EEXIST"))throw new h(`Failed to acquire lock for ${t}: ${Je(p)}`,g.GENERIC_FAILURE);let _=await Fd(c);if(Ud(_.info,n)){let b=await fE({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 qd(t,_.info,l===0?0:y);await iE(Math.min(f,l-y)),f=Math.min(f*2,Zv)}}(function(){try{var e=typeof window<"u"?window:typeof 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 fe="_workspace";function vo(e){return Kn.join(e,"history",`${fe}.jsonl`)}function pE(e,t=e.length){let n=qn();for(let r of e.slice(0,t))n=pn(n,r.patch).document;return Bn(n)}function mE(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function _E(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 gE(e,t){let n=Kn.resolve(t),r=Kn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Kn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Bs(e){let t=await _t(vo(e),fe),n=zt(t);n.ok||_E(n.errors);let r=mE(t.length===0?hi:pE(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let l;try{let d=gE(e,Kn.resolve(e,c));if(l=await Q(d.absolutePath),l===null){s.push(c);continue}let u=JSON.parse(l);(R(u)===R(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}}(function(){try{var e=typeof window<"u"?window:typeof 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 hE={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Gd=120;function Gs(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function Vd(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var yE=Vd(hE),Hd=new WeakMap;function bE(e){let t=Hd.get(e);if(t)return t;let n=Vd(e);return Hd.set(e,n),n}function Wd(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Gd;if(t){let o=bE(t).get(n);if(Gs(o))return Math.floor(o)}let r=yE.get(n);return Gs(r)?Math.floor(r):Gd}function Kd(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||!Gs(r)||(t[o]=Math.floor(r))}return t}import{stat as wE}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 Eo=new Map;function Yd(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function vE(e){try{let t=await wE(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function vt(e){let t=Yd(e),n=await Promise.all(t.map(r=>vE(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Yn(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 Xd(e){return Eo.get(e)}function ko(e,t){let n=Yd(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));Eo.set(e,{tracked_paths:n,signatures:r,value:t.value})}function Ht(e){if(e){Eo.delete(e);return}Eo.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 Qd=Symbol("pm.settings.persist_source"),kE=128,TE=new Set(["off","advisory","strict"]);function Jd(e){return structuredClone(_i[e])}function SE(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:oe.governance.preset}function AE(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),TE.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 Vt(e){let t=e.governance??{},n=SE(t.preset),r=AE(t);if(n==="custom"){let s=Jd("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=Jd(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function eu(){return structuredClone(oe)}function xE(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:oe.search.mutation_refresh_policy}function CE(e){return typeof e=="boolean"?e:oe.search.query_expansion.enabled}function IE(e){return typeof e!="string"?oe.search.query_expansion.provider:e.trim()}function OE(e){return typeof e=="boolean"?e:oe.search.rerank.enabled}function RE(e){return typeof e!="string"?oe.search.rerank.model:e.trim()}function NE(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:oe.search.rerank.top_k}function DE(e){if(typeof e!="string")return oe.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,kE);return n.length>0?n:oe.vector_store.collection_name}function Hs(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function PE(e,t){let n=e.schema,r=Hs(n?.statuses),o=Hs(n?.fields),i=Hs(n?.type_workflows);return{source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Ao(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:Ao(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 tu(e,t){Object.defineProperty(e,Qd,{value:t,writable:!0,configurable:!0,enumerable:!1})}function LE(e){let t=e[Qd];if(!(!t||typeof t!="object"))return t}function So(e){let t=structuredClone(e.settings),n=LE(e.settings);return n&&tu(t,n),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function ME(e,t,n){let r=ut(t);return[n,be(e,r.files.types,_e.types),be(e,r.files.statuses,_e.statuses),be(e,r.files.fields,_e.fields),be(e,r.files.workflows,_e.workflows)]}async function FE(e,t,n){let r=await vt(t);ko(e,{tracked_paths:t,signatures:r,value:So(n)})}async function $E(e,t,n){try{await FE(e,t,n)}catch{Ht(e)}}function Zd(e,t){return e.find(n=>n.path===t)}function jE(e,t,n){for(let r of n){let o=Zd(e,r),i=Zd(t,r);if(!o||!i||!Yn([o],[i]))return!1}return!0}async function Vs(e,t,n,r,o){try{let i=await vt(t);if(!jE(r,i,o)){Ht(e);return}ko(e,{tracked_paths:t,signatures:i,value:So(n)})}catch{Ht(e)}}function Xn(e){return{settings:eu(),metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function UE(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function zE(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qE(e){let t=oe.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:zE(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 BE(e){return e==="off"||e==="warn"||e==="enforce"?e:oe.extensions.policy.mode}function GE(e){return e==="off"||e==="warn"||e==="enforce"?e:oe.extensions.policy.trust_mode}function nu(e){return e==="none"||e==="restricted"||e==="strict"?e:oe.extensions.policy.default_sandbox_profile}function HE(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=nu(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 VE(e){let t=new Map;for(let n of e??[]){let r=HE(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Ws(e){return e==="block"||e==="warn"?e:void 0}function WE(e){if(typeof e=="string")return Ws(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Ws(e.global),n=Ws(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function ke(e,t){return je(e?.[t]??oe.extensions.policy[t])}function KE(e){let t=WE(e?.pm_max_version_exceeded_mode);return{mode:BE(e?.mode),trust_mode:GE(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:ke(e,"trusted_extensions"),default_sandbox_profile:nu(e?.default_sandbox_profile),allowed_extensions:ke(e,"allowed_extensions"),blocked_extensions:ke(e,"blocked_extensions"),allowed_capabilities:ke(e,"allowed_capabilities"),blocked_capabilities:ke(e,"blocked_capabilities"),allowed_surfaces:ke(e,"allowed_surfaces"),blocked_surfaces:ke(e,"blocked_surfaces"),allowed_commands:ke(e,"allowed_commands"),blocked_commands:ke(e,"blocked_commands"),allowed_actions:ke(e,"allowed_actions"),blocked_actions:ke(e,"blocked_actions"),allowed_services:ke(e,"allowed_services"),blocked_services:ke(e,"blocked_services"),extension_overrides:VE(e?.extension_overrides??oe.extensions.policy.extension_overrides)}}function YE(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 To(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function XE(e){return Array.isArray(e)?e:[]}function JE(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:YE(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:To(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:To(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:To(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:To(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Kd(e.validation?.estimate_defaults_by_type)}}function ZE(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 QE(e,t){return{...t.search,...e.search,mutation_refresh_policy:xE(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:CE(e.search?.query_expansion?.enabled),provider:IE(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:OE(e.search?.rerank?.enabled),model:RE(e.search?.rerank?.model),top_k:NE(e.search?.rerank?.top_k)}}}function ek(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:DE(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function tk(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function nk(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 rk(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Ao(e){let t=(e??[]).map(r=>Gr(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 ok(e){let t=eu(),n=Vt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:tk(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:JE(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:ZE(e,t),agent_guidance:qE(e.agent_guidance??t.agent_guidance),item_types:{definitions:Ao(e.item_types?.definitions)},schema:ut(e.schema??t.schema),context:nk(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:KE(e.extensions.policy??t.extensions.policy)},search:QE(e,t),providers:rk(e,t),vector_store:ek(e,t)}}async function Jn(e){let t=ve(e),n=[t];await Me({path:t,scope:"project"});let r=Xd(e);if(r){let l=await vt(r.tracked_paths);if(Yn(l,r.signatures))return So(r.value)}let o=await vt([t]),i;try{i=await Q(t)}catch{return Xn("settings_read_fs_error")}if(i===null){let l=Xn();return await Vs(e,[t],l,o,[t]),l}let s=await vt([t]);if(!Yn(o,s))return Ht(e),Jn(e);let a;try{a=JSON.parse(i)}catch{let l=Xn("settings_read_invalid_json");return await Vs(e,[t],l,s,[t]),l}let c=Dd(a);if(!c.success){let l=Xn("settings_read_invalid_schema");return await Vs(e,[t],l,s,[t]),l}try{let l=ok(c.data),d=ME(e,l.schema,t);n=d;let u=await vt(d),f=await Lc(e,l.schema),p=await Mc(e,l.schema),_=await vt(d),y={...l,item_types:{definitions:Ao([...l.item_types.definitions,...XE(p.type_definitions_from_file)])},schema:p.schema};tu(y,PE(c.data,y));let b={settings:y,metadata:{has_explicit_item_format:UE(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?Yn(u,_)?ko(e,{tracked_paths:d,signatures:_,value:So(b)}):Ht(e):Ht(e),b}catch{let l=Xn("settings_read_merge_failed");return await $E(e,n,l),l}}async function te(e){return(await Jn(e)).settings}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2c8046a5-06aa-58f8-b347-e757086082d1")}catch{}})();var Ys=["item","history","relationship","json"];function ck(e){let t=e.trim().toLowerCase();if(Ys.includes(t))return t;throw new h(`Unknown merge artifact "${e}". Supported values: ${Ys.join(", ")}.`,g.USAGE)}function lk(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new h(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,g.USAGE)}async function Ks(e,t){try{return await ik(e,"utf8")}catch{throw new h(`Cannot read merge ${t} file at ${e}.`,g.NOT_FOUND)}}async function dk(e){let t=re(process.cwd(),e.path);return await B(ve(t))?te(t):null}function uk(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function fk(e,t){let n=ck(e.artifact),r=lk(e.prefer),o=ak.resolve(e.outputPath??e.oursPath),[i,s,a]=await Promise.all([Ks(e.basePath,"base"),Ks(e.oursPath,"ours"),Ks(e.theirsPath,"theirs")]),c,l,d=[],u={};if(n==="history"){let p=Cs(i,s,a);c=p.merged,u.history={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="relationship"){let p=Is(i,s,a);c=p.merged,u.relationship={strategy:p.strategy,common_entries:p.common_entries,entries_from_ours:p.entries_from_ours,entries_from_theirs:p.entries_from_theirs,entries_total:p.entries_total,reanchored:p.reanchored}}else if(n==="item"){let p=await dk(t),_=uk(e.itemPath??o,p),y=nt(Y()),b=Os(i,s,a,{format:_,schema:p?.schema,extensionFieldNames:y,preferred:r,conflictResolution:"stable_value_order"});if(c=b.merged,d.push(...b.conflict_fields),u.item={fields_from_theirs:b.fields_from_theirs,union_fields:b.union_fields,conflict_resolution:"stable_value_order"},e.itemPath!==void 0){let E=Ce(c,{format:_,schema:p?.schema,extensionFieldNames:y}),v=E.metadata,C=[...new Set([...b.fields_from_theirs,...b.union_fields,...b.conflict_decisions.map(k=>k.field)])];l={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,conflictResolution:"stable_value_order",fieldsFromTheirs:b.fields_from_theirs,unionFields:b.union_fields,mergedFieldHashes:Object.fromEntries(C.map(k=>[k,ae(R(k==="body"?E.body:v[k]))])),decisions:b.conflict_decisions}}}else{let p=Rs(i,s,a,{preferred:r});c=p.merged,d.push(...p.conflict_paths),u.json={paths_from_theirs:p.paths_from_theirs}}if(await sk(o,c,"utf8"),l!==void 0){let p=await Od(l);p!==null&&(u.receipt=We(p))}let f=[];if(d.length>0){let p=u.receipt===void 0?'Run "pm merge report" to inspect clone-local merge evidence.':`Run "pm merge report" and correlate receipt ${u.receipt.receipt_id} with item ${u.receipt.item_id}; clone-local discarded values are never copied into this result.`;f.push(`Both branches changed ${d.join(", ")}; the item driver kept the direction-independent stable value. ${p} Review the merged file, re-apply the discarded change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm merge reconcile --dry-run" to inspect the complete post-merge repair, then "pm merge reconcile" to apply it; use --force only after explicitly accepting reported discards.'),{ok:d.length===0,artifact:n,output_path:o,requested_preference:r,conflicts:d,...u,guidance:f,generated_at:q()}}import Js from"node:fs/promises";import xo 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 Et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Zs(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 Co(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 Xs(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 pk(e){let t=xo.resolve(e),n=xo.parse(t).root,r=xo.dirname(t);for(;r!==n;){let o;try{o=await Js.stat(r)}catch(i){if(Et(i,"ENOTDIR"))throw Co(e);if(!Et(i,"ENOENT"))throw i;r=xo.dirname(r);continue}if(!o.isDirectory())throw Co(e);return}}async function Zn(e){let t;try{t=await Js.stat(e)}catch(n){throw Et(n,"ENOENT")?(await pk(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:Zs(e)})):Et(n,"ENOTDIR")?Co(e):Et(n,"EACCES")||Et(n,"EPERM")?Xs(e):n}if(!t.isDirectory())throw Co(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Xs(e);try{await(await Js.opendir(e)).close()}catch(n){throw Et(n,"EACCES")||Et(n,"EPERM")?Xs(e):n}}async function Oe(e){if(await Zn(e),!await B(ve(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: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]="745b9c3b-538c-558f-b018-b406ca4318f0")}catch{}})();import{readFile as Oo,realpath as Qs,writeFile as hk}from"node:fs/promises";import{execFile as yk}from"node:child_process";import Z from"node:path";import{promisify as bk}from"node:util";import mk 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]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var ru=["runtime/","search/","locks/","transactions/","checkpoints/"];function ou(e){let t=e.replaceAll("\\","/");return mk.isAbsolute(e)||t===".."||t.startsWith("../")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var _k="PM_SOURCE_CONTEXT_ACCESS",gk="PM_ALLOW_SOURCE_CONTEXT_WRITES";function iu(e){let t=e[_k],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[gk]?.trim()==="1";return{access:n,write_override_applied:r,source_writes_allowed:n==="write"||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]="dea4137f-adbd-5dca-bfc7-b56c99c7aa79")}catch{}})();var ea=bk(yk),Qn="# pm-cli:merge-drivers:start",ta="# pm-cli:merge-drivers:end",Wt="# pm-cli:merge-drivers:v2:start",Io="# pm-cli:merge-drivers:v2:end",wk="merge-fence";function su(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function lu(){let e=an(import.meta.url,["../../.."]);return`${su(process.execPath)} ${su(Z.join(e,"dist","cli.js"))}`}var du=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function uu(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),o=iu(e.environment),i=!!(n&&r),s=t===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(t!==void 0){let a=re(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return s?{pm_root:Z.resolve(r),workspace_start:Z.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?re(e.cwd,".agents/pm"):re(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function kt(e){try{let{stdout:t}=await ea("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Qs(t.trim())}catch{return null}}async function fu(e){let t=await kt(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function na(e,t){return Z.relative(e,t).replaceAll("\\","/")}function Ke(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function au(e,t){if(e[t]!=="'")return null;let n="";for(let r=t+1;r<e.length;r+=1){if(e.startsWith(`'"'"'`,r)){n+="'",r+=4;continue}if(e[r]==="'")return{value:n,nextOffset:r+1};n+=e[r]}return null}async function vk(e,t){let n=au(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=au(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(Z.basename(n.value))||Z.basename(r.value)!=="cli.js"||Z.basename(Z.dirname(r.value))!=="dist"||!await B(n.value)||!await B(r.value))return!1;try{let o=Z.dirname(Z.dirname(r.value)),i=JSON.parse(await Oo(Z.join(o,"package.json"),"utf8")),s=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Ro(e,t){let n=e.length>0?`${e}/`:"",r=[`${Ke(`${n}**/*.toon`)} merge=pm-item-toon`,`${Ke(`${n}**/*.md`)} merge=pm-item-markdown`];for(let o of t)r.push(`${Ke(`${n}${o}/*.toon`)} merge=pm-item-toon`),r.push(`${Ke(`${n}${o}/*.md`)} merge=pm-item-markdown`);return r.push(`${Ke(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${Ke(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${Ke(`${n}settings.json`)} merge=pm-json`),r.push(`${Ke(`${n}**/*.json`)} merge=pm-json`),r.push(`${Ke(`${n}extensions/**`)} -merge`),r.push(`${Ke(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}function cu(e,t,n){let r=e.indexOf(t),o=e.indexOf(n);return r>=0&&o>r?`${e.slice(0,r)}${e.slice(o+n.length)}`:e.replace(t,"").replace(n,"")}async function pu(e,t,n){let r=Z.join(e,".gitattributes"),o="";try{o=await Oo(r,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&K(l)))throw l}let i=[Wt,...t,Io].join(`
30
+ `),a=cu(cu(o,Wt,Io),Qn,ta).trimEnd(),c=`${a.length>0?`${a}
31
31
 
32
32
  `:""}${i}
33
- `;return c===o?{path:r,changed:!1}:(n||await lk(r,c,"utf8"),{path:r,changed:!0})}function Io(e){let t=le(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function na(e,t){let n=K.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let I=K.join(i,".gitattributes");try{let A=await xo(I,"utf8");if(A.includes(Ht)||A.includes(Yn)){r=i,o=A;break}}catch{}let T=K.dirname(i);if(T===i)break;i=T}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=K.join(r,".gitattributes"),a=o.includes(Ht),c=a?Ht:Yn,l=a?Ao:ea,d=o.indexOf(c),u=o.indexOf(l),f=u>d?o.slice(d+c.length,u).split(`
34
- `).map(v=>v.trim()).filter(v=>v.length>0):[],p=Co(ta(r,n),t),_=new Set(f),g=new Set(p),b=p.filter(v=>!_.has(v)),E=f.filter(v=>!g.has(v));return{status:b.length>0||E.length>0?"drift":"ok",path:s,missing_patterns:b,stale_patterns:E,schema_scope:"project"}}async function ra(e){let t=su(),n=[],r=[];for(let o of au){let i=`merge.${o.key}.driver`,s=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await Qs("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await pk(l,s)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function mk(e){let t;try{t=await lu(K.resolve(e))}catch{return{status:"no_git"}}let n=ta(t,K.resolve(e)),r=await Q(e),o=$e(void 0,r.author_default),i=await Ue(e,fk,r.locks.ttl_seconds,o,!1,Gt(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=K.join(t,".gitattributes"),a;try{a=await xo(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&X(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Ht)&&!a.includes(Yn))return{status:"not_installed",path:s};let c=await Q(e),l=Io(c),d=await du(t,Co(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function _k(e,t){let n=cu({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Oe(r);let o=await lu(n.workspace_start);return gk({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function gk(e){let t=K.resolve(e.pmRoot),n=K.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([Zs(t),Zs(n)])}catch(p){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=ta(i,o);if(tu(s))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,h.USAGE);let a=await Q(o),c=Io(a),l=Co(s,c),d=[],u=su();for(let p of au)d.push({key:`merge.${p.key}.name`,value:p.name}),d.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of d)await Qs("git",["config","--local",p.key,p.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let f=await du(i,l,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:f.path,changed:f.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:q()}}import{realpath as Ku}from"node:fs/promises";import qT from"node:path";import Yu 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]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function uu(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function Xn(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?uu(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?uu(t):"root"}import xT from"node:fs/promises";import tr from"node:fs/promises";import _T from"node:path";import hk from"node:fs/promises";import yk 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 bk(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function wk(e,t){return new y(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,h.NOT_FOUND)}async function vk(e,t){return await at(yk.dirname(e)),await(await hk.open(e,"a")).close(),ve({path:e,scope:"project",op:`${t}:history:auto_create`})}async function oa(e){return fu({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function fu(e){let t=bk(e.itemIds),n=[],r=[];for(let o of t){let i=Ge(e.pmRoot,o);if(!await B(i)){if(e.settings.history.missing_stream==="strict_error")throw wk(o,e.commandLabel);r.push(...await vk(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings: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]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function Ek(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 fn(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function wt(e,t){let n=Ek(t),r=fn(e);return r.startsWith(n)?r:`${n}${r}`}import ue from"node:fs/promises";import G from"node:path";import{createHash as Ok,randomUUID as ku}from"node:crypto";import Vt from"node:fs/promises";import pu from"node:path";import{randomUUID as kk}from"node:crypto";import{createRequire as Tk}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 Sk="metadata-query-index.sqlite",mu="4";function Ak(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Oo;function xk(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?Ak(t):null}function _u(){return Oo!==void 0||(Oo=xk(process.versions.node,Tk(import.meta.url))),Oo}function ia(e){return pu.join(e,"runtime",Sk)}function Ck(e){e.exec(`
33
+ `;return c===o?{path:r,changed:!1}:(n||await hk(r,c,"utf8"),{path:r,changed:!0})}function No(e){let t=ue(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function ra(e,t){let n=Z.resolve(e),r=null,o="",i=n;for(let v=0;v<8;v+=1){let C=Z.join(i,".gitattributes");try{let S=await Oo(C,"utf8");if(S.includes(Wt)||S.includes(Qn)){r=i,o=S;break}}catch{}let k=Z.dirname(i);if(k===i)break;i=k}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=Z.join(r,".gitattributes"),a=o.includes(Wt),c=a?Wt:Qn,l=a?Io:ta,d=o.indexOf(c),u=o.indexOf(l),f=u>d?o.slice(d+c.length,u).split(`
34
+ `).map(v=>v.trim()).filter(v=>v.length>0):[],p=Ro(na(r,n),t),_=new Set(f),y=new Set(p),b=p.filter(v=>!_.has(v)),E=f.filter(v=>!y.has(v));return{status:b.length>0||E.length>0?"drift":"ok",path:s,missing_patterns:b,stale_patterns:E,schema_scope:"project"}}async function oa(e){let t=lu(),n=[],r=[];for(let o of du){let i=`merge.${o.key}.driver`,s=` merge driver ${o.artifact} "%O" "%A" "%B"${o.itemPath===void 0?"":` --item-path ${o.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await ea("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await vk(l,s)&&r.push(i)}catch{n.push(i)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Ek(e){let t;try{t=await fu(Z.resolve(e))}catch{return{status:"no_git"}}let n=na(t,Z.resolve(e)),r=await te(e),o=Fe(void 0,r.author_default),i=await $e(e,wk,r.locks.ttl_seconds,o,!1,Vt(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=Z.join(t,".gitattributes"),a;try{a=await Oo(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&K(u))return{status:"not_installed",path:s};throw u}if(!a.includes(Wt)&&!a.includes(Qn))return{status:"not_installed",path:s};let c=await te(e),l=No(c),d=await pu(t,Ro(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await i()}}async function kk(e,t){let n=uu({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;await Oe(r);let o=await fu(n.workspace_start);return Tk({pmRoot:r,workspaceRoot:o,dryRun:e.dryRun===!0})}async function Tk(e){let t=Z.resolve(e.pmRoot),n=Z.resolve(e.workspaceRoot),r=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([Qs(t),Qs(n)])}catch(p){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(p)}`,g.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=na(i,o);if(ou(s))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await te(o),c=No(a),l=Ro(s,c),d=[],u=lu();for(let p of du)d.push({key:`merge.${p.key}.name`,value:p.name}),d.push({key:`merge.${p.key}.driver`,value:`${u} merge driver ${p.artifact} "%O" "%A" "%B"${p.itemPath===void 0?"":` --item-path ${p.itemPath}`}`});if(!r)try{for(let p of d)await ea("git",["config","--local",p.key,p.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let f=await pu(i,l,r);return{ok:!0,dry_run:r,workspace_root:i,pm_root:o,gitattributes:{path:f.path,changed:f.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:q()}}import{realpath as Ju}from"node:fs/promises";import JT from"node:path";import Zu 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]="19ff592c-0746-54e8-a304-2006f4845da2")}catch{}})();function mu(e){return e.replaceAll("~1","/").replaceAll("~0","~")}function er(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?mu(n):"metadata"}let t=e.replace(/^\//,"").split("/")[0];return t?mu(t):"root"}import LT from"node:fs/promises";import ir from"node:fs/promises";import kT from"node:path";import Sk from"node:fs/promises";import Ak 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 xk(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,n)=>t.localeCompare(n))}function Ck(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 Ik(e,t){return await dt(Ak.dirname(e)),await(await Sk.open(e,"a")).close(),Ee({path:e,scope:"project",op:`${t}:history:auto_create`})}async function ia(e){return _u({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function _u(e){let t=xk(e.itemIds),n=[],r=[];for(let o of t){let i=Be(e.pmRoot,o);if(!await B(i)){if(e.settings.history.missing_stream==="strict_error")throw Ck(o,e.commandLabel);r.push(...await Ik(i,e.commandLabel)),r.push(`history_stream_auto_created:${o}`),n.push(o)}}return{auto_created_ids:n,warnings: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]="6b3f1585-ab12-57ca-80eb-d3cebc384c52")}catch{}})();function Ok(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 _n(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function Tt(e,t){let n=Ok(t),r=_n(e);return r.startsWith(n)?r:`${n}${r}`}import pe from"node:fs/promises";import G from"node:path";import{createHash as $k,randomUUID as Au}from"node:crypto";import Kt from"node:fs/promises";import gu from"node:path";import{randomUUID as Rk}from"node:crypto";import{createRequire as Nk}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 Dk="metadata-query-index.sqlite",hu="4";function Pk(e){try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}}var Do;function Lk(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?Pk(t):null}function yu(){return Do!==void 0||(Do=Lk(process.versions.node,Nk(import.meta.url))),Do}function sa(e){return gu.join(e,"runtime",Dk)}function Mk(e){e.exec(`
35
35
  PRAGMA foreign_keys = ON;
36
36
  PRAGMA journal_mode = OFF;
37
37
  PRAGMA synchronous = OFF;
@@ -86,7 +86,7 @@ ${i}
86
86
  tags,
87
87
  tokenize = 'unicode61'
88
88
  );
89
- `)}function Ro(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function gu(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
89
+ `)}function Po(e,t,n){e.prepare("INSERT INTO metadata(key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value").run(t,n)}function bu(e,t){let n=t.metadata;e.prepare(`INSERT INTO items(
90
90
  id, relative_path, metadata_json, status, type, priority,
91
91
  updated_at, created_at, parent, assignee, sprint, release
92
92
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
@@ -101,13 +101,13 @@ ${i}
101
101
  parent = excluded.parent,
102
102
  assignee = excluded.assignee,
103
103
  sprint = excluded.sprint,
104
- 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 hu(e){let t=ia(e.pmRoot),n=_u();if(!n){await Vt.rm(t,{force:!0});return}await Vt.mkdir(pu.dirname(t),{recursive:!0});let r=`${t}.${kk()}.tmp`,o;try{o=new n(r),Ck(o),o.exec("BEGIN IMMEDIATE"),Ro(o,"version",mu),Ro(o,"context_fingerprint",e.contextFingerprint),Ro(o,"source_cursor",e.sourceCursor);for(let i of e.rows)gu(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Vt.rm(t,{force:!0}),await Vt.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Vt.rm(r,{force:!0})]),i}}function Ik(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function yu(e){let t=ia(e.pmRoot),n;try{await Vt.access(t);let r=_u();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Ik(n);if(o.version!==mu||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&&gu(n,e.row),Ro(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function No(e){await Vt.rm(ia(e),{force:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var Ye=8,Tu=500,Rk="metadata-derived-index",Nk="metadata-cache.json",Dk="metadata-cache-bodies.json",Pk="metadata-cache-collections.json",Lk="metadata-cache-delta.json",Mk="metadata-cache-manifest.json",bu=4,Fk=["comments","notes","learnings","files","tests","test_runs","docs"];function Su(){return et(V())}function Po(e){let t={...e},n={};for(let r of Fk)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Au(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function xu(e,t,n,r){let o=Ok("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 Lo(e){return G.join(e,"runtime",Nk)}function Mo(e){return G.join(e,"runtime",Dk)}function Fo(e){return G.join(e,"runtime",Pk)}function ca(e){return G.join(e,"runtime",Lk)}function la(e){return G.join(e,"runtime",Mk)}function $o(e,t){let n=G.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var $k=24,Re=new Map,jo=new WeakMap;function da(e){return jo.get(e)??e.source_cursor}function jk(e,t){let n=da(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){jo.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 Uk(e,t){if(!e)return;let n=da(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){jo.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 zk(e,t){if(!e)return;let n=da(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){jo.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 qk(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(jk(e,r),Uk(t,r),zk(n,r))}function sa(e,t){Re.size>=$k&&!Re.has(e)&&Zt(Re),Re.set(e,t)}async function vt(e,t){let n;try{n=await ue.stat(e)}catch{return Re.delete(e),null}let r=Re.get(e);if(r&&Jn(r.signature,n.mtimeMs,n.ctimeMs,n.size))return Re.delete(e),Re.set(e,r),r.envelope;let o;try{o=t(await ue.readFile(e,"utf8"))}catch{o=null}return sa(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function Bk(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==Ye||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=Lo(e),i=await vt(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await vt($o(o,t),r);return s===null&&er(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function Gk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=Mo(e),o=await vt(r,n);return t&&o?.context_fingerprint!==t?await vt($o(r,t),n):o}async function Hk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Fo(e),o=await vt(r,n);return t&&o?.context_fingerprint!==t?await vt($o(r,t),n):o}async function Cu(e){let t=ca(e),n=await vt(t,r=>{let o=JSON.parse(r);return o.version!==Ye||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 ue.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function Iu(e){let t=la(e),n=await vt(t,r=>{let o=JSON.parse(r);return o.version!==Ye||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 ue.stat(t),await Zn(e)}catch{}return null}async function Qn(e,t){await ue.mkdir(G.dirname(e),{recursive:!0}),await $(e,JSON.stringify(t));try{let r=await ue.stat(e);sa(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{Re.delete(e)}let n=G.dirname(G.dirname(e));if(e===Lo(n)||e===Mo(n)||e===Fo(n)){let r=$o(e,t.context_fingerprint);await $(r,JSON.stringify(t));try{let c=await ue.stat(r);sa(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{Re.delete(r)}let o=G.dirname(e),i=G.extname(e),s=G.basename(e,i),a=(await ue.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==G.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>G.join(o,c.name));if(a.length>bu){let c=(await Promise.all(a.map(async l=>{try{return{path:l,mtime:(await ue.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-bu)))await ue.rm(l.path,{force:!0}),Re.delete(l.path)}}}function Vk(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Ou(e,t,n){return e===void 0||Vk(e,t,n)}function er(e,t){e&&!e.includes(t)&&e.push(t)}function Jn(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function Wk(e,t,n){let r=G.join(e,t);try{let o=await ue.readdir(r);return{folder:t,dirPath:r,files:o}}catch(o){return typeof o=="object"&&o!==null&&"code"in o&&!X(o)&&er(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function Kk(e,t){try{let n=await ue.stat(G.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 aa(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await Kk(e,n))))}function Do(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&&Jn(o,r.mtime_ms,r.ctime_ms,r.size)})}function Yk(e){return sn.some(t=>e.toLowerCase().endsWith(t))}function Xk(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function Jk(e,t,n){if(n)for(let r of await Fe({path:e,scope:"project"}))er(t,r)}function wu(e,t,n,r){if(e)return t&&n?n.collections:r}async function Zk(e,t,n){let r=await ue.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Wr(e);await Jk(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&Jn(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&Jn(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&Jn(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:wu(n.includeCollections,p,f,void 0),bodyLength:c.body_length,body:n.includeBody?d.body:void 0};let g=await ue.readFile(e,"utf8"),b=xe(g,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:v=>er(n.warnings,v)}),E=Po(b.metadata);return Xk(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:wu(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function Qk(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?Au(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};Ou(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function eT(e,t,n,r){try{let o=await Zk(t,n,r);Qk(t,n,r,o)}catch{er(r.warnings,`item_list_item_read_failed:${e}/${G.basename(t)}`)}}function tT(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function nT(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function rT(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function oT(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function iT(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!Yk(s))continue;let a=G.join(o,s),c=G.relative(t.pmRoot,a);n.push(eT(r,a,c,t))}return n}async function sT(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Do(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await Qn(Lo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await Qn(la(e.pmRoot),{version:Ye,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:G.relative(e.pmRoot,r.item_path),metadata:Po(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await hu({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await No(e.pmRoot)}catch{}}async function aT(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 Qn(Mo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function cT(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 Qn(Fo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function ua(e,t,n={}){let r=await Iu(e);return n.required!==!0&&(r===null||r.entry_count<Tu)?async()=>{}:Ue(e,Rk,30,t,!1,!1,3e3)}function vu(e,t){let n=G.relative(e,t);return n===""||n===".."||n.startsWith(`..${G.sep}`)||G.isAbsolute(n)?null:n}async function Zn(e){await Promise.all([Lo(e),Mo(e),Fo(e),ca(e),la(e)].map(async t=>{await ue.rm(t,{force:!0}),Re.delete(t)})),await No(e)}async function lT(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await ue.stat(e.mutation.itemPath),n=Po(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 dT(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function fa(e){let t=vu(e.pmRoot,e.itemPath),n=e.previousItemPath?vu(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await Zn(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=xu(e.preferredFormat,e.typeToFolder,e.schema,Su()),o=await Iu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await Cu(e.pmRoot);if(s.invalid)return await Zn(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=dT(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 lT({mutation:e});let l=ku();return await Qn(ca(e.pmRoot),{version:Ye,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await aa(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await yu({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:Po(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await No(e.pmRoot),[]}catch{return await Zn(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function uT(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function Eu(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function fT(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function pT(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Wr(n);if(!o)continue;let i=e.includeCollections?Au(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Ou(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:G.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function mT(e){return e.forceSourceScan||Zr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Do(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Eu(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Eu(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&fT(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Uo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Su(),l=xu(t,n,o,c),d=await Cu(e);d.invalid&&await Zn(e);let u=await Bk(e,l,i.cacheDiagnostics),f=s?await Gk(e,l):null,p=a?await Hk(e,l):null;qk(u,f,p,d.envelope);let _=tT(u,l),g=nT(f,l),b=rT(p,l),E=[...new Set(Object.values(n))],v=await aa(e,E),I=Object.keys(_),T=Math.max(1,Math.floor(i.derivedIndexMinimumItems??Tu));if(mT({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:v,entryKeys:I,minimumIndexedItems:T,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:b}))return pT({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:g,previousCollections:b});let A=await Promise.all(E.map(z=>Wk(e,z,r))),L=Zr(),D=oT(),ie={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:L,previousEntries:_,previousBodies:g,previousCollections:b,state:D};await Promise.all(iT(A,ie));let ee=await aa(e,E),pe=Do(v,ee)?ee:{},N=D.misses.metadata||Object.keys(_).length!==Object.keys(D.newEntries).length||!Do(u?.directory_signatures,pe)||u===null?ku():u.source_cursor;return await sT({pmRoot:e,contextFingerprint:l,sourceCursor:N,existingCache:u,previousEntries:_,directorySignatures:pe,state:D,minimumIndexedItems:T}),s&&await aT({pmRoot:e,contextFingerprint:l,sourceCursor:N,existingBodyCache:f,previousBodies:g,state:D}),a&&await cT({pmRoot:e,contextFingerprint:l,sourceCursor:N,existingCollectionsCache:p,previousCollections:b,state:D}),uT(D)}async function Ru(e,t,n,r,o){return(await Uo(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.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]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function gT(e){try{return await tr.access(e),!0}catch{return!1}}function hT(e,t){e&&(e.includes(t)||e.push(t))}function yT(e){return e??et(V())}function bT(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function qe(e,t,n="pm-",r,o=Se){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=wt(t,n),c=fn(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=bT(r);for(let f of l)for(let[p]of d)for(let _ of u){let g=an(e,p,f,_,o);if(await gT(g))return{id:f,type:p,itemPath:g,item_format:_}}return null}async function Ne(e,t={}){let n=await tr.readFile(e.itemPath,"utf8");await Fe({path:e.itemPath,scope:"project"});let r=xe(n,{format:e.item_format,schema:t.schema,extensionFieldNames:yT(t.extensionFieldNames),onWarning:o=>hT(t.warnings,o)});return{raw:n,document:r}}async function nr(e,t,n=Se,r,o){return await Kn(e),(await Ru(e,t,n,r,o)).map(s=>s.metadata)}async function zo(e,t,n=Se,r,o,i={}){return await Kn(e),(await Uo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function Nu(e){return{async get(t){let n=await qe(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Ne(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>nr(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function wT(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await tr.readdir(_T.join(e,o));for(let s of i)for(let a of sn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function vT(e,t,n,r){let o=wt(t,n),i=await wT(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Nt(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function Du(e,t,n,r){let o=await vT(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 y(`Item ${t} not found`,h.NOT_FOUND,{nextSteps:i})}function ET(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 kT(e){let t=e.typeToFolder??le(e.settings,V()).type_to_folder,n=await qe(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Du(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await Ue(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 Ne(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=as(e.author),d=Gt(e.settings);if(a&&c!==l&&!e.force&&!ET(e.op,e.bypassAssigneeConflict)){if(d.ownership_enforcement==="strict")throw new y(`Item ${n.id} is assigned to ${a}. Use --force to override.`,h.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 TT(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 ST(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await $(e.originalItemPath,e.originalRaw),await tr.rm(e.effectiveTargetItemPath,{force:!0});return}await $(e.originalItemPath,e.originalRaw)}}async function AT(e){let t=await kT({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=be(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=be(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=q();let f=be(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Vi({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:Nu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await oa({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",g=Ot(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=an(e.pmRoot,f.metadata.type,r.id,_,n),E=Ge(e.pmRoot,r.id),v=await He("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:g}),{effectiveTargetItemPath:I,effectiveSerializedAfter:T,skipItemWrite:A}=TT(v,b,g),L=await ua(e.pmRoot,e.author),D=[];try{A||await $(I,T),!A&&I!==r.itemPath&&await tr.rm(r.itemPath);let ee=Fn({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await po(E,ee)}catch(pe){throw await ST({skipItemWrite:A,effectiveTargetItemPath:I,originalItemPath:r.itemPath,originalRaw:o}),pe}A||(D=await fa({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:I,previousItemPath:r.itemPath,document:f}))}finally{await L()}let ie=[...await ve({path:I,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await ve({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 Hi({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:Jr(c.metadata,d.changedFields),current:Jr(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...v.warnings,...D,...ie]}}finally{await a()}}async function qo(e){return AT(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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function CT(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Gt(e.settings);if(n.ownership_enforcement==="strict")throw new y(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,h.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function IT(e){let t=await J(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new y(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);let n=await qe(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await Ne(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new y(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,h.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Pu(e){let t=e.writeHistoryRaw??$;try{await t(e.historyPath,e.nextHistoryRaw),await Qe(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await xT.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await Qe(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function pa(e){let t=[...CT({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await Ue(e.pmRoot,e.subject.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 r=await IT({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}import rr from"node:fs/promises";import{createHash as OT}from"node:crypto";import Mu 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]="65c0fed6-315a-5930-a23f-83996d3f5081")}catch{}})();var Fu=7,RT="history-drift-cache.json";function $u(e){return Mu.join(e,"runtime",RT)}async function NT(e){try{let t=await rr.readFile($u(e),"utf8"),n=JSON.parse(t);return n.version!==Fu||n.history_item_hash_version!==je||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Ce.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Ce.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function DT(e,t,n,r,o){let i=yo(e),s;try{s=await rr.stat(i)}catch(l){return X(l)||o.unreadableStreams.push(de),!1}let a=o.missingStreams.length,c=await ju({itemId:de,historyPath:i,stat:s,cached:t[de],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.versionSkew&&o.versionSkews.push(de),c.verification.chainOk||o.chainMismatches.push(de),n[de]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function PT(e){return OT("sha256").update(e).digest("hex")}async function LT(e){let t=await rr.readFile(e,"utf8"),n=PT(t);if(t.trim().length===0)return null;let r=[],o=null;for(let u of t.split(/\r?\n/)){let f=u.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),o=p.after_hash}if(!o)return null;let i=Ft(r),s=r.some(u=>u.item_hash_version!==void 0&&!Ce.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,l=c!==void 0&&Ce.includes(c),d=l?c:i.item_hash_version;return{latestAfterHash:o,chainOk:i.ok,versionSkew:s,latestHashComparable:d!==void 0&&(!s||l||c===void 0),contentHash:n,itemHashVersion:d??je}}function MT(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function Lu(e,t,n){try{let r=await LT(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function ju(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(MT(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await Lu(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await Lu(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Ce.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function FT(e,t,n,r){let o=Ge(e,t.id),i;try{i=await rr.stat(o)}catch(d){return(X(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await ju({itemId:t.id,historyPath:o,stat:i,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&Mn({metadata:c,body:a},s.verification.itemHashVersion)!==s.verification.latestAfterHash&&r.hashMismatches.push(t.id),s.cacheDirty}async function $T(e,t){if(!(t.unreadableStreams.includes(de)||t.chainMismatches.includes(de)||t.versionSkews.includes(de)))try{let n=await qs(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(de)}}async function Bo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await NT(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await FT(e,f,l,r)&&(a=!0);let d=await DT(e,i,s,c,r);if(a||=d,await $T(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=$u(e);try{await rr.mkdir(Mu.dirname(f),{recursive:!0}),await $(f,JSON.stringify({version:Fu,history_item_hash_version:je,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[de]:[]])].sort((f,p)=>f.localeCompare(p));return{...r,driftedItems:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47c087c2-124a-58b7-a5c9-09403235f4a2")}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]="05b945f2-4f96-5f88-98ff-84cc856d0d57")}catch{}})();async function Uu(e,t,n,r){let o=await qe(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Ge(e,o.id),located:o};let i=wt(t,n.id_prefix),s=fn(t),a=i===s?[i]:[i,s];for(let c of a){let l=Ge(e,c);if(await B(l))return{id:c,historyPath:l,located:null}}throw new y(`Item ${t} not found`,h.NOT_FOUND)}import zu from"node:fs/promises";import qu from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var jT=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function or(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Bu(e){return jT.find(t=>t.matches(e))?.kind}function Gu(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=or(i.agent_provenance)?i.agent_provenance:void 0;if(s===void 0)return i;let a={},c=!1;for(let[d,u]of Object.entries(s)){let f=or(u)?Bu(u.value):void 0;if(f===void 0){a[d]=u;continue}c=!0,r+=1;let p=i.agent_harness??"unknown",_=`${p}\0${d}\0${f}`,g=t.get(_)??{harness:p,dimension:d,kind:f,count:0};g.count+=1,t.set(_,g)}if(!c)return i;n+=1;let l={...i};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,l}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension)||i.kind.localeCompare(s.kind))}}}async function Hu(e){let t=[];for(let n of await UT(e))try{let r=await zu.readFile(qu.join(e,"history",n),"utf8");for(let o of r.split(`
105
- `)){if(o.trim().length===0)continue;let i=zT(o);if(i===null||!or(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>or(a)&&Bu(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function UT(e){try{return(await zu.readdir(qu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function zT(e){try{let t=JSON.parse(e);return or(t)?t:null}catch{return null}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="04dbdc08-ad98-543f-96dc-fde635bae92e")}catch{}})();function Vu(e,t){return t==="body"?e.body:e.metadata[t]}function ma(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(o=>{let i=t.findIndex((s,a)=>!r.has(a)&&ma(o,s));return i<0?!1:(r.add(i),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,o])=>Object.hasOwn(n,r)&&ma(o,n[r]))}function Wu(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let i=e[o],s=new Set;for(let c of Un(i.patch))s.add(Xn(c.path)),c.from&&s.add(Xn(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:o+1,ts:i.ts,author:i.author,op:i.op,fields:a.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function BT(e,t,n){let r=Yu.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(Xn(_.path));let i=new Set([...o].filter(_=>ma(Vu(t,_),Vu(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=Wu(e,s),c=Wu(e,i),l=[...o].sort((_,g)=>_.localeCompare(g)),d=[...s].sort((_,g)=>_.localeCompare(g)),u=[...i].sort((_,g)=>_.localeCompare(g)),f=[...new Set(a.map(_=>_.author))].sort((_,g)=>_.localeCompare(g)),p=[...new Set(c.map(_=>_.author))].sort((_,g)=>_.localeCompare(g));return{reconciled_field_count:o.size,reconciled_fields:l,reverted_field_count:s.size,reverted_fields:d,discarded_events:a,discarded_authors:f,preserved_field_count:i.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function GT(e){try{return await Ku(e)}catch{return null}}async function HT(e){if(await GT(qT.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let o=Object.keys(r).sort();if(n.length!==o.length||n.some((a,c)=>a!==o[c]))return null;let i=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:i[a];return r[a]===ce(O(c))})?{receipt:e.receipt,declaredFields:n}:null}async function VT(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Ku(e.itemPath),r=[];for(let s of t){let a=await HT({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let o=new Set(r.flatMap(({declaredFields:s})=>s)),i=e.reconciliation?.reconciled_fields;return r.length>0&&(i===void 0||i.length>0&&i.every(s=>o.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function WT(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await Ut(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],o=e.options.mergeReceiptProof?await VT({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(o&&!o.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new y(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${o.reason}).`,h.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=o?.trusted?r.filter(s=>o.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:o,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(We)}}:e.options.auditContext}}async function KT(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Ne(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=bs(i.document),a=n[n.length-1]?.after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:Ie(s,r)===a,currentItemRawBeforeLock:i.raw,loadedItem:i}}function YT(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function XT(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:q(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Yu.compare(e.finalReplay,e.currentItemReplay):[],before_hash:Ie(e.finalReplay,e.itemHashVersion),after_hash:Ie(n,e.itemHashVersion),message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function JT(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function ZT(e){return pa({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Pu({historyPath:e.historyPath,nextHistoryRaw:_t(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>ve({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function _a(e,t,n){let r=ne(process.cwd(),n.path);await Oe(r);let o=await Q(r),i=le(o,V()),s=await Uu(r,e,o,i.type_to_folder);if(!await B(s.historyPath))throw new y(`No history stream exists for ${s.id}.`,h.NOT_FOUND);let a=await J(s.historyPath),c=await ft(s.historyPath,s.id);if(c.length===0)throw new y(`No history entries exist for ${s.id}; nothing to repair.`,h.USAGE);let l=$t(c),d=Ft(c),u=t.normalizeProvenance?Gu(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=ws(u.entries),p=new Set(u.entries.map(z=>z.item_hash_version).filter(z=>z!==void 0)),_=mo(u.entries,f),g=await KT(s,o,c,f),b=_.finalDocument,E=g.currentItemReplay!==null&&Ie(b,f)!==Ie(g.currentItemReplay,f),v=E&&g.currentItemReplay?BT(_.entries,b,g.currentItemReplay):void 0,{mergeReceiptProof:I,effectiveAuditContext:T}=await WT({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:g,reconciliation:v}),A=[_.entriesRehashed>0,_.entriesPatchRepaired>0,E,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),L=$e(t.author,o.author_default),D=!!t.dryRun,ie=YT({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:E}),{rewrittenEntries:ee,auditEntryAdded:pe}=XT({reanchorEntries:_.entries,changed:A,reconcileNeeded:E,currentItemReplay:g.currentItemReplay,finalReplay:b,author:L,message:ie,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...T,provenance_normalization:u.receipt}:T,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),Y=$t(ee);if(!Y.ok)throw new y(`history-repair produced an invalid rewritten chain (${Y.errors.join(", ")}).`,h.GENERIC_FAILURE);let N=JT(A,_.skippedOps,v);return A&&!D&&N.push(...await ZT({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:g.currentItemRawBeforeLock,author:L,force:t.force,loadedItem:g.loadedItem,historyPath:s.historyPath,rewrittenEntries:ee})),{id:s.id,dry_run:D,changed:A,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!l.ok,entries_rehashed:_.entriesRehashed,entries_patch_repaired:_.entriesPatchRepaired,converted_replace_to_add:_.convertedReplaceToAdd,skipped_ops:_.skippedOps,reconciled_with_item:E,audit_entry_added:pe,verify_ok:Y.ok,verify_errors:Y.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:g.currentItemPath!==null,path:g.currentItemPath,matched_chain_before:g.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...v?{reconciliation:v}:{},...I?{merge_receipt_proof:I}:{},warnings:[...new Set(N)].sort((z,yr)=>z.localeCompare(yr)),generated_at:q()}}async function Xu(e,t){let n=ne(process.cwd(),t.path);await Oe(n);let r=await Q(n),o=le(r,V()),i=[],s=await zo(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await Bo(n,s),c=e.normalizeProvenance?await Hu(n):[],l=[...new Set([...a.driftedItems,...c])].sort((p,_)=>p.localeCompare(_)),d=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let p of l)try{let _=await _a(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),g=_.changed?"repaired":"skipped_clean";f[g]+=1,u.push(..._.warnings.map(b=>`${p}:${b}`)),d.push({id:p,outcome:g,entries_rehashed:_.history.entries_rehashed,entries_patch_repaired:_.history.entries_patch_repaired,reconciled_with_item:_.history.reconciled_with_item,..._.reconciliation?{reconciliation:_.reconciliation}:{},..._.merge_receipt_proof?{merge_receipt_proof:_.merge_receipt_proof}:{},warnings:_.warnings})}catch(_){f.failed+=1,d.push({id:p,outcome:"failed",error:_ instanceof Error?_.message:String(_)})}return e.dryRun||await _s(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:f,warnings:[...new Set([...i,...u])].sort((p,_)=>p.localeCompare(_)),generated_at:q()}}import uc from"node:fs/promises";import{realpathSync as qC}from"node:fs";import{execFile as BC}from"node:child_process";import he from"node:path";import{promisify as GC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb094b44-42b2-5a1c-9fc2-7a0eeaf9fbfd")}catch{}})();var QT=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm health --check-only --full",summary:"One or more receipt files failed bounded-file, schema, or identity validation; use the full health count to inspect the clone-local and durable receipt directories, then repair or remove only confirmed invalid evidence."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function eS(e){if(typeof e!="string")return;let t=e.trim();for(let n of QT)if(t===n.code||t.startsWith(`${n.code}:`))return n}function tS(e){let t={};for(let n of e){let r=eS(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Ju(e){return Object.values(tS(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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var nS=["metadata","resolution"],ga=["metadata","resolution","estimates","lifecycle"],rS="completed";function ha(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Zu(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Qu(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Zu(n.close_reason)??rS;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ha(r)}`,gate:"resolution"})}return t}function ef(e){let t=[];for(let n of e){let r=Zu(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${ha(r)}`,gate:"metadata"})}return t}function tf(e,t){return e.map(n=>{let r=Gd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function nf(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function rf(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${ha(n.path)}`})}return t}function of(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new y(`--fix-scope values must not be empty. Supported values: ${ga.join(", ")}.`,h.USAGE);return new Set(nS)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(ga.includes(o)){n.add(o);continue}throw new y(`Unknown --fix-scope value "${r}". Supported values: ${ga.join(", ")}.`,h.USAGE)}return n}function sf(e,t){let n=[],r=[];for(let o of e)o.gate!==void 0&&!t.has(o.gate)?r.push(o):n.push(o);return{applicable:n,gated:r}}function ir(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var oS=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function iS(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=oS.exec(n);if(!r)return null;let o=r[1],i=o.toUpperCase(),s=o.slice(0,o.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(o.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${i}`)||l.includes(`ISSUE CODE \`${i}\``)||l.includes(`\`${i}\``)||l.includes(`[${i}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?i:null}function af(e){return typeof e=="string"&&e.trim().length>0}function cf(e,t={}){let n=new Map;for(let o of e){if(typeof o.title!="string"||af(o.duplicate_of))continue;let i=iS(o.title,{...t,evidenceText:o.body});if(i===null)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(a=>a.id===o.id)||s.push({id:o.id,title:o.title,parent:af(o.parent)?o.parent.trim():null})}let r=[];for(let[o,i]of n){if(i.length<2)continue;let s=new Set(i.map(l=>l.id.toLowerCase())),a=i.filter(l=>l.parent===null||!s.has(l.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((l,d)=>l.id.localeCompare(d.id));r.push({code:o,count:c.length,ids:c.map(l=>l.id),titles:c.map(l=>l.title)})}return r.sort((o,i)=>o.code.localeCompare(i.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]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function lf(e){let t=new Map;for(let r of e){let o=t.get(r.item_type);o||(o=new Map,t.set(r.item_type,o)),o.set(r.field,(o.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r),i={};for(let s of[...o.keys()].sort((a,c)=>a.localeCompare(c)))i[s]=o.get(s);n[r]=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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var df=3;function uf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function ff(e,t,n=df){let r=Number.isFinite(n)&&n>=1?Math.floor(n):df,o=new Map;for(let i of t){let s=uf(i);if(s.length===0)continue;let a=o.get(s);a?a.push(i):o.set(s,[i])}return e.map(i=>{let s=(o.get(uf(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function pf(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var sS=/^[a-z][a-z0-9+.-]+:\/\//i;function sr(e){return sS.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function aS(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function mf(e){return`${e.item_id} ${e.link_kind}`}function _f(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=aS(o.classification,r.classification),o.owners.set(mf(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[mf(r),r]])})}return[...n.entries()].sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({path:r,classification:o.classification,items:[...o.owners.values()].map(i=>{let s=t(i.item_id);return{id:i.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:i.link_kind}}).sort((i,s)=>{let a=i.id.localeCompare(s.id);return a!==0?a:i.field.localeCompare(s.field)})}))}function cS(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function gf(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${cS(r.title)}"`);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]="971d929f-12be-5648-93c9-8a9878b40dde")}catch{}})();function Go(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function ar(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3f3beb2-1d60-52fe-88ce-1ab3cb9dba0d")}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]="d49d73c9-f988-5c3c-a22d-0580ee5526f6")}catch{}})();function Wt(){let e=cn();for(let t of V()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="924f7718-0527-5967-8ab0-53e8228bd665")}catch{}})();function Vo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Ho(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function lS(e,t){let n=new Set,r=[];for(let o of[...e].sort()){if(n.has(o))continue;n.add(o);let i=[{nodeId:o,children:[...t.get(o)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),i.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),i.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function dS(e,t){let n=[...e].sort(),r=lS(n,t),o=new Set,i=uS(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=fS(a,i,o);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function uS(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,o]of t)for(let i of o)n.get(i)?.add(r);return n}function fS(e,t,n){let r=[],o=[e];for(n.add(e);o.length>0;){let i=o.pop();r.push(i);for(let s of[...t.get(i)].sort())n.has(s)||(n.add(s),o.push(s))}return r.sort()}function pS(e){let t=new Map;for(let n of e){let r=Vo(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function mS(e,t,n){let r=Vo(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function _S(e,t,n,r){let o=Vo(t?.id),i=r.resolve(t?.kind);if(!o||!n.has(o)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:o,child_id:s?o:e,source:"dependency",kind:i.kind,holder_id:e,target_id:o,child_cardinality:s?i.incoming:i.outgoing}}function gS(e,t){let n=new Map;for(let[r,o]of e){let i=mS(r,o,e);i&&n.set(Ho(i),i);for(let s of o.dependencies??[]){let a=_S(r,s,e,t);a&&n.set(Ho(a),a)}}return[...n.values()].sort((r,o)=>Ho(r).localeCompare(Ho(o)))}function hS(e,t,n){let r=new Set(e.filter(o=>o.child_cardinality==="one").map(o=>o.child_id));return[...t].filter(([o,i])=>i.length>1&&r.has(o)).map(([o,i])=>({child_id:o,parent_ids:[...i],legacy_terminal:n.has(o)&&i.every(s=>n.has(s))})).sort((o,i)=>o.child_id.localeCompare(i.child_id))}function yS(e,t,n){let r=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=r.get(i.child_id)??new Set;s.add(i.parent_id),r.set(i.child_id,s)}let o=[];for(let[i,s]of e){let a=Vo(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(i)??[]].filter(l=>l!==a).sort();c.length!==0&&o.push({child_id:i,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(i)&&n.has(a)&&c.every(l=>n.has(l))})}return o.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function ya(e,t=r=>r==="closed"||r==="canceled",n=Wt()){let r=pS(e),o=gS(r,n),i=bS(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=dS([...r.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:o,cycles:a,cardinality_violations:hS(o,i.parents_by_child,s),divergences:yS(r,o,s)}}function bS(e){let t=new Map,n=new Map;for(let r of e){let o=t.get(r.child_id)??new Set;o.add(r.parent_id),t.set(r.child_id,o);let i=n.get(r.parent_id)??new Set;i.add(r.child_id),n.set(r.parent_id,i)}return{parents_by_child:new Map([...t].map(([r,o])=>[r,[...o].sort()])),children_by_parent:new Map([...n].map(([r,o])=>[r,[...o].sort()]))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e04a91fa-4625-50fd-9bfd-c712126baf0d")}catch{}})();function hf(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function wS(e,t,n=!0){let r=hf(e);return n&&(ar(t)||r!==void 0&&Go(r))}function yf(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),o=new Map,i=(c,l,d,u,f)=>{let p=hf(l);if(!p||r.has(p.toLowerCase())||wS(p,void 0,f))return;let _={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};o.set(`${_.holder_id}::${_.target_id}::${_.kind}::${_.source}`,_)};for(let c of n){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;ar(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...o.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}import pn from"node:fs/promises";import mn 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]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function vS(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await pn.readdir(mn.join(e,o))}catch{return}for(let s of i)for(let a of sn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${o}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((o,i)=>o.relativePath.localeCompare(i.relativePath))}function ES(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Me(t);if(s){i.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{i.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&o.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function ba(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function kS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await pn.readdir(mn.join(e,"history"))}catch{return n}for(let o of r.sort((i,s)=>i.localeCompare(s))){if(!o.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await pn.readFile(mn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:ba("history stream",s)});continue}ES({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function bf(e){let t=Me(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function TS(e){let t=[],n=0,r=null;try{r=await J(we(e))}catch(i){n+=1,t.push({path:"settings.json",detail:ba("configuration file",i)})}if(r!==null){n+=1;let i=bf(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await pn.readdir(mn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of o.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let s;try{s=await pn.readFile(mn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:ba("configuration file",c)});continue}let a=bf(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function wf(e,t,n,r={}){let o=await vS(e,n),i=new Set(o.map(u=>u.id)),s=new Map;for(let u of o){let f=s.get(u.id);f===void 0?s.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((p,_)=>p.localeCompare(_))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(o.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=mn.join(e,u.relativePath);return xe(await pn.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await kS(e,i),d=await TS(e);return{item_files_on_disk:o.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import{execFile as SS}from"node:child_process";import{realpath as AS}from"node:fs/promises";import vf from"node:path";import{promisify as xS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var CS=xS(SS),IS=32*1024*1024,OS=1e4,RS=["search/eval-queries.json"];function wa(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function NS(e){return`'${e.replaceAll("'","'\\''")}'`}async function DS(e,t=AS){return t(e).catch(()=>vf.resolve(e))}async function Ef(e){let t=await bt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await DS(e),r=wa(vf.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let o=eu.map(i=>`${r}/${wa(i)}`);try{let{stdout:i}=await CS("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:IS,windowsHide:!0,timeout:OS}),s=new Set(RS.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(wa(l))))].sort((l,d)=>l.localeCompare(d)),c=o.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>NS(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import ec from"node:fs/promises";import tc from"node:path";import{Option as aW}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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}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]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}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]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}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]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var _n="-",Tf=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 va(e){return e.replace(/\r\n/g,`
106
- `)}function Sf(e){let t=va(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
104
+ 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 wu(e){let t=sa(e.pmRoot),n=yu();if(!n){await Kt.rm(t,{force:!0});return}await Kt.mkdir(gu.dirname(t),{recursive:!0});let r=`${t}.${Rk()}.tmp`,o;try{o=new n(r),Mk(o),o.exec("BEGIN IMMEDIATE"),Po(o,"version",hu),Po(o,"context_fingerprint",e.contextFingerprint),Po(o,"source_cursor",e.sourceCursor);for(let i of e.rows)bu(o,i);o.exec("COMMIT"),o.close(),o=void 0,await Kt.rm(t,{force:!0}),await Kt.rename(r,t)}catch(i){throw o?.close(),await Promise.allSettled([Kt.rm(r,{force:!0})]),i}}function Fk(e){return Object.fromEntries(e.prepare("SELECT key, value FROM metadata").all().map(t=>[String(t.key),String(t.value)]))}async function vu(e){let t=sa(e.pmRoot),n;try{await Kt.access(t);let r=yu();if(!r)return!1;n=new r(t),n.exec("PRAGMA foreign_keys = ON");let o=Fk(n);if(o.version!==hu||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&&bu(n,e.row),Po(n,"source_cursor",e.sourceCursor),n.exec("COMMIT"),n.close(),!0}catch{try{n?.exec("ROLLBACK")}catch{}return n?.close(),!1}}async function Lo(e){await Kt.rm(sa(e),{force:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b8c705a-8d80-576f-8642-f6f686cdbed9")}catch{}})();var Ye=8,xu=500,jk="metadata-derived-index",Uk="metadata-cache.json",zk="metadata-cache-bodies.json",qk="metadata-cache-collections.json",Bk="metadata-cache-delta.json",Gk="metadata-cache-manifest.json",Eu=4,Hk=["comments","notes","learnings","files","tests","test_runs","docs"];function Cu(){return nt(Y())}function Fo(e){let t={...e},n={};for(let r of Hk)r in t&&(n[r]=t[r],delete t[r]);return{light:t,heavy:n}}function Iu(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function Ou(e,t,n,r){let o=$k("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 $o(e){return G.join(e,"runtime",Uk)}function jo(e){return G.join(e,"runtime",zk)}function Uo(e){return G.join(e,"runtime",qk)}function la(e){return G.join(e,"runtime",Bk)}function da(e){return G.join(e,"runtime",Gk)}function zo(e,t){let n=G.extname(e);return`${e.slice(0,-n.length)}.${t}${n}`}var Vk=24,Re=new Map,qo=new WeakMap;function ua(e){return qo.get(e)??e.source_cursor}function Wk(e,t){let n=ua(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){qo.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 Kk(e,t){if(!e)return;let n=ua(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){qo.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 Yk(e,t){if(!e)return;let n=ua(e);if(!(t.base_source_cursor!==n||e.source_cursor===t.source_cursor)){qo.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 Xk(e,t,n,r){!e||!r||e.context_fingerprint!==r.context_fingerprint||(Wk(e,r),Kk(t,r),Yk(n,r))}function aa(e,t){Re.size>=Vk&&!Re.has(e)&&Qt(Re),Re.set(e,t)}async function St(e,t){let n;try{n=await pe.stat(e)}catch{return Re.delete(e),null}let r=Re.get(e);if(r&&tr(r.signature,n.mtimeMs,n.ctimeMs,n.size))return Re.delete(e),Re.set(e,r),r.envelope;let o;try{o=t(await pe.readFile(e,"utf8"))}catch{o=null}return aa(e,{signature:{mtime_ms:n.mtimeMs,ctime_ms:n.ctimeMs,size:n.size},envelope:o}),o}async function Jk(e,t,n){let r=a=>{let c=JSON.parse(a);return c.version!==Ye||typeof c.source_cursor!="string"||typeof c.entries!="object"||c.entries===null?null:c},o=$o(e),i=await St(o,r);if(!t||i===null||i.context_fingerprint===t)return i;let s=await St(zo(o,t),r);return s===null&&or(n,`metadata_cache_context_changed:${i.context_fingerprint}->${t}`),s}async function Zk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},r=jo(e),o=await St(r,n);return t&&o?.context_fingerprint!==t?await St(zo(r,t),n):o}async function Qk(e,t){let n=i=>{let s=JSON.parse(i);return s.version!==Ye||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},r=Uo(e),o=await St(r,n);return t&&o?.context_fingerprint!==t?await St(zo(r,t),n):o}async function Ru(e){let t=la(e),n=await St(t,r=>{let o=JSON.parse(r);return o.version!==Ye||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 Nu(e){let t=da(e),n=await St(t,r=>{let o=JSON.parse(r);return o.version!==Ye||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 nr(e)}catch{}return null}async function rr(e,t){await pe.mkdir(G.dirname(e),{recursive:!0}),await j(e,JSON.stringify(t));try{let r=await pe.stat(e);aa(e,{signature:{mtime_ms:r.mtimeMs,ctime_ms:r.ctimeMs,size:r.size},envelope:t})}catch{Re.delete(e)}let n=G.dirname(G.dirname(e));if(e===$o(n)||e===jo(n)||e===Uo(n)){let r=zo(e,t.context_fingerprint);await j(r,JSON.stringify(t));try{let c=await pe.stat(r);aa(r,{signature:{mtime_ms:c.mtimeMs,ctime_ms:c.ctimeMs,size:c.size},envelope:t})}catch{Re.delete(r)}let o=G.dirname(e),i=G.extname(e),s=G.basename(e,i),a=(await pe.readdir(o,{withFileTypes:!0}).catch(()=>[])).filter(c=>c.isFile()&&c.name!==G.basename(e)&&c.name.startsWith(`${s}.`)&&c.name.endsWith(i)).map(c=>G.join(o,c.name));if(a.length>Eu){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-Eu)))await pe.rm(l.path,{force:!0}),Re.delete(l.path)}}}function eT(e,t,n){return n?t===n&&e!==n:t==="toon"&&e!=="toon"}function Du(e,t,n){return e===void 0||eT(e,t,n)}function or(e,t){e&&!e.includes(t)&&e.push(t)}function tr(e,t,n,r){return e.mtime_ms===t&&e.ctime_ms===n&&e.size===r}async function tT(e,t,n){let r=G.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&&!K(o)&&or(n,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:r,files:[]}}}async function nT(e,t){try{let n=await pe.stat(G.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 ca(e,t){return Object.fromEntries(await Promise.all(t.map(async n=>await nT(e,n))))}function Mo(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&&tr(o,r.mtime_ms,r.ctime_ms,r.size)})}function rT(e){return cn.some(t=>e.toLowerCase().endsWith(t))}function oT(e,t,n,r,o,i){r||(e.metadata=!0),t&&!o&&(e.body=!0),n&&!i&&(e.collections=!0)}async function iT(e,t,n){if(n)for(let r of await Me({path:e,scope:"project"}))or(t,r)}function ku(e,t,n,r){if(e)return t&&n?n.collections:r}async function sT(e,t,n){let r=await pe.stat(e),o=r.mtimeMs,i=r.ctimeMs,{size:s}=r,a=Kr(e);await iT(e,n.warnings,n.dispatchReadHooks);let c=n.previousEntries[t],l=!n.forceSourceRead&&c!==void 0&&tr(c,o,i,s),d=n.previousBodies[t],u=!n.forceSourceRead&&d!==void 0&&tr(d,o,i,s),f=n.previousCollections[t],p=!n.forceSourceRead&&f!==void 0&&tr(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:ku(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=Ce(y,{format:a,schema:n.schema,extensionFieldNames:n.extensionFieldNames,onWarning:v=>or(n.warnings,v)}),E=Fo(b.metadata);return oT(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:ku(n.includeCollections,p,f,E.heavy),bodyLength:l?c.body_length:b.body.length,body:n.includeBody?b.body:void 0}}function aT(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?Iu(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};Du(i?.itemFormat,r.itemFormat,n.preferredFormat)&&n.state.documentsById.set(o.id,{candidate:s,itemFormat:r.itemFormat})}async function cT(e,t,n,r){try{let o=await sT(t,n,r);aT(t,n,r,o)}catch{or(r.warnings,`item_list_item_read_failed:${e}/${G.basename(t)}`)}}function lT(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function dT(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function uT(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function fT(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}function pT(e,t){let n=[];for(let{folder:r,dirPath:o,files:i}of e)for(let s of i){if(!rT(s))continue;let a=G.join(o,s),c=G.relative(t.pmRoot,a);n.push(cT(r,a,c,t))}return n}async function mT(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!Mo(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await rr($o(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await rr(da(e.pmRoot),{version:Ye,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:G.relative(e.pmRoot,r.item_path),metadata:Fo(r.metadata).light,linkedFiles:r.metadata.files??[]}));n.length>=e.minimumIndexedItems?await wu({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:n}):await Lo(e.pmRoot)}catch{}}async function _T(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 rr(jo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function gT(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 rr(Uo(e.pmRoot),{version:Ye,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function fa(e,t,n={}){let r=await Nu(e);return n.required!==!0&&(r===null||r.entry_count<xu)?async()=>{}:$e(e,jk,30,t,!1,!1,3e3)}function Tu(e,t){let n=G.relative(e,t);return n===""||n===".."||n.startsWith(`..${G.sep}`)||G.isAbsolute(n)?null:n}async function nr(e){await Promise.all([$o(e),jo(e),Uo(e),la(e),da(e)].map(async t=>{await pe.rm(t,{force:!0}),Re.delete(t)})),await Lo(e)}async function hT(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await pe.stat(e.mutation.itemPath),n=Fo(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 yT(e,t,n){return e?.context_fingerprint===t&&e.base_source_cursor===n?structuredClone(e.changes):{}}async function pa(e){let t=Tu(e.pmRoot,e.itemPath),n=e.previousItemPath?Tu(e.pmRoot,e.previousItemPath):void 0;if(t===null||n===null)return await nr(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let r=Ou(e.preferredFormat,e.typeToFolder,e.schema,Cu()),o=await Nu(e.pmRoot);if(o===null||o.context_fingerprint!==r)return[];let i=o.source_cursor,s=await Ru(e.pmRoot);if(s.invalid)return await nr(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=yT(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 hT({mutation:e});let l=Au();return await rr(la(e.pmRoot),{version:Ye,context_fingerprint:r,base_source_cursor:i,source_cursor:l,directory_signatures:await ca(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await vu({pmRoot:e.pmRoot,contextFingerprint:r,expectedSourceCursor:c,sourceCursor:l,row:e.document===null?null:{relativePath:t,metadata:Fo(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...n===void 0?[]:[n],...e.document===null?[t]:[]]})||await Lo(e.pmRoot),[]}catch{return await nr(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function bT(e){return[...e.documentsById.values()].sort((t,n)=>t.candidate.metadata.id.localeCompare(n.candidate.metadata.id)).map(t=>t.candidate)}function Su(e,t,n){return e?.context_fingerprint===t&&e.source_cursor===n}function wT(e,t,n,r,o){return e.every(i=>(!t||r[i]!==void 0)&&(!n||o[i]!==void 0))}function vT(e){let t=new Map;for(let[n,r]of Object.entries(e.previousEntries)){let o=Kr(n);if(!o)continue;let i=e.includeCollections?Iu(r.metadata,e.previousCollections[n]?.collections):r.metadata,s=t.get(i.id);Du(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:G.join(e.pmRoot,n)}})}return[...t.values()].sort((n,r)=>n.candidate.metadata.id.localeCompare(r.candidate.metadata.id)).map(n=>n.candidate)}function ET(e){return e.forceSourceScan||Qr()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!Mo(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Su(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Su(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&wT(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Bo(e,t,n,r,o,i={}){let s=i.includeBody!==!1,a=i.includeCollections!==!1,c=Cu(),l=Ou(t,n,o,c),d=await Ru(e);d.invalid&&await nr(e);let u=await Jk(e,l,i.cacheDiagnostics),f=s?await Zk(e,l):null,p=a?await Qk(e,l):null;Xk(u,f,p,d.envelope);let _=lT(u,l),y=dT(f,l),b=uT(p,l),E=[...new Set(Object.values(n))],v=await ca(e,E),C=Object.keys(_),k=Math.max(1,Math.floor(i.derivedIndexMinimumItems??xu));if(ET({forceSourceScan:i.forceSourceScan===!0,contextFingerprint:l,existingCache:u,existingBodyCache:f,existingCollectionsCache:p,directorySignatures:v,entryKeys:C,minimumIndexedItems:k,includeBody:s,includeCollections:a,previousBodies:y,previousCollections:b}))return vT({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:_,previousBodies:y,previousCollections:b});let S=await Promise.all(E.map(W=>tT(e,W,r))),P=Qr(),M=fT(),L={pmRoot:e,preferredFormat:t,warnings:r,schema:o,extensionFieldNames:c,includeBody:s,includeCollections:a,forceSourceRead:i.forceSourceScan===!0,dispatchReadHooks:P,previousEntries:_,previousBodies:y,previousCollections:b,state:M};await Promise.all(pT(S,L));let V=await ca(e,E),J=Mo(v,V)?V:{},O=M.misses.metadata||Object.keys(_).length!==Object.keys(M.newEntries).length||!Mo(u?.directory_signatures,J)||u===null?Au():u.source_cursor;return await mT({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingCache:u,previousEntries:_,directorySignatures:J,state:M,minimumIndexedItems:k}),s&&await _T({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingBodyCache:f,previousBodies:y,state:M}),a&&await gT({pmRoot:e,contextFingerprint:l,sourceCursor:O,existingCollectionsCache:p,previousCollections:b,state:M}),bT(M)}async function Pu(e,t,n,r,o){return(await Bo(e,t,n,r,o,{includeBody:!1})).map(s=>({metadata:s.metadata,body:s.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]="bffd3114-3e85-58ae-90c7-eea5069cdb89")}catch{}})();async function TT(e){try{return await ir.access(e),!0}catch{return!1}}function ST(e,t){e&&(e.includes(t)||e.push(t))}function AT(e){return e??nt(Y())}function xT(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function Ue(e,t,n="pm-",r,o=Ae){let i=t.trim(),s=i.startsWith("#")?i.slice(1):i;if(s.length===0)return null;let a=Tt(t,n),c=_n(t),l=[...new Set([s,a,c])].filter(f=>f.length>0),d=Object.entries(o),u=xT(r);for(let f of l)for(let[p]of d)for(let _ of u){let y=ln(e,p,f,_,o);if(await TT(y))return{id:f,type:p,itemPath:y,item_format:_}}return null}async function Ne(e,t={}){let n=await ir.readFile(e.itemPath,"utf8");await Me({path:e.itemPath,scope:"project"});let r=Ce(n,{format:e.item_format,schema:t.schema,extensionFieldNames:AT(t.extensionFieldNames),onWarning:o=>ST(t.warnings,o)});return{raw:n,document:r}}async function sr(e,t,n=Ae,r,o){return await Zn(e),(await Pu(e,t,n,r,o)).map(s=>s.metadata)}async function Go(e,t,n=Ae,r,o,i={}){return await Zn(e),(await Bo(e,t,n,r,o,{includeBody:!0,forceSourceScan:i.forceSourceScan})).map(a=>({...a.metadata,body:a.body}))}function Lu(e){return{async get(t){let n=await Ue(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!n)return null;let{document:r}=await Ne(n,{schema:e.settings.schema});return{item:r.metadata,body:r.body}},list:()=>sr(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function CT(e,t){let n=new Set(Object.values(t)),r=[];return await Promise.all([...n].map(async o=>{try{let i=await ir.readdir(kT.join(e,o));for(let s of i)for(let a of cn)if(s.toLowerCase().endsWith(a)){r.push(s.slice(0,-a.length));break}}catch{}})),r}async function IT(e,t,n,r){let o=Tt(t,n),i=await CT(e,r);if(i.length===0)return[];let s=Math.max(3,Math.floor(o.length/2));return i.map(c=>({id:c,distance:Mt(c,o,s)})).filter(c=>c.distance!==null).sort((c,l)=>c.distance-l.distance).slice(0,3).map(c=>c.id)}async function Mu(e,t,n,r){let o=await IT(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 OT(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 RT(e){let t=e.typeToFolder??ue(e.settings,Y()).type_to_folder,n=await Ue(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!n)throw await Mu(e.pmRoot,e.id,e.settings.id_prefix,t);let r=await $e(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 Ne(n,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:o}),a=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||a,l=ls(e.author),d=Vt(e.settings);if(a&&c!==l&&!e.force&&!OT(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 NT(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 DT(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await j(e.originalItemPath,e.originalRaw),await ir.rm(e.effectiveTargetItemPath,{force:!0});return}await j(e.originalItemPath,e.originalRaw)}}async function PT(e){let t=await RT({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=we(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),l=we(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=q();let f=we(l,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames});await Ki({pm_root:e.pmRoot,operation:e.op,before:c,after:f,changed_fields:d.changedFields,sdk:Lu({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:n})});let p=await ia({pmRoot:e.pmRoot,settings:e.settings,itemId:r.id,commandLabel:e.op}),_="toon",y=Pt(f,{format:_,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),b=ln(e.pmRoot,f.metadata.type,r.id,_,n),E=Be(e.pmRoot,r.id),v=await Ge("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:C,effectiveSerializedAfter:k,skipItemWrite:S}=NT(v,b,y),P=await fa(e.pmRoot,e.author),M=[];try{S||await j(C,k),!S&&C!==r.itemPath&&await ir.rm(r.itemPath);let V=zn({nowIso:f.metadata.updated_at,author:e.author,op:e.op,before:c,after:f,message:e.message,context:u});try{await go(E,V)}catch(J){throw await DT({skipItemWrite:S,effectiveTargetItemPath:C,originalItemPath:r.itemPath,originalRaw:o}),J}S||(M=await pa({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:n,schema:e.settings.schema,itemPath:C,previousItemPath:r.itemPath,document:f}))}finally{await P()}let L=[...await Ee({path:C,scope:"project",op:e.op,item_id:f.metadata.id,item_type:f.metadata.type,before:c,after:f,changed_fields:d.changedFields}),...await Ee({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 Wi({id:f.metadata.id,op:e.op,item_type:f.metadata.type,previous_status:c.metadata.status,status:f.metadata.status,previous:Zr(c.metadata,d.changedFields),current:Zr(f.metadata,d.changedFields),changed_fields:d.changedFields}),{item:f.metadata,body:f.body,changedFields:d.changedFields,warnings:[...s,...d.warnings??[],...p.warnings,...v.warnings,...M,...L]}}finally{await a()}}async function Ho(e){return PT(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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function MT(e){if(!e.itemDocument)return[];let t=e.itemDocument.metadata?.assignee?.trim();if(!t||t===e.author||e.force)return[];let n=Vt(e.settings);if(n.ownership_enforcement==="strict")throw new h(`Item ${e.subjectId} is assigned to ${t}. Use --force to override.`,g.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.subjectId}:${t}`]:[]}async function FT(e){let t=await Q(e.subject.historyPath);if(t!==e.historyRawBeforeLock)throw new h(`History for ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);let n=await Ue(e.pmRoot,e.subject.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder),r=n?await Ne(n,{schema:e.settings.schema}):null;if((r?.raw??null)!==(e.currentItemRawBeforeLock??null))throw new h(`Item ${e.subject.id} changed while waiting for lock; retry ${e.operation}.`,g.CONFLICT);return{historyRawUnderLock:t,locatedUnderLock:n,loadedItemUnderLock:r}}async function Fu(e){let t=e.writeHistoryRaw??j;try{await t(e.historyPath,e.nextHistoryRaw),await et(e.historyPath)}catch(n){try{e.historyRawUnderLock===null?await LT.rm(e.historyPath,{force:!0}):await t(e.historyPath,e.historyRawUnderLock),await et(e.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function ma(e){let t=[...MT({itemDocument:e.itemDocument,subjectId:e.subject.id,author:e.author,force:e.force,settings:e.settings})],n=await $e(e.pmRoot,e.subject.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 r=await FT({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:e.operation});return await e.applyRewrite(r),e.applyPostRewrite&&t.push(...await e.applyPostRewrite(r)),t}finally{await n()}}import ar from"node:fs/promises";import{createHash as $T}from"node:crypto";import ju 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]="1c6c65ef-115b-50e2-815e-84f6e91158cd")}catch{}})();var Uu=9,jT="history-drift-cache.json";function zu(e){return ju.join(e,"runtime",jT)}async function UT(e){try{let t=await ar.readFile(zu(e),"utf8"),n=JSON.parse(t);return n.version!==Uu||n.history_item_hash_version!==Ve||typeof n.entries!="object"||n.entries===null||Object.values(n.entries).some(r=>typeof r.chain_ok!="boolean"||typeof r.latest_hash_comparable!="boolean"||!Ie.includes(r.item_hash_version)&&r.version_skew!==!0||r.chain_ok&&r.version_skew!==!0&&Ie.includes(r.item_hash_version)&&!r.latest_hash_comparable)?null:n}catch{return null}}async function zT(e,t,n,r,o){let i=vo(e),s;try{s=await ar.stat(i)}catch(l){return K(l)||o.unreadableStreams.push(fe),!1}let a=o.missingStreams.length,c=await qu({itemId:fe,historyPath:i,stat:s,cached:t[fe],verifyCacheHitByContent:r,accumulator:o});return c.verification?(c.verification.versionSkew&&o.versionSkews.push(fe),c.verification.chainOk||o.chainMismatches.push(fe),n[fe]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,version_skew:c.verification.versionSkew,latest_hash_comparable:c.verification.latestHashComparable,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(o.missingStreams.splice(a),c.cacheDirty)}function qT(e){return $T("sha256").update(e).digest("hex")}async function BT(e){let t=await ar.readFile(e,"utf8"),n=qT(t);if(t.trim().length===0)return null;let r=[],o=null;for(let u of t.split(/\r?\n/)){let f=u.trim();if(f.length===0)continue;let p=JSON.parse(f);if(typeof p.after_hash!="string"||p.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(p),o=p.after_hash}if(!o)return null;let i=Ut(r),s=r.some(u=>u.item_hash_version!==void 0&&!Ie.includes(u.item_hash_version)),c=r[r.length-1].item_hash_version,l=c!==void 0&&Ie.includes(c),d=l?c:i.item_hash_version;return{latestAfterHash:o,chainOk:i.ok,versionSkew:s,latestHashComparable:d!==void 0&&(!s||l||c===void 0),contentHash:n,itemHashVersion:d??Ve}}function GT(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function $u(e,t,n){try{let r=await BT(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function qu(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(GT(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await $u(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};if(e.verifyCacheHitByContent){let r=await $u(e.itemId,e.historyPath,e.accumulator);return{verification:r,cacheDirty:r===null||r.contentHash!==t||r.latestAfterHash!==e.cached.latest_after_hash||r.chainOk!==e.cached.chain_ok||r.versionSkew!==(e.cached.version_skew===!0)||r.latestHashComparable!==e.cached.latest_hash_comparable||r.itemHashVersion!==e.cached.item_hash_version}}return{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,versionSkew:e.cached.version_skew===!0,latestHashComparable:e.cached.latest_hash_comparable&&Ie.includes(e.cached.item_hash_version),contentHash:t,itemHashVersion:e.cached.item_hash_version},cacheDirty:!1}}async function HT(e,t,n,r){let o=Be(e,t.id),i;try{i=await ar.stat(o)}catch(d){return(K(d)?r.missingStreams:r.unreadableStreams).push(t.id),!1}let s=await qu({itemId:t.id,historyPath:o,stat:i,cached:n.previousEntries[t.id],verifyCacheHitByContent:n.verifyCacheHitByContent,accumulator:r});if(!s.verification)return s.cacheDirty;s.verification.versionSkew&&r.versionSkews.push(t.id),s.verification.chainOk||r.chainMismatches.push(t.id),n.nextEntries[t.id]={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size,content_hash:s.verification.contentHash,latest_after_hash:s.verification.latestAfterHash,chain_ok:s.verification.chainOk,version_skew:s.verification.versionSkew,latest_hash_comparable:s.verification.latestHashComparable,item_hash_version:s.verification.itemHashVersion};let{body:a,...c}=t;return s.verification.latestHashComparable&&(_o({metadata:c,body:a},s.verification.itemHashVersion).includes(s.verification.latestAfterHash)||r.hashMismatches.push(t.id)),s.cacheDirty}async function VT(e,t){if(!(t.unreadableStreams.includes(fe)||t.chainMismatches.includes(fe)||t.versionSkews.includes(fe)))try{let n=await Bs(e);t.workspaceStateMismatches.push(...n.mismatched_documents),t.workspaceStateMissing.push(...n.missing_documents),t.workspaceStateUnreadable.push(...n.unreadable_documents)}catch{t.unreadableStreams.push(fe)}}async function Vo(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[],versionSkews:[],workspaceStateMismatches:[],workspaceStateMissing:[],workspaceStateUnreadable:[]},i=(await UT(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata",l={previousEntries:i,nextEntries:s,verifyCacheHitByContent:c};for(let f of t)await HT(e,f,l,r)&&(a=!0);let d=await zT(e,i,s,c,r);if(a||=d,await VT(e,r),a||Object.keys(i).length!==Object.keys(s).length){let f=zu(e);try{await ar.mkdir(ju.dirname(f),{recursive:!0}),await j(f,JSON.stringify({version:Uu,history_item_hash_version:Ve,entries:s}))}catch{}}let u=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches,...r.versionSkews,...r.workspaceStateMismatches.length>0||r.workspaceStateMissing.length>0||r.workspaceStateUnreadable.length>0?[fe]:[]])].sort((f,p)=>f.localeCompare(p));return{...r,driftedItems:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47c087c2-124a-58b7-a5c9-09403235f4a2")}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]="05b945f2-4f96-5f88-98ff-84cc856d0d57")}catch{}})();async function Bu(e,t,n,r){let o=await Ue(e,t,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:Be(e,o.id),located:o};let i=Tt(t,n.id_prefix),s=_n(t),a=i===s?[i]:[i,s];for(let c of a){let l=Be(e,c);if(await B(l))return{id:c,historyPath:l,located:null}}throw new h(`Item ${t} not found`,g.NOT_FOUND)}import Gu from"node:fs/promises";import Hu 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]="6efed404-acd2-5c3a-a008-856df67c8b77")}catch{}})();var KT=[{kind:"boolean",matches:e=>typeof e=="boolean"||typeof e=="string"&&/^(?:true|false)$/iu.test(e.trim())},{kind:"single_digit",matches:e=>typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=9||typeof e=="string"&&/^\d$/u.test(e.trim())}];function cr(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vu(e){return KT.find(t=>t.matches(e))?.kind}function Wu(e){let t=new Map,n=0,r=0;return{entries:e.map(i=>{let s=cr(i.agent_provenance)?i.agent_provenance:void 0;if(s===void 0)return i;let a={},c=!1;for(let[d,u]of Object.entries(s)){let f=cr(u)?Vu(u.value):void 0;if(f===void 0){a[d]=u;continue}c=!0,r+=1;let p=i.agent_harness??"unknown",_=`${p}\0${d}\0${f}`,y=t.get(_)??{harness:p,dimension:d,kind:f,count:0};y.count+=1,t.set(_,y)}if(!c)return i;n+=1;let l={...i};return Object.keys(a).length===0?delete l.agent_provenance:l.agent_provenance=a,l}),receipt:{changed:n>0,events_changed:n,observations_removed:r,invalid_values:[...t.values()].sort((i,s)=>i.harness.localeCompare(s.harness)||i.dimension.localeCompare(s.dimension)||i.kind.localeCompare(s.kind))}}}async function Ku(e){let t=[];for(let n of await YT(e))try{let r=await Gu.readFile(Hu.join(e,"history",n),"utf8");for(let o of r.split(`
105
+ `)){if(o.trim().length===0)continue;let i=XT(o);if(i===null||!cr(i.agent_provenance))continue;if(Object.values(i.agent_provenance).some(a=>cr(a)&&Vu(a.value)!==void 0)){t.push(n.slice(0,-6));break}}}catch{}return t}async function YT(e){try{return(await Gu.readdir(Hu.join(e,"history"))).filter(t=>t.endsWith(".jsonl")).sort()}catch{return[]}}function XT(e){try{let t=JSON.parse(e);return cr(t)?t:null}catch{return null}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="151e5d26-d6f5-5fcf-84ab-ce89e2b7664e")}catch{}})();function Yu(e,t){return t==="body"?e.body:e.metadata[t]}function _a(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let r=new Set;return e.every(o=>{let i=t.findIndex((s,a)=>!r.has(a)&&_a(o,s));return i<0?!1:(r.add(i),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let n=t;return Object.entries(e).every(([r,o])=>Object.hasOwn(n,r)&&_a(o,n[r]))}function Xu(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let i=e[o],s=new Set;for(let c of Gn(i.patch))s.add(er(c.path)),c.from&&s.add(er(c.from));let a=[...n].filter(c=>s.has(c));if(a.length!==0){for(let c of a)n.delete(c);r.push({index:o+1,ts:i.ts,author:i.author,op:i.op,fields:a.sort((c,l)=>c.localeCompare(l))})}}return r.reverse()}function ZT(e,t,n){let r=Zu.compare(t,n);if(r.length===0)return;let o=new Set;for(let _ of r)o.add(er(_.path));let i=new Set([...o].filter(_=>_a(Yu(t,_),Yu(n,_)))),s=new Set([...o].filter(_=>!i.has(_))),a=Xu(e,s),c=Xu(e,i),l=[...o].sort((_,y)=>_.localeCompare(y)),d=[...s].sort((_,y)=>_.localeCompare(y)),u=[...i].sort((_,y)=>_.localeCompare(y)),f=[...new Set(a.map(_=>_.author))].sort((_,y)=>_.localeCompare(y)),p=[...new Set(c.map(_=>_.author))].sort((_,y)=>_.localeCompare(y));return{reconciled_field_count:o.size,reconciled_fields:l,reverted_field_count:s.size,reverted_fields:d,discarded_events:a,discarded_authors:f,preserved_field_count:i.size,preserved_fields:u,preserved_events:c,preserved_authors:p,recovery_hint:a.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function QT(e){try{return await Ju(e)}catch{return null}}async function eS(e){if(await QT(JT.resolve(e.gitWorkspaceRoot,e.receipt.item_path))!==e.currentPath)return null;let n=[...new Set([...e.receipt.fields_from_theirs,...e.receipt.union_fields,...e.receipt.decisions.map(a=>a.field)])].sort(),r=e.receipt.merged_field_hashes;if(!r||n.length===0)return null;let o=Object.keys(r).sort();if(n.length!==o.length||n.some((a,c)=>a!==o[c]))return null;let i=e.currentItemReplay.metadata;return n.every(a=>{let c=a==="body"?e.currentItemReplay.body:i[a];return r[a]===ae(R(c))})?{receipt:e.receipt,declaredFields:n}:null}async function tS(e){if(e.proof.gitWorkspaceRoot===null)return{trusted:!1,reason:"git_workspace_unavailable",receipt_ids:[]};if(e.itemPath===null||e.currentItemReplay===null)return{trusted:!1,reason:"item_path_unavailable",receipt_ids:[]};let t=e.proof.receipts.filter(s=>s.item_id===e.id);if(t.length===0)return{trusted:!1,reason:"no_item_receipts",receipt_ids:[]};let n=await Ju(e.itemPath),r=[];for(let s of t){let a=await eS({receipt:s,gitWorkspaceRoot:e.proof.gitWorkspaceRoot,currentPath:n,currentItemReplay:e.currentItemReplay});a&&r.push(a)}let o=new Set(r.flatMap(({declaredFields:s})=>s)),i=e.reconciliation?.reconciled_fields;return r.length>0&&(i===void 0||i.length>0&&i.every(s=>o.has(s)))?{trusted:!0,reason:"trusted_merge_driver_hash_evidence",receipt_ids:r.map(({receipt:s})=>s.id)}:{trusted:!1,reason:"no_receipt_set_proves_snapshot",receipt_ids:[]}}async function nS(e){let t=new Set(e.options.mergeReceiptProof?.receipts.filter(s=>s.item_id===e.subjectId).map(s=>s.id)??[]),r=(e.options.mergeReceiptProof?await tt(e.options.mergeReceiptProof.gitWorkspaceRoot??process.cwd(),{includeReconciled:!0,includeLossless:!0,pmRoot:e.pmRoot}):void 0)?.receipts.filter(s=>s.item_id===e.subjectId&&t.has(s.id))??[],o=e.options.mergeReceiptProof?await tS({proof:{...e.options.mergeReceiptProof,receipts:r},id:e.subjectId,itemPath:e.itemReplayContext.currentItemPath,currentItemReplay:e.itemReplayContext.currentItemReplay,reconciliation:e.reconciliation}):void 0;if(o&&!o.trusted&&e.options.dryRun!==!0&&e.options.force!==!0)throw new h(`Merge receipt evidence for ${e.subjectId} does not prove the exact item snapshot (${o.reason}).`,g.CONFLICT,{code:"merge_reconcile_receipt_evidence_untrusted",required:"Use authoritative clone-local or durable receipt evidence whose canonical path, declared fields, and merged-value hashes match the current item, or review the mismatch and rerun with --force.",recovery:{suggested_retry:"pm merge reconcile --dry-run"}});let i=o?.trusted?r.filter(s=>o.receipt_ids.includes(s.id)):[];return{mergeReceiptProof:o,effectiveAuditContext:i.length>0&&e.options.force!==!0?{...e.options.auditContext,merge:{receipts:i.map(We)}}:e.options.auditContext}}async function rS(e,t,n,r){let o=e.located?.itemPath??null,i=e.located?await Ne(e.located,{schema:t.schema}):null;if(!i)return{currentItemReplay:null,currentItemPath:o,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let s=ws(i.document),a=n[n.length-1].after_hash;return{currentItemReplay:s,currentItemPath:o,matchedChainBefore:yt(s,r).includes(a),currentItemRawBeforeLock:i.raw,loadedItem:i}}function oS(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function iS(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let n=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay,r=yt(e.finalReplay,e.itemHashVersion),o=e.reanchorEntries[e.reanchorEntries.length-1].after_hash,i=r.indexOf(o),s=yt(n,e.itemHashVersion);return t.push({ts:q(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Zu.compare(e.finalReplay,e.currentItemReplay):[],before_hash:r[i],after_hash:s[i],message:e.message,...e.explicitItemHashVersion?{item_hash_version:e.itemHashVersion}:{},...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function sS(e,t,n){let r=[];return e||r.push("history_repair_no_changes"),t>0&&r.push(`history_repair_skipped_unresolvable_ops:${t}`),n&&n.discarded_events.length>0&&r.push(`history_repair_reconcile_discards_events:${n.discarded_events.length}`,`history_repair_discarded_authors:${n.discarded_authors.join(",")}`),r}async function aS(e){return ma({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>Fu({historyPath:e.historyPath,nextHistoryRaw:bt(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>Ee({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function ga(e,t,n){let r=re(process.cwd(),n.path);await Oe(r);let o=await te(r),i=ue(o,Y()),s=await Bu(r,e,o,i.type_to_folder);if(!await B(s.historyPath))throw new h(`No history stream exists for ${s.id}.`,g.NOT_FOUND);let a=await Q(s.historyPath),c=await _t(s.historyPath,s.id);if(c.length===0)throw new h(`No history entries exist for ${s.id}; nothing to repair.`,g.USAGE);let l=zt(c),d=Ut(c),u=t.normalizeProvenance?Wu(c):{entries:c,receipt:{changed:!1,events_changed:0,observations_removed:0,invalid_values:[]}},f=vs(u.entries),p=new Set(u.entries.map(ze=>ze.item_hash_version).filter(ze=>ze!==void 0)),_=ho(u.entries,f),y=await rS(s,o,c,f),b=_.finalDocument,E=yt(b,f),v=!1;if(y.currentItemReplay!==null){let ze=yt(y.currentItemReplay,f);v=!E.some((ct,kn)=>ct===ze[kn])}let C=v&&y.currentItemReplay?ZT(_.entries,b,y.currentItemReplay):void 0,{mergeReceiptProof:k,effectiveAuditContext:S}=await nS({options:t,pmRoot:r,subjectId:s.id,itemReplayContext:y,reconciliation:C}),P=[_.entriesRehashed>0,_.entriesPatchRepaired>0,v,t.forceAuditEntry===!0,u.receipt.changed].some(Boolean),M=Fe(t.author,o.author_default),L=!!t.dryRun,V=oS({message:t.message,entriesRehashed:_.entriesRehashed,entriesPatchRepaired:_.entriesPatchRepaired,reconcileNeeded:v}),{rewrittenEntries:J,auditEntryAdded:se}=iS({reanchorEntries:_.entries,changed:P,reconcileNeeded:v,currentItemReplay:y.currentItemReplay,finalReplay:b,author:M,message:V,auditOperation:t.auditOperation??"history_repair",auditContext:u.receipt.changed?{...S,provenance_normalization:u.receipt}:S,itemHashVersion:f,explicitItemHashVersion:_.explicitItemHashVersion}),O=zt(J);if(!O.ok)throw new h(`history-repair produced an invalid rewritten chain (${O.errors.join(", ")}).`,g.GENERIC_FAILURE);let W=sS(P,_.skippedOps,C);return P&&!L&&W.push(...await aS({pmRoot:r,subject:s,settings:o,typeRegistry:i,historyRawBeforeLock:a,currentItemRawBeforeLock:y.currentItemRawBeforeLock,author:M,force:t.force,loadedItem:y.loadedItem,historyPath:s.historyPath,rewrittenEntries:J})),{id:s.id,dry_run:L,changed:P,history:{path:s.historyPath,entries_scanned:c.length,chain_drift_before:!l.ok,entries_rehashed:_.entriesRehashed,entries_patch_repaired:_.entriesPatchRepaired,converted_replace_to_add:_.convertedReplaceToAdd,skipped_ops:_.skippedOps,reconciled_with_item:v,audit_entry_added:se,verify_ok:O.ok,verify_errors:O.errors,item_hash_version_before:d.item_hash_version??null,item_hash_version_after:f,version_disposition:p.size>1?"selected_for_ambiguous_stream":"preserved"},item:{exists:y.currentItemPath!==null,path:y.currentItemPath,matched_chain_before:y.matchedChainBefore},provenance_normalization:{requested:t.normalizeProvenance===!0,...u.receipt},...C?{reconciliation:C}:{},...k?{merge_receipt_proof:k}:{},warnings:[...new Set(W)].sort((ze,ct)=>ze.localeCompare(ct)),generated_at:q()}}async function Qu(e,t){let n=re(process.cwd(),t.path);await Oe(n);let r=await te(n),o=ue(r,Y()),i=[],s=await Go(n,r.item_format,o.type_to_folder,i,r.schema,{forceSourceScan:!0}),a=await Vo(n,s),c=e.normalizeProvenance?await Ku(n):[],l=[...new Set([...a.driftedItems,...c])].sort((p,_)=>p.localeCompare(_)),d=[],u=[],f={repaired:0,skipped_clean:0,failed:0};for(let p of l)try{let _=await ga(p,{...e,auditContext:e.auditContextById?.[p],auditContextById:void 0,mergeReceiptProof:e.mergeReceiptProofById?.[p]??e.mergeReceiptProof,mergeReceiptProofById:void 0},t),y=_.changed?"repaired":"skipped_clean";f[y]+=1,u.push(..._.warnings.map(b=>`${p}:${b}`)),d.push({id:p,outcome:y,entries_rehashed:_.history.entries_rehashed,entries_patch_repaired:_.history.entries_patch_repaired,reconciled_with_item:_.history.reconciled_with_item,..._.reconciliation?{reconciliation:_.reconciliation}:{},..._.merge_receipt_proof?{merge_receipt_proof:_.merge_receipt_proof}:{},warnings:_.warnings})}catch(_){f.failed+=1,d.push({id:p,outcome:"failed",error:_ instanceof Error?_.message:String(_)})}return e.dryRun||await hs(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:s.length,drifted_streams:a.driftedItems.length,provenance_invalid_streams:c.length,streams:d,totals:f,warnings:[...new Set([...i,...u])].sort((p,_)=>p.localeCompare(_)),generated_at:q()}}import fc from"node:fs/promises";import{realpathSync as JC}from"node:fs";import{execFile as ZC}from"node:child_process";import he from"node:path";import{promisify as QC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bb094b44-42b2-5a1c-9fc2-7a0eeaf9fbfd")}catch{}})();var cS=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"merge_receipts_pending",command:"pm merge reconcile",summary:"A lossless merge receipt is still pending; run pm merge reconcile to settle it (optionally preview first with --dry-run) so a green health gate certifies receipt settlement, not only intact data."},{code:"merge_receipt_evidence_invalid",command:"pm health --check-only --full",summary:"One or more receipt files failed bounded-file, schema, or identity validation; use the full health count to inspect the clone-local and durable receipt directories, then repair or remove only confirmed invalid evidence."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_version_skew",command:"npm install -g @unbrained/pm-cli@latest",summary:"A history stream declares an item hash version this runtime does not support; upgrade pm to verify the chain instead of re-anchoring it."},{code:"history_drift_merge_receipt",command:"pm merge reconcile",summary:"Canonical path, changed-field, and merged-value hash evidence attributes this drift to a pending receipt; run reconciliation (optionally preview first with --dry-run) instead of repairing history directly."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"provenance_value_domain_invalid",command:"pm history-repair --all --normalize-provenance",summary:"Remove invalid bounded provenance observations from affected streams and append privacy-safe aggregate repair receipts."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_history_drift_version_skews",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more history streams declare an item hash version this runtime does not support; upgrade pm to verify the chains instead of re-anchoring them."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function lS(e){if(typeof e!="string")return;let t=e.trim();for(let n of cS)if(t===n.code||t.startsWith(`${n.code}:`))return n}function dS(e){let t={};for(let n of e){let r=lS(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function ef(e){return Object.values(dS(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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var uS=["metadata","resolution"],ha=["metadata","resolution","estimates","lifecycle"],fS="completed";function ya(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function tf(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function nf(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=tf(n.close_reason)??fS;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ya(r)}`,gate:"resolution"})}return t}function rf(e){let t=[];for(let n of e){let r=tf(n.resolution);r!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:r,command:`pm update ${n.id} --close-reason ${ya(r)}`,gate:"metadata"})}return t}function of(e,t){return e.map(n=>{let r=Wd(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(r),command:`pm update ${n.id} --estimate ${r}`,gate:"estimates"}})}function sf(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function af(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let r=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${r} ${n.item_id} --remove ${ya(n.path)}`})}return t}function cf(e){let t=(e??[]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new h(`--fix-scope values must not be empty. Supported values: ${ha.join(", ")}.`,g.USAGE);return new Set(uS)}let n=new Set;for(let r of t){let o=r.toLowerCase().replaceAll("-","_");if(ha.includes(o)){n.add(o);continue}throw new h(`Unknown --fix-scope value "${r}". Supported values: ${ha.join(", ")}.`,g.USAGE)}return n}function lf(e,t){let n=[],r=[];for(let o of e)o.gate!==void 0&&!t.has(o.gate)?r.push(o):n.push(o);return{applicable:n,gated:r}}function lr(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8a7fbaf1-917f-5067-b9b6-a9f27c80e291")}catch{}})();var pS=/^([A-Z][A-Z0-9]*-\d+)\b/iu;function mS(e,t={}){if(typeof e!="string")return null;let n=e.trim();if(n.length===0)return null;let r=pS.exec(n);if(!r)return null;let o=r[1],i=o.toUpperCase(),s=o.slice(0,o.lastIndexOf("-")),a=new Set((t.configuredPrefixes??[]).map(f=>f.trim().replace(/-+$/u,"").toUpperCase())),c=n.slice(o.length),l=t.evidenceText?.toUpperCase()??"",d=l.includes(`ISSUE CODE: ${i}`)||l.includes(`ISSUE CODE \`${i}\``)||l.includes(`\`${i}\``)||l.includes(`[${i}]`);return s===s.toUpperCase()||/^\s*(?::|—|–|\])/u.test(c)||a.has(s.toUpperCase())||d?i:null}function df(e){return typeof e=="string"&&e.trim().length>0}function uf(e,t={}){let n=new Map;for(let o of e){if(typeof o.title!="string"||df(o.duplicate_of))continue;let i=mS(o.title,{...t,evidenceText:o.body});if(i===null)continue;let s=n.get(i);s||(s=[],n.set(i,s)),s.some(a=>a.id===o.id)||s.push({id:o.id,title:o.title,parent:df(o.parent)?o.parent.trim():null})}let r=[];for(let[o,i]of n){if(i.length<2)continue;let s=new Set(i.map(l=>l.id.toLowerCase())),a=i.filter(l=>l.parent===null||!s.has(l.parent.toLowerCase()));if(a.length<2)continue;let c=[...a].sort((l,d)=>l.id.localeCompare(d.id));r.push({code:o,count:c.length,ids:c.map(l=>l.id),titles:c.map(l=>l.title)})}return r.sort((o,i)=>o.code.localeCompare(i.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]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function ff(e){let t=new Map;for(let r of e){let o=t.get(r.item_type);o||(o=new Map,t.set(r.item_type,o)),o.set(r.field,(o.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r),i={};for(let s of[...o.keys()].sort((a,c)=>a.localeCompare(c)))i[s]=o.get(s);n[r]=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]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var pf=3;function mf(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function _f(e,t,n=pf){let r=Number.isFinite(n)&&n>=1?Math.floor(n):pf,o=new Map;for(let i of t){let s=mf(i);if(s.length===0)continue;let a=o.get(s);a?a.push(i):o.set(s,[i])}return e.map(i=>{let s=(o.get(mf(i))??[]).filter(a=>a!==i).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:i,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:i,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function gf(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var _S=/^[a-z][a-z0-9+.-]+:\/\//i;function dr(e){return _S.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function gS(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function hf(e){return`${e.item_id} ${e.link_kind}`}function yf(e,t){let n=new Map;for(let r of e){let o=n.get(r.path);o?(o.classification=gS(o.classification,r.classification),o.owners.set(hf(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[hf(r),r]])})}return[...n.entries()].sort(([r],[o])=>r.localeCompare(o)).map(([r,o])=>({path:r,classification:o.classification,items:[...o.owners.values()].map(i=>{let s=t(i.item_id);return{id:i.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:i.link_kind}}).sort((i,s)=>{let a=i.id.localeCompare(s.id);return a!==0?a:i.field.localeCompare(s.field)})}))}function hS(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function bf(e){let t=[];for(let n of e)for(let r of n.items)t.push(`${n.path}:${n.classification} owner=${r.id} status=${r.status} field=${r.field} title="${hS(r.title)}"`);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]="971d929f-12be-5648-93c9-8a9878b40dde")}catch{}})();function Wo(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function ur(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f3f3beb2-1d60-52fe-88ce-1ab3cb9dba0d")}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]="d49d73c9-f988-5c3c-a22d-0580ee5526f6")}catch{}})();function Yt(){let e=dn();for(let t of Y()?.relationship_kinds??[])for(let n of t.definitions)e.register(n);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="924f7718-0527-5967-8ab0-53e8228bd665")}catch{}})();function Yo(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function Ko(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function yS(e,t){let n=new Set,r=[];for(let o of[...e].sort()){if(n.has(o))continue;n.add(o);let i=[{nodeId:o,children:[...t.get(o)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),a=s.children[s.nextChild];a===void 0?(r.push(s.nodeId),i.pop()):(s.nextChild+=1,n.has(a)||(n.add(a),i.push({nodeId:a,children:[...t.get(a)??[]].sort(),nextChild:0})))}}return r}function bS(e,t){let n=[...e].sort(),r=yS(n,t),o=new Set,i=wS(n,t),s=[];for(let a of r.reverse()){if(o.has(a))continue;let c=vS(a,i,o);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((a,c)=>a.join("\0").localeCompare(c.join("\0")))}function wS(e,t){let n=new Map(e.map(r=>[r,new Set]));for(let[r,o]of t)for(let i of o)n.get(i)?.add(r);return n}function vS(e,t,n){let r=[],o=[e];for(n.add(e);o.length>0;){let i=o.pop();r.push(i);for(let s of[...t.get(i)].sort())n.has(s)||(n.add(s),o.push(s))}return r.sort()}function ES(e){let t=new Map;for(let n of e){let r=Yo(n?.id);r&&!t.has(r)&&t.set(r,n)}return t}function kS(e,t,n){let r=Yo(t.parent);if(!(!r||!n.has(r)))return{parent_id:r,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function TS(e,t,n,r){let o=Yo(t?.id),i=r.resolve(t?.kind);if(!o||!n.has(o)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:o,child_id:s?o:e,source:"dependency",kind:i.kind,holder_id:e,target_id:o,child_cardinality:s?i.incoming:i.outgoing}}function SS(e,t){let n=new Map;for(let[r,o]of e){let i=kS(r,o,e);i&&n.set(Ko(i),i);for(let s of o.dependencies??[]){let a=TS(r,s,e,t);a&&n.set(Ko(a),a)}}return[...n.values()].sort((r,o)=>Ko(r).localeCompare(Ko(o)))}function AS(e,t,n){let r=new Set(e.filter(o=>o.child_cardinality==="one").map(o=>o.child_id));return[...t].filter(([o,i])=>i.length>1&&r.has(o)).map(([o,i])=>({child_id:o,parent_ids:[...i],legacy_terminal:n.has(o)&&i.every(s=>n.has(s))})).sort((o,i)=>o.child_id.localeCompare(i.child_id))}function xS(e,t,n){let r=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=r.get(i.child_id)??new Set;s.add(i.parent_id),r.set(i.child_id,s)}let o=[];for(let[i,s]of e){let a=Yo(s.parent);if(!a||!e.has(a))continue;let c=[...r.get(i)??[]].filter(l=>l!==a).sort();c.length!==0&&o.push({child_id:i,scalar_parent_id:a,dependency_parent_ids:c,legacy_terminal:n.has(i)&&n.has(a)&&c.every(l=>n.has(l))})}return o.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function ba(e,t=r=>r==="closed"||r==="canceled",n=Yt()){let r=ES(e),o=SS(r,n),i=CS(o),s=new Set([...r].filter(([,c])=>t(c.status)).map(([c])=>c)),a=bS([...r.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:o,cycles:a,cardinality_violations:AS(o,i.parents_by_child,s),divergences:xS(r,o,s)}}function CS(e){let t=new Map,n=new Map;for(let r of e){let o=t.get(r.child_id)??new Set;o.add(r.parent_id),t.set(r.child_id,o);let i=n.get(r.parent_id)??new Set;i.add(r.child_id),n.set(r.parent_id,i)}return{parents_by_child:new Map([...t].map(([r,o])=>[r,[...o].sort()])),children_by_parent:new Map([...n].map(([r,o])=>[r,[...o].sort()]))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e04a91fa-4625-50fd-9bfd-c712126baf0d")}catch{}})();function wf(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function IS(e,t,n=!0){let r=wf(e);return n&&(ur(t)||r!==void 0&&Wo(r))}function vf(e,t=n=>n==="closed"||n==="canceled"){let n=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),r=new Set(n.map(c=>c.id.trim().toLowerCase())),o=new Map,i=(c,l,d,u,f)=>{let p=wf(l);if(!p||r.has(p.toLowerCase())||IS(p,void 0,f))return;let _={holder_id:c.id.trim(),target_id:p,kind:d,source:u,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:p.toLowerCase()==="no-active-blocker"};o.set(`${_.holder_id}::${_.target_id}::${_.kind}::${_.source}`,_)};for(let c of n){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let d=l;ur(d.source_kind)||i(c,d.id,typeof d.kind=="string"?d.kind:"related","dependency",!0)}}let s=[...o.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),a=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:a,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}import gn from"node:fs/promises";import hn 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]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function OS(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async o=>{let i;try{i=await gn.readdir(hn.join(e,o))}catch{return}for(let s of i)for(let a of cn)if(s.toLowerCase().endsWith(a)){r.push({relativePath:`${o}/${s}`,id:s.slice(0,-a.length)});break}})),r.sort((o,i)=>o.relativePath.localeCompare(i.relativePath))}function RS(e,t){let{id:n,relativePath:r,liveItemIds:o,out:i}=e,s=Le(t);if(s){i.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{i.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&o.has(n)&&i.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(i.repairReconciliations+=1))}function wa(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function NS(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await gn.readdir(hn.join(e,"history"))}catch{return n}for(let o of r.sort((i,s)=>i.localeCompare(s))){if(!o.endsWith(".jsonl"))continue;n.scanned+=1;let i;try{i=await gn.readFile(hn.join(e,"history",o),"utf8")}catch(s){n.unparseable.push({id:o.slice(0,-6),path:`history/${o}`,detail:wa("history stream",s)});continue}RS({id:o.slice(0,-6),relativePath:`history/${o}`,liveItemIds:t,out:n},i)}return n}function Ef(e){let t=Le(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function DS(e){let t=[],n=0,r=null;try{r=await Q(ve(e))}catch(i){n+=1,t.push({path:"settings.json",detail:wa("configuration file",i)})}if(r!==null){n+=1;let i=Ef(r);i!==null&&t.push({path:"settings.json",detail:i})}let o;try{o=await gn.readdir(hn.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let i of o.sort((s,a)=>s.localeCompare(a))){if(!i.endsWith(".json"))continue;n+=1;let s;try{s=await gn.readFile(hn.join(e,"schema",i),"utf8")}catch(c){t.push({path:`schema/${i}`,detail:wa("configuration file",c)});continue}let a=Ef(s);a!==null&&t.push({path:`schema/${i}`,detail:a})}return{scanned:n,unparseable:t}}async function kf(e,t,n,r={}){let o=await OS(e,n),i=new Set(o.map(u=>u.id)),s=new Map;for(let u of o){let f=s.get(u.id);f===void 0?s.set(u.id,[u.relativePath]):f.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,f])=>({id:u,paths:[...f].sort((p,_)=>p.localeCompare(_))})).sort((u,f)=>u.id.localeCompare(f.id)),c=(await Promise.all(o.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let f=hn.join(e,u.relativePath);return Ce(await gn.readFile(f,"utf8"),{format:f.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:r.schema,extensionFieldNames:r.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await NS(e,i),d=await DS(e);return{item_files_on_disk:o.length,item_ids_on_disk:i.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import{execFile as PS}from"node:child_process";import{realpath as LS}from"node:fs/promises";import Tf from"node:path";import{promisify as MS}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var FS=MS(PS),$S=32*1024*1024,jS=1e4,US=["search/eval-queries.json"];function va(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function zS(e){return`'${e.replaceAll("'","'\\''")}'`}async function qS(e,t=LS){return t(e).catch(()=>Tf.resolve(e))}async function Sf(e){let t=await kt(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await qS(e),r=va(Tf.relative(t,n));if(r.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let o=ru.map(i=>`${r}/${va(i)}`);try{let{stdout:i}=await FS("git",["ls-files","-z","--",...o.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:$S,windowsHide:!0,timeout:jS}),s=new Set(US.map(l=>`${r}/${l}`)),a=[...new Set(i.split("\0").filter(l=>l.length>0&&!s.has(va(l))))].sort((l,d)=>l.localeCompare(d)),c=o.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>zS(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import ec from"node:fs/promises";import tc from"node:path";import{Option as gW}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]="71a8cd89-54fc-5f8a-b93b-9e4a79bb34b6")}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]="a9b23a46-0bba-5174-8793-dfc37016d1fb")}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]="ab276268-7a98-5f97-b3f5-300dfd1b5ed5")}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]="80965b57-856c-5fef-a372-0c9f3766ada5")}catch{}})();var yn="-",xf=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 Ea(e){return e.replace(/\r\n/g,`
106
+ `)}function Cf(e){let t=Ea(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
107
107
  `);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
108
- `)}function PS(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 Af(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 LS(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 MS(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 kf(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=MS(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} ${_n} to read piped stdin input.`}function FS(e){let t=Sf(e).trim();if(t.length===0||!t.includes(`
109
- `)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=va(t).split(`
110
- `).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]=Af(s[3].trim()),r=a;continue}if(r&&Tf.has(r.toLowerCase())){n[r]=`${n[r]}
111
- ${i}`;continue}return null}return n}function gn(e,t){let n=Sf(e).trim();if(!n)throw new y(`${t} cannot be empty`,h.USAGE);let r=FS(n);if(r)return r;let o={},i,s=PS(n);for(let a of s){let c=LS(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new y(kf(e,t),h.USAGE);let d=Af(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&Tf.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new y(kf(e,t),h.USAGE)}return o}var $S=/^[A-Za-z]:[\\/]/,jS=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function Ea(e){let t=e.trim();return $S.test(t)?!1:jS.test(t)}function xf(e,t,n,r){if(!(r||!e.includes(",")))throw new y(`${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.`,h.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 hn(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 y(`${t} does not recognize key${o.length>1?"s":""} ${o.map(i=>`"${i}"`).join(", ")}. Allowed keys: ${n.join(", ")}.`,h.USAGE);for(let i of Object.keys(e)){let s=i.toLowerCase();if(s!==i){if(Object.hasOwn(e,s))throw new y(`${t} provides key "${i}" more than once after case normalization.`,h.USAGE);e[s]=e[i],delete e[i]}}}async function US(e){if(process.stdin.isTTY===!0)throw new y(`${e} value "${_n}" requires piped stdin input. Pipe content into the command, or end manual stdin with Ctrl+D (Unix/macOS) or Ctrl+Z then Enter (Windows).`,h.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(va(r))}),process.stdin.on("error",o=>{n(o)})})}function cr(){let e,t,n=async i=>{if(t&&t!==i)throw new y(`Only one option may use "${_n}" stdin token per command invocation. Already used by ${t}.`,h.USAGE);return t=i,e||(e=US(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==_n?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()===_n?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new y(`${s} accepts "${_n}" stdin token at most once per command invocation`,h.USAGE);let l=await n(s),d=[...i];return d[c[0]]=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]="411f4336-eb02-5167-9dce-ea99822a8a14")}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]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}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]="4a376062-2e23-5991-80a5-27183909caf3")}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]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var zS={critical:0,high:1,medium:2,low:3,minimal:4},qS=Object.keys(zS),Ez=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${qS.join(", ")}), case-insensitive`;(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 jz=new Map(_i.map(e=>[e.toLowerCase(),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]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}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]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}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]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}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]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}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]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}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]="af754be6-8026-530a-8a20-b03d4ed742e1")}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]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}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]="2c518b97-bc75-5e3f-91e8-d6779d565558")}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]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}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]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}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]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();import{createRequire as cA}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 lA=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,Hq=new RegExp(`\\b(${lA.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var Vq=cA(import.meta.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]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var Yq=new Map([[h.USAGE,"invalid_command_usage"],[h.NOT_FOUND,"item_not_found"],[h.CONFLICT,"lock_conflict"],[h.DEPENDENCY_FAILED,"dependency_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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 uA=[{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"}],iB=new Map(uA.map(e=>[e.action,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]="3ad30a32-0f83-5473-b0a3-349e271d8378")}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]="dff9b113-2b29-5154-afbf-f191f2f556a6")}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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}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]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var pB=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"});(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();import AB from"node:readline/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]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();import mA from"node:crypto";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]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var zB=ka.join("runtime","telemetry","events.jsonl"),qB=ka.join("runtime","telemetry","state.json"),BB=ka.join("runtime","telemetry","otel-spans.jsonl");var GB=3600*1e3;var HB=globalThis.fetch,_A=["user","automation","test","dogfood"],VB=Promise.resolve(),WB=Promise.resolve();var KB=new Set(_A);var YB=mA.randomUUID();var Pf="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",XB=new RegExp(`\\b(${Pf})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),JB=new RegExp(`(--${Pf})(=|\\s+)([^\\s,;]+)`,"giu");(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 Ta=[{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}],Lf=Ta.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Mf=Ta.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Sa=[{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}],Aa=Sa.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Ff=Sa.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 ae(e){return e.map(t=>({...t}))}var xa=[{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"}],$f=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],AA=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...$f],jf=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],xA=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],CA=[...xa,...jf],Uf=[{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"}],IA=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],zf=[{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"}],Ca=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...ae(xa),...ae(AA),{param:"ids",flag:"--ids"},...ae(jf),...ae(IA),...ae(Uf),...ae(zf),{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"}],Ia=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...ae(CA)],Oa=[{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"},...ae(xa),...ae($f),...ae(xA),...ae(Uf),...ae(zf),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],qf=[{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"}],Wo=ae(qf),Bf=[{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"}],Ra=ae(Bf),Gf=[{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"}],Na=ae(Gf),Da=[{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"}],Pa=ae(Da),La=ae(Da);var Ma=[{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}],Fa=[{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"}];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0f4c030-0028-5acb-a438-210666118074")}catch{}})();function k(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Hf(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var U=k("id","item_id",!0),lr=k("id","item_id",!1),dr=k("text","string",!1),ur=k("plan-id","item_id",!0),Vf=k("step","string",!0),RA=["--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"],$a=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],NA={"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."},yn=[{command:"plan create",parent:"plan",action:"create",slots:[k("title","string",!1,{polymorphic:!0})],accepted_flags:RA,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:[ur],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:[ur],accepted_flags:$a,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(NA).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[ur,Vf],accepted_flags:$a,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[ur,Vf,k("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:[ur],accepted_flags:$a,description:`${Hf(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:[k("kind","string",!0),...e==="list"?[]:[k("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Hf(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:[k("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:[k("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:[k("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:[k("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 snapshot create",parent:"workspace snapshot",action:"create",slots:[k("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:[k("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:[k("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:[k("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],DA=[...yn].sort((e,t)=>t.command.length-e.command.length),PA=new Map([["append",[U,dr]],["assurance",[k("action","action",!0),k("kind","string",!1),k("id","string",!1)]],["beads import",[k("file","string",!1)]],["changelog export",[k("file","string",!1)]],["claim",[lr]],["close",[U,dr]],["close-task",[U,k("reason","string",!1)]],["comments",[U,dr]],["completion",[k("shell","string",!1)]],["config",[k("scope","string",!1,{polymorphic:!0}),k("action","action",!1),k("key","string",!1),k("value","string",!1,{polymorphic:!0})]],["copy",[U]],["create",[k("type-or-title","string",!1,{polymorphic:!0}),k("title","string",!1)]],["delete",[U]],["deps",[U]],["docs",[U]],["event",[k("title","string",!0)]],["files",[U]],["files discover",[U]],["files lookup",[k("paths","string",!0,{variadic:!0})]],["focus",[lr]],["get",[U]],["graph",[k("subcommand","action",!0),lr,k("target","item_id",!1)]],["guide",[k("topic","string",!1)]],["history",[U]],["history-compact",[lr]],["history-redact",[U]],["history-repair",[lr]],["init",[k("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[U,k("reason","string",!1)]],["item reopen",[U,k("reason","string",!0)]],["learnings",[U,dr]],["meet",[k("title","string",!0)]],["merge",[k("subcommand","action",!0),k("artifact","string",!1),k("base","string",!1),k("ours","string",!1),k("theirs","string",!1)]],["notes",[U,dr]],["package",[k("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[k("target","string",!0)]],["package upgrade",[k("target","string",!1)]],["packages",[k("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[k("target","string",!0)]],["packages upgrade",[k("target","string",!1)]],["pause-task",[U]],["plan",[k("subcommand","action",!0),k("id","item_id",!1,{polymorphic:!0}),k("step","string",!1),k("new-order","integer",!1)]],["profile",[k("subcommand","action",!0),k("name","string",!1)]],["release",[U]],["remind",[k("title","string",!0)]],["restore",[U,k("target","string",!0)]],["schema",[k("subcommand","action",!0),k("name","string",!1)]],["search-advanced",[k("keywords","string",!0,{variadic:!0})]],["search",[k("keywords","string",!0,{variadic:!0})]],["start-task",[U]],["telemetry",[k("namespace-or-subcommand","action",!1,{polymorphic:!0}),k("subcommand","action",!1)]],["test",[U]],["update",[U]],["workspace snapshot",[k("action","action",!0),k("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[k("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[k("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[k("targets","string",!1,{variadic:!0})]])),["vcs abandon",[U]],["vcs create",[k("title","string",!0)]],["vcs merge",[U]],["vcs propose",[U]],["vcs ref-create",[k("name","string",!0)]],["vcs show",[U]]]);function LA(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function MA(e){let t=LA(e);return DA.find(n=>n.command===t||t.startsWith(`${n.command} `))}function F(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var FA=[...F("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...F("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"]),...F("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...F("list","list","target_noun","pm-pfqi",["list"]),...F("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...F("context","context","target_noun","pm-pbyu",["context"]),...F("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...F("search","search","target_noun","pm-pbyu",["search"]),...F("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...F("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...F("graph","graph","target_noun","pm-pbyu",["graph"]),...F("graph","graph show","consolidation","pm-yql1",["deps"]),...F("history","history","target_noun","pm-pbyu",["history"]),...F("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...F("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...F("workspace","workspace","target_noun","pm-pbyu",["workspace","workspace snapshot","workspace snapshot create","workspace snapshot delete","workspace snapshot inspect","workspace snapshot list","workspace snapshot restore"]),...F("workspace","workspace init","consolidation","pm-n7rr",["init"]),...F("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"]),...F("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"]),...F("package","package","package_owned","package:beads",["beads import"]),...F("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...F("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...F("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...F("ops","ops assurance","consolidation","pm-2tan",yn.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...F("plan","plan","target_noun","pm-pbyu",["plan"]),...F("plan","plan","target_noun","pm-2tan",yn.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...F("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...F("help","help","target_noun","pm-pbyu",["help"]),...F("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],$A=[...new Set(FA.map(({command:e})=>e))].map(e=>({command:e,slots:MA(e)?.slots??PA.get(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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function ja(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]="bd6c497f-9fb0-5c47-a677-9dd6636dba02")}catch{}})();var Wf=Fi.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),jA=[...Wf,{flag:"--version"}],Kf=[{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"}],Yf=[{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"}],Ko=Ga([{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"},...Kf,{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"])),Xf=[{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}],Jf=[{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 Ga(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var Zf=[{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"}],Qf=[{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"}],ep=[{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"}],tp=[{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"}],np=[{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"}],rp=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],op=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],ip=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],sp=[{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"}],ap=[{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"}],cp=[{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"}],lp=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Ha=[{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"}],dp=[{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"}],up=[{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"}],Va=[{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"}],rt=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],fp=[...rt,{flag:"--capability"}],Ua=[...Va,{flag:"--declarative"}],UA=[...fp,{flag:"--declarative"}];var zA=[...rt,{flag:"--markdown"},{flag:"--output"}];var qA=[...rt,{flag:"--dry-run"}],BA=[...rt,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],GA=[...rt,{flag:"--watch"}],HA=[...rt,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],VA=[...rt,{flag:"--fields",list:!0}],WA=[...rt,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],pp=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],mp=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var _p=[{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"}],gp=[{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"},...Yf,{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"}],hp=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],yp=[{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"]}],bp=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],wp=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],vp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Ep=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],kp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Tp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],Sp=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Wa=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...Sp],Ap=Wa,xp=[{flag:"--at"},{flag:"--text"},...Sp],Cp=[{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"}],Ip=[{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"}],Op=[{flag:"--limit"}],Rp=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Np=[{flag:"--dry-run"},{flag:"--scope"}],Dp=[{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"}],Pp=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],Lp=[{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"}],Mp=[{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"}],Ka=[{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"}],Fp=[{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"}],$p=[{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"}],jp=[{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"]}],za=[{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"},...Fp,...$p,{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"}],Up=[{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"}],zp=[{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"}],qp=[{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"}],Bp=[{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"}],Gp=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Hp=[{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"},...jp,...Fp,{flag:"--fixed_version"},...$p,{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"}],Vp=[{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"},...Yf,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...jp,{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"}],qa=[{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"}],Wp=[{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"}],Kp=[{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"}],Ba=Ga([{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"])),Yp=[{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"}],Xp=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],Jp=[{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}],Zp=[{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"}],Qp=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],nt=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],em=[{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"]}],tm=Ga([{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"},...Kf],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),nm=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],rm=[{flag:"--eager-tags"}];var KA=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],YA=Ko.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),XA=Ko.filter(e=>e.flag!=="--status");function Ya(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 JA=Ya(Ha),ZA=Ya(Ka),QA=new Map([["assurance",ZA],["plan",JA],["workspace snapshot",Ya(nt)]]);function om(e=yn){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=QA.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 ex=om(),XV=new Map([["list",Ko],["list-all",XA],...KA.map(e=>[e,YA]),["templates",za],["cal",qa],["ctx",Ba],["test-runs-worker",Rp],["init",dp],["config",up],["extension",Va],["package",Ua],["packages",Ua],["install",pp],["upgrade",mp],["create",za],["item mutate",Up],["item complete",zp],["item reopen",qp],["copy",Bp],["focus",Gp],["aggregate",Xf],["calendar",qa],["context",Ba],["get",Yp],["guide",Xp],["search",tm],["next",em],["eval",Qp],["workspace",nt],["workspace snapshot",nt],["workspace snapshot create",nt],["workspace snapshot list",nt],["workspace snapshot inspect",nt],["workspace snapshot restore",nt],["workspace snapshot delete",nt],["history",np],["history-redact",op],["history-repair",ip],["history-author-acknowledge",sp],["history-compact",ap],["merge",rp],["schema",cp],["profile",lp],["plan",Ha],["activity",Wp],["events",Kp],["restore",bp],["update",Hp],["update-many",Vp],["close",_p],["close-many",gp],["delete",wp],["append",hp],["comments",Jf],["notes",Zf],["learnings",Qf],["files",ep],["docs",tp],["deps",Jp],["graph",Zp],["test",Cp],["test-all",Ip],["telemetry",Op],["health",Lp],["assurance",Ka],...ex,["validate",Mp],["gc",Np],["stats",Dp],["duplicates",Pp],["contracts",nm],["completion",rm],["claim",yp],["release",vp],["start-task",Ep],["pause-task",kp],["close-task",Tp],["meet",Wa],["event",Ap],["remind",xp]]);(function(){try{var e=typeof window<"u"?window:typeof 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 im={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},sm={if:{required:["field"]}};Reflect.set(sm,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var am={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:[sm],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:im,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:im,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 fr={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:lo,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"}},cm={assurance:{definition:am,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}}},tx=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Xa={subcommand:{type:"string",enum:[...tx]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...vc]},mode:{type:"string",enum:[...wc]},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:[...Ir]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...Ec]},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"}}]}},Ja={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"]}},pr={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"]}},lm={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]="91de08b8-ad0b-5c61-a272-3c18cd3f083b")}catch{}})();var rx=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],ox=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],ix=new Set(["action","cwd","options",...Object.keys(fr).filter(e=>e!=="severity")]);var sx={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"]},_m=["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"],d5=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(pt.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function ke(e){return ja(e)}var ax=ke([...Ra.map(e=>e.param),...Wo.map(e=>e.param),"assignee","closeReason","completedAt"]),gm=ke([...Na.map(e=>e.param),...Wo.map(e=>e.param),"force"]),cx=ke([...Pa.map(e=>e.param),...gm.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),lx=ke([...La.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),dm=ke([...Fa.map(e=>e.param),"past","section"]),dx=ke([...Ma.map(e=>e.param),"stream"]),Za=ke([...Ca.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),bn=Za.filter(e=>e!=="all"&&e!=="status"),ux=Za.filter(e=>e!=="status"),Et=[[{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"}}]],fx=[[{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}}]],px=ke([...Ia.map(e=>e.param),"count","completion","includeUnparented"]),mx=ke(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Oa.map(e=>e.param)]),um=ke(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),ge=["author","message","force"],hm=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],mr=["author","assignee","message","force"],_x=["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 fm(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:_x}}}var pm={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},mm={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Yo={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"]},...fm("extension"),...fm("package"),"package-upgrade":mm,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:mm,create:{required:["title","description","type","status","priority","message"],optional:ax},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Za,mutuallyExclusiveWhen:Et},"list-all":{optional:ux,mutuallyExclusiveWhen:Et},"list-draft":{optional:bn,mutuallyExclusiveWhen:Et},"list-open":{optional:bn,mutuallyExclusiveWhen:Et},"list-in-progress":{optional:bn,mutuallyExclusiveWhen:Et},"list-blocked":{optional:bn,mutuallyExclusiveWhen:Et},"list-closed":{optional:bn,mutuallyExclusiveWhen:Et},"list-canceled":{optional:bn,mutuallyExclusiveWhen:Et},aggregate:{optional:px},guide:{optional:["list","format","depth"]},context:{optional:dm},ctx:{optional:dm},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:mx,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","snapshotAction"],optional:["name","target","dryRun","force","author","message","lockTtlSeconds","lockWaitMs"]},meet:pm,event:pm,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[...um,"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",...ge],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...ge],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",...ge]},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",..._m,"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",...ge]},activity:{optional:dx},restore:{required:["id","target"],optional:ge},update:{required:["id"],optional:gm,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:cx,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...hm,...ge]},"close-many":{optional:lx},delete:{required:["id"],optional:["dryRun",...ge]},append:{required:["id","body"],optional:ge},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...ge],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...ge],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",...ge],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",...ge],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...ge],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",...ge],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:fx},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",...um,...mr],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:mr},"start-task":{required:["id"],optional:mr},"pause-task":{required:["id"],optional:mr},"close-task":{required:["id"],optional:["text","validateClose",...mr]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},gx=Object.freeze(Object.fromEntries(pt.map(e=>[e,Yo[e]])));function ym(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function hx(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=pr[e];return{...n,description:r?.description??ym(e),...r?.examples?{examples:r.examples}:{}}}function yx(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(Ja,t))return Ja[t];let n=lm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:pr[t]}function bx(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=yx(e,t);return{...r,description:o?.description??ym(t),...o?.examples?{examples:o.examples}:{}}}function wx(e,t){let n=cm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(Xa,t)?Xa[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:fr[t]}function vx(e,t){let n={action:{const:e,description:pr.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=wx(e,r);o&&(n[r]=bx(e,r,o))}return n}function Ex(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 kx(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:ke(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 bm(e){if(!Object.prototype.hasOwnProperty.call(Yo,e))return;let t=Yo[e],n=sx[e]??[];return ke(["action",...rx,...Ln(e)!==void 0?ox:[],...n,...t.required??[],...t.optional??[]])}function Tx(e){let t=Yo[e],n=ke(t.required??[]),r=bm(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:vx(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=Ex(e,t.oneOfRequired));let i=kx(t);return i.length>0&&(o.allOf=i),o}function wm(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 Qa="4.10.1",vm=Qa.split(".")[0],Em="1.4.0",Sx=wm(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${vm}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Qa,type:"object",oneOf:pt.map(e=>Tx(e))}));function Ax(e,t){let n=hx(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 xx(){let e={action:{type:"string",description:pr.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(fr).sort())e[t]=Ax(t,fr[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Em,type:"object",additionalProperties:!1,required:["action"],properties:e}}var Cx=wm(xx);(function(){try{var e=typeof window<"u"?window:typeof 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 g5=new Set([...Kl,...Yl]);(function(){try{var e=typeof window<"u"?window:typeof 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]="01742f33-d1e8-5684-a585-2add88ddb73c")}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]="fde4fea5-94d6-53e2-bfbc-bff71d828c01")}catch{}})();var $x=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),vW=new Set([...$x].filter(e=>e!=="file"));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var jx="2026-07-15T06:22:12.276Z",Ux=Date.parse(jx),zx=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],km=e=>typeof e=="string"?e:"",qx=e=>{let t=e??{},n=km(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(km(t.ts))>=Ux);return zx[r][o]};function Bx(e,t,n=20,r=new Set,o=!1){let i=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let _;try{_=JSON.parse(p)}catch{continue}l+=1;let g=qx(_);if(g!=="attributed"){if(d+=1,g==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[g]+=1,o&&g==="actionable_unknown"&&s.push({item_id:e,line:f+1}),i.length<c&&i.push({item_id:e,line:f+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:s}}function Gx(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let s of i.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var Tm=async(e,t=20,n=!1)=>{let r=tc.join(e,"history"),o;try{o=(await ec.readdir(r)).filter(E=>E.endsWith(".jsonl")).sort((E,v)=>E.localeCompare(v))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,_="_workspace.jsonl",g=new Set;if(o.includes(_))try{g=Gx(await ec.readFile(tc.join(r,_),"utf8"))}catch{g=new Set}for(let E of o){let v;try{v=await ec.readFile(tc.join(r,E),"utf8")}catch{continue}let I=E.slice(0,-6),T=Bx(I,v,t-s.length,g,n);c+=1,l+=T.checked_events,d+=T.unknown_event_count,u+=T.legacy_unknown_event_count,f+=T.actionable_unknown_event_count,p+=T.acknowledged_actionable_event_count,T.unknown_event_count>0&&i.add(I),s.push(...T.samples),n&&a.push(...T.actionable_events)}let b=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...i].sort((E,v)=>E.localeCompare(v)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import Hx from"node:fs/promises";import De from"node:path";import Vx from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var Wx=["path","scope","note"],Kx=["pattern","glob","path","scope","note"],Yx=["path"],Xx=["from","to"],Jx=new Set(["note","scope"]);function Am(e){let t=e??"project";if(!gi.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${gi.join(", ")} (default: project).`,h.USAGE);return t}function nc(e){if(e.startsWith("```")||e.includes(`
112
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||Ea(e)}function Zx(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function Qx(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!nc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let i=e.slice(t+2,-1).trim();if(i.length>0&&Zx(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function eC(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=Qx(r);if(i!==void 0)return[i]}xf(r,"--add",`${t} path`,nc(r));let o=nc(r)?gn(n,"--add"):{path:r};if(hn(o,"--add",Wx),!o.path)throw new y(`--add requires path=<value> or a bare ${t} path`,h.USAGE);return[{path:o.path,scope:Am(o.scope),note:o.note?.trim()||void 0}]}):[]}function tC(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--add-glob");hn(r,"--add-glob",Kx);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new y("--add-glob key/value form requires pattern=<glob>",h.USAGE);return{pattern:o,scope:Am(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function nC(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",h.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=gn(n,"--remove"),o=Object.keys(r).filter(i=>Jx.has(i.toLowerCase()));if(o.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${o.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,h.USAGE);if(hn(r,"--remove",Yx),!r.path)throw new y("--remove key/value form requires path=<value>",h.USAGE);return r.path}return n}):[]}function rC(e){return e?e.map(t=>{let n=gn(t,"--migrate");hn(n,"--migrate",Xx);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new y("--migrate requires from=<value> and to=<value>",h.USAGE);return{from:r,to:o}}):[]}function _r(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function oC(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>_r(i.path,n))),o=[...new Set(t.map(i=>_r(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new y(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,h.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function Xo(e){return e.split(De.sep).join("/")}function rc(e,t,n=process.cwd()){let r=e.trim();if(sr(r))return r;if(De.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Xo(r.replaceAll("\\",De.sep));let o=De.relative(t,n);return o.startsWith(`..${De.sep}`)||o===".."||De.isAbsolute(o)?Xo(De.normalize(r)):Xo(De.relative(t,De.resolve(n,r)))}async function iC(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=De.isAbsolute(o.pattern),s=await Vx(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>rc(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)r.push({path:c,scope:o.scope,note:o.note})}return r}function sC(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",h.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function aC(e){return`${e.path}::${e.scope}`}function xm(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Cm(e){return[...new Map(e.map(t=>[aC(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function cC(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],i=[],s=[];for(let a of n){if(sr(a)){s.push(a.trim());continue}let c=De.isAbsolute(a)?a:De.resolve(t,a);try{(await Hx.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&kn(l)){o.push(a);continue}i.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:i,remote_references:s}}function lC(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=_r(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=_r(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>_r(s,r)),count:o}}function dC(e,t,n,r){for(let i of t)e.some(s=>s.path===i.path&&s.scope===i.scope)||e.push(i);if(n.length>0)for(let i=e.length-1;i>=0;i-=1)n.includes(e[i].path)&&e.splice(i,1);let o=Cm(e);return r?o:xm(o)}async function Sm(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await cC(t,e.workspaceRoot):void 0}}async function Jo(e,t,n,r){let{metadataKey:o}=r,i=cr(),s=ne(process.cwd(),n.path),a=Vr(s),c=process.cwd();await Oe(s);let l=await Q(s),d=le(l,V()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),p=await i.resolveList(t.remove,"--remove"),_=await i.resolveList(t.migrate,"--migrate"),g=eC(u,r.bareNoun).map(Y=>({...Y,path:rc(Y.path,a,c)})),b=tC(f),E=await iC(b,a,c),v=sC([...g,...E],t.note,g.length>0||b.length>0),I=nC(p).map(Y=>rc(Y,a,c)),T=rC(_);if(oC(v,I,T),!(v.length>0||I.length>0||T.length>0)){let Y=await qe(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!Y)throw new y(`Item ${e} not found`,h.NOT_FOUND);let z=(await Ne(Y,{schema:l.schema})).document.metadata[o]??[];return Sm({id:Y.id,artifacts:z,changed:!1,options:t,workspaceRoot:a})}let L=$e(t.author,l.author_default),D=await qo({pmRoot:s,settings:l,id:e,op:r.op,author:L,message:t.message,force:t.force,skipNoop:!0,mutate(Y){let N=Y.metadata,z=N[o]??[],yr=[...z],br=lC(yr,v,I,T),ii=dC(yr,br.adds,br.removes,r.supportsAppendStable&&t.appendStable===!0);ii.length>0?N[o]=ii:delete N[o];let pc=!Ae(z,ii);return{changedFields:pc?[o]:[],warnings:pc&&br.count>0?[`path_migrations_applied:${br.count}`]:[]}}}),ie=D.item[o]??[],ee=D.warnings.find(Y=>Y.startsWith("path_migrations_applied:")),pe=ee?Number(ee.slice(24)):0;return Sm({id:D.item.id,artifacts:ie,changed:D.changedFields.includes(o),migrationsApplied:pe,options:t,workspaceRoot:a})}function Zo(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Im(e,t,n){let r=await Jo(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Zo(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}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]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();async function Om(e,t,n){let r=await Jo(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Zo(r,"files")}import{readFileSync as uC}from"node:fs";import Qo 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]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var fC=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Dm=new Set(["--pm-path","--path","--author"]),pC={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},mC=new Set(["-p","--package"]),_C=new Set(["-c","--call"]),gC=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),hC=new Set(["-C","--prefix","--userconfig","--cache"]);var yC=new Set(["exec","x"]);function bC(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function wC(e,t=process.cwd()){let n=vC(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(Rm(r)||Nm(r,t))return o;if(r==="node"&&o[0]&&Nm(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?oc(o):r==="pnpm"?TC(o):r==="npm"?SC(o):null;return i&&(Rm(i.command)||kC(i.command))?i.args:null}var Pm=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of bC(i)){let c=wC(a),l=c?AC(c):null,d=l&&fC.has(l.subcommand)?xC(l.remaining,pC[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${o}-`)===!0&&u.length>o.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function vC(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Rm(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function EC(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function kC(e){let t=EC(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Nm(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=Qo.resolve(t,e);try{return JSON.parse(uC(Qo.join(Qo.dirname(Qo.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function oc(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let i=o[1];return i?{command:i,args:e.slice(t+1)}:null}if(_C.has(r)){t+=1;break}t+=mC.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Lm(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function TC(e){let t=Lm(e,gC);return t?.subcommand!=="dlx"?null:oc(t.args)}function SC(e){let t=Lm(e,hC);return!t||!yC.has(t.subcommand)?null:oc(t.args)}function AC(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Dm.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function xC(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Dm.has(r)||t.has(r))&&(n+=1)}}import{execFile as CC}from"node:child_process";import{readFile as IC}from"node:fs/promises";import OC from"node:path";import{promisify as RC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var NC=RC(CC),ic=1,DC="linked-test-trust.json";function PC(e){return OC.join(Kr(e),DC)}function Mm(){return{version:ic,acknowledged:{}}}async function LC(e){try{let t=JSON.parse(await IC(PC(e),"utf8"));return t.version!==ic||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Mm():{version:ic,acknowledged:t.acknowledged}}catch{return Mm()}}async function Fm(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await NC("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function $m(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function MC(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Pe(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function gr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function FC(e){return ce(O({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}function $C(e,t,n){let r=FC(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let i=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!MC(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...gr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...gr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...gr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...gr(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...gr(o,t)}}async function jm(e,t,n){let r=await LC(e);return t.map(o=>$C(o,n,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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Um(e){return e.includeBody?zo(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):nr(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var jC=5;async function zm(e,t,n){let r=await Bo(e,t),i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),s=n?Number.POSITIVE_INFINITY:jC,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings: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]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function sc(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),o=[n],i=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&o.length>1)return o.push(n),!0;if(!i.has(c)){if(i.add(c),o.push(c),s(c))return!0;o.pop(),i.delete(c)}}return!1};return s(n)?[...o]:[...e,n]}function UC(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function zC(e,t,n,r){for(let o of e.dependencies??[]){if(typeof o!="object"||o===null||typeof o.id!="string")continue;let i=r.resolve(o.kind);if(!i?.hierarchy)continue;let s=n.get(o.id.toLowerCase());s&&(i.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function qm(e,t=Wt()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),r=new Map(e.map(o=>[o.id,[]]));for(let o of[...e].sort((i,s)=>i.id.localeCompare(s.id))){let i=r.get(o.id),s=UC(o.parent,n);s&&i.push(s),zC(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function Bm(e,t,n=Wt()){let r=ya(e,s=>t?Ei(s,t):s==="closed"||s==="canceled",n),o=qm(e,n),i=r.cycles.map(s=>s.item_ids);return{cycle_count:i.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(i.flat())].sort(),cycle_sample_paths:i.map(s=>sc(s,o).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e7a231e7-0546-5d5f-b0c8-59629ad4d731")}catch{}})();var HC=["src","tests","docs"],VC=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],WC=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),KC=["resolution","expected_result","actual_result"],YC=["default","tracked-all","tracked-all-strict"],Gm=["core","strict","custom"],ni=["off","warn","error"],lc=["author","acceptance_criteria","estimated_minutes","close_reason"],Ym=[...lc,"reviewer","risk","confidence","sprint","release"],fc=Array.from(new Set(Ym)),XC={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},JC={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},ZC={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},QC={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},eI={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},tI=32*1024*1024,nI=1e4,Xm=40,St=5,rI=4096,oI=255,iI=GC(BC);function Jm(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Jm(r):r);return t}function sI(e){return{...e,checks:e.checks.map(t=>({...t,details:Jm(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function Kt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Hm(e){return Kt(e).replace(/\/+$/,"")}function it(e){let t=fe(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function oi(e,t){return It(e,t)??e}function hr(e,t){return t.terminal_statuses.has(oi(e,t))}function kt(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ei(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function aI(e){let t=kt(pi),n={blocked_reason:kt(At.blocked_reason),resolution:kt(At.resolution),actual_result:kt(At.actual_result)},r=kt(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:kt(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:kt(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:kt(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:ei(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:ei(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:ei(o.resolution,n.resolution)?"default":"settings",actual_result:ei(o.actual_result,n.actual_result)?"default":"settings"}}}function cI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Gm.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${Gm.join(", ")}.`,h.USAGE)}function lI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ni.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ni.join(", ")}.`,h.USAGE)}function dI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ni.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ni.join(", ")}.`,h.USAGE)}function uI(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>XC[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function fI(e,t,n){let r=uI(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...lc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Ym],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...lc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var pI=new Set(["acceptance_criteria","estimated_minutes"]);function mI(e,t,n,r){return!r&&pI.has(t)&&hr(e.status,n)?!1:t==="author"?!fe(e.author):t==="acceptance_criteria"?!fe(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?oi(e.status,n)===n.close_status&&!fe(e.close_reason):t==="reviewer"?!fe(e.reviewer):t==="risk"?!fe(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!fe(e.confidence):t==="sprint"?!fe(e.sprint):!fe(e.release)}function _I(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new y(`Unknown --scan-mode value "${e}". Supported values: ${YC.join(", ")}.`,h.USAGE)}function gI(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return he.resolve(t);let n=he.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return he.dirname(he.dirname(n));let o=he.resolve(process.cwd()),i=Vm(n),s=Vm(o),a=he.relative(i,s);return a.length===0||!a.startsWith("..")&&!he.isAbsolute(a)?n:o}function Vm(e){try{return qC.native(e)}catch{return he.resolve(e)}}function hI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Zm(e,t,n){let r=t.length>0?he.join(e,t):e,o;try{o=await uc.readdir(r,{withFileTypes:!0})}catch(i){if(X(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?he.join(t,i.name):i.name;if(i.isDirectory()){if(WC.has(i.name))continue;await Zm(e,s,n);continue}i.isFile()&&n.push(Kt(s))}}async function Wm(e){let t=[];for(let n of HC)await Zm(e,n,t);for(let n of VC){let r=he.join(e,n);try{(await uc.stat(r)).isFile()&&t.push(Kt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function yI(e){try{let{stdout:t}=await iI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:tI,windowsHide:!0,timeout:nI}),n=t.split("\0").map(r=>Kt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function bI(e,t){let n=new Set,r=Hm(Yt);r.length>0&&n.add(r);let o=Hm(he.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function Km(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function wI(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await yI(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await Wm(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await Wm(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function W(e,t=St){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function Tt(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=W(e,Xm);return{values:n.values,truncated:n.truncated,total:e.length}}var vI={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},EI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function kI(e){let t=e.missing_fields.map(n=>`${vI[n]} "${EI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function TI(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,o=r?n.filter(s=>typeof s=="string"):Ju(t);if(o.length===0)return;let i=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:o,...i?{fix_hints_truncated:!0}:{}}}function SI(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var AI="validate_metadata_duplicate_issue_codes";function xI(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:St,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${AI}:${e.length}`]}}function CI(){return Object.fromEntries(fc.map(e=>[e,[]]))}function II(e,t,n){let r=CI();for(let o of e)for(let i of fc)mI(o,i,t,n)&&r[i].push(o.id);return r}function OI(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${JC[o]}:${i.length}`)}return r.push(...n),r}function RI(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=ZC[r];n[s]=i}return n}function NI(e,t,n){let r=[];for(let o of e.required_fields){let i=t[o];if(i)for(let s of i){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:o})}}return r}function DI(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=QC[o],a=eI[o];if(!s||!a)continue;let c=W(i,r?i.length:St);e[s]=c.values,e[a]=c.truncated}}function PI(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:fe(n.get(o)?.resolution)})):[]}function LI(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:fe(n.get(o)?.type)})):[]}function MI(e,t,n,r,o){let i=new Map(e.map(E=>[E.id,E])),s=t.profile==="strict",a=II(e,n,s),c=cf(e,{configuredPrefixes:o}),l=xI(c,r),d=OI(t,a,l.warnings),u=RI(t,a),f=NI(t,a,i),p=lf(f),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...fc],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),DI(_,t,a,r);let g=PI(t,a,i),b=LI(t,a,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:_},warnings:d,closeReasonBackfillRows:g,estimateBackfillRows:b}}function FI(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(oi(f.status,t))),i=[],s=[];for(let f of o){let p=KC.filter(_=>!fe(f[_]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:fe(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:St,l=W(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>kI(f)),u=W(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:o.length,missing_resolution_items:i.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function $I(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function jI(e,t="pm",n=cn()){let r=new Set(e.map(i=>i.id)),o=[...e].sort((i,s)=>i.id.localeCompare(s.id));return new Map(o.map(i=>{let s=new Set,a=it(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=it(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>it(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=it(i.definition_of_ready);return zI(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function UI(e,t,n){let r=yf(e,n?d=>hr(d,n):void 0),o=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),i=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:St,a=W(o,s),c=W(i,s),l=W(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:e.length,dangling_reference_count:o.length+i.length,active_dangling_reference_count:o.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:o.length>0?[`validate_dangling_dependency_references:${o.length}`]:[]}}function zI(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${$I(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(o=>o[1].toLowerCase()))].sort((o,i)=>o.localeCompare(i))}function qI(e){let t=0,n=new Map,r=new Map,o=[],i=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,o.push(d),i.add(d);for(let f of e.get(d)??[])n.has(f)?i.has(f)&&r.set(d,Math.min(r.get(d),n.get(f))):(a(f),r.set(d,Math.min(r.get(d),r.get(f))));if(r.get(d)!==n.get(d))return;let u=[];for(;o.length>0;){let f=o.pop();if(i.delete(f),u.push(f),f===d)break}u.sort((f,p)=>f.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function BI(e,t="pm"){let n=jI(e,t),r=qI(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>sc(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function GI(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function ri(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function HI(e,t){let n=ri(e).split("/").filter(Boolean),r=ri(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function VI(e,t){let n=ri(t),r=ri(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=HI(e,t);return!i&&!s&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function WI(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function KI(e,t,n){let r=t==="docs_unowned"?"docs":"files",o;return n.flatMap(i=>(r==="docs"?i.docs??[]:i.files??[]).map(s=>({item:i,link:s}))).forEach(({item:i,link:s})=>{if(s.scope!=="project")return;let a=Kt(s.path);if(a.length===0||a===e)return;let c=VI(e,a);c!==null&&WI(o,i,c.score)&&(o={item:i,score:c.score,confidence:c.confidence})}),o?{id:o.item.id,type:o.item.type,title:o.item.title,status:o.item.status,confidence:o.confidence}:null}function YI(e,t){return e.map(n=>{let r=GI(n),o=r==="docs_unowned"?"docs":"files",i=KI(n,r,t),s=i?.id??"<id>";return{path:n,classification:r,owner_candidate:i,remediation_hint:`pm ${o} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function XI(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function JI(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=it(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function ZI(e,t,n,r,o){let i=it(t.parent),s=i?n.get(r.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!hr(s.status,o)}}function QI(e,t,n,r){let o=it(e.blocked_by),i=it(e.blocked_reason),s=i?.toLowerCase(),a=oi(e.status,n),c=[];return t.has(a)?(!o&&!i&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(o&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function eO(e,t,n,r){let o=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!hr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=JI(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=it(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&hr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(ZI(c,u,o,i,n))),t){let f=QI(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((p,_)=>p.localeCompare(_))})}}return a}function tO(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function ti(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ac(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function nO(e,t,n,r,o){let i=[];e.closureLikeRows.length>0&&i.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&i.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&i.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=ti("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=ti("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=ti("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=ti("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=ac("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=ac("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=ac("validate_legacy_hierarchy_parent_divergence",r,o.legacyHierarchyDivergence);return[...i,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...f?[f]:[]]}function rO(e){let t=Kt(e);return t.length>rI||t.split(/[\\/]/).some(n=>n.length>oI)}async function oO(e,t){let n=he.isAbsolute(t)?t:he.resolve(e,t);if(rO(n))return!1;try{let r=await uc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return hI(r,["ENOENT","ENOTDIR"])}}async function iO(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(o=>[...(o.files??[]).map(i=>({item:o,artifact:i,link_kind:"files"})),...(o.docs??[]).map(i=>({item:o,artifact:i,link_kind:"docs"}))]);for(let{item:o,artifact:i,link_kind:s}of r){if(i.scope!=="project")continue;if(sr(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=Kt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await oO(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function sO(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:bI(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>Km(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!Km(p,l)),f={};if(d.length>0){let p=Tt(d,i);f.pm_internals={count:d.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function aO(e,t,n,r,o,i,s,a="pm"){let c=eO(e,t,o,i);tO(c);let l=BI(c.activeItems,a),d=Bm(e,o),u=nO(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),f=s?Number.POSITIVE_INFINITY:St,p=W(c.closureLikeRows.map(D=>`${D.id}:${D.fields.join(",")}`),f),_=W(c.terminalParentRows.map(D=>`${D.id}:${D.parent_id}:${D.parent_status}`),f),g=W(c.staleBlockerRows.map(D=>`${D.id}:${D.status}:${D.reasons.join(",")}`),f),b=W(l.cycle_item_ids,f),E=W(l.cycle_sample_paths,f),v=W(d.cycle_item_ids,f),I=W(d.cycle_sample_paths,f),T=W(d.cardinality_violation_rows,f),A=W(d.parent_divergence_rows,f),L=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:L?"error":u.length===0?"ok":"warn",ok:!L&&u.length===0,details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:p.values,active_closure_like_metadata_rows_truncated:p.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:_.values,active_terminal_parent_rows_truncated:_.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:g.values,stale_blocker_rows_truncated:g.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:b.values,dependency_cycle_item_ids_truncated:b.truncated,dependency_cycle_sample_paths:E.values,dependency_cycle_sample_paths_truncated:E.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:I.values,parent_cycle_sample_paths_truncated:I.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:T.values,hierarchy_cardinality_violation_rows_truncated:T.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:A.values,hierarchy_parent_divergence_rows_truncated:A.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function cO(e,t,n,r,o,i){let s=await iO(e,t),a=new Map(e.map(N=>[N.id,N])),c=[...new Set(s.missingLinkedPaths)].sort((N,z)=>N.localeCompare(z)),l=await wI(t,r),d=sO(l,n,t,r,o,i),u=d.candidateFiles.filter(N=>!s.linkedProjectPaths.has(N)),f=YI(u,e),p=ff(c,d.candidateFiles),_=new Map(p.map(N=>[N.path,N.classification])),g=p.filter(N=>N.classification==="moved").length,b=s.staleLinkRows.map(N=>({...N,classification:_.get(N.path)??"deleted"})).sort((N,z)=>N.item_id.localeCompare(z.item_id)||N.path.localeCompare(z.path)||N.link_kind.localeCompare(z.link_kind)),E=[];d.strictModeForcesPmInternals&&E.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&E.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&E.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((N,z)=>N.localeCompare(z)),I=Tt(v,i),T=Tt(c,i),A=Tt(u,i),L=Tt(f.map(N=>`${N.path}:${N.classification}:owner_candidate=${N.owner_candidate?.id??"unowned"}`),i),D=i?f:Tt(XI(f),!1).values,ie=Tt(pf(p),i),ee=b.map(N=>({item_id:N.item_id,path:N.path,link_kind:N.link_kind,classification:N.classification})),pe=_f(ee,N=>{let z=a.get(N);return z?{type:z.type,title:z.title,status:z.status}:void 0}),Y=i?pe:Tt(gf(pe),!1).values;return{check:{name:"files",status:E.length===0?"ok":"warn",ok:E.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:Xm,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:o,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:I.total,remote_linked_paths:I.values,remote_linked_paths_truncated:I.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:T.total,missing_linked_paths:T.values,missing_linked_paths_truncated:T.truncated,missing_linked_paths_moved_count:g,missing_linked_paths_deleted_count:c.length-g,missing_linked_path_classifications:ie.values,missing_linked_path_classifications_truncated:ie.truncated,missing_linked_path_rows_count:pe.length,missing_linked_path_rows:Y,orphaned_paths_count:u.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:L.values,orphaned_path_classifications_truncated:L.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:D}},warnings:E,staleLinkPruneRows:b}}function Qm(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function lO(e,t,n){return`${e}:${t}:${Qm(n)}`}function dO(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=Qm(o.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function uO(e,t,n,r){let o=new Set(e.map(A=>A.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(A=>(A.tests??[]).map(L=>({item:A,linkedTest:L}))),d=await Fm($m()),u=await jm(r,l.map(({linkedTest:A})=>A),d),f=dO(l,u);for(let{item:A,linkedTest:L}of l){if(typeof L.command!="string"||L.command.trim().length===0)continue;i+=1;let D=Pm(L.command,t);if(D.length!==0){s+=D.length;for(let ie of D)a.add(ie),o.has(ie.toLowerCase())||c.push(lO(A.id,ie,L.command))}}let p=[...new Set(c)].sort((A,L)=>A.localeCompare(L)),_=[...new Set(p.map(A=>A.split(":")[1]??""))].filter(A=>A.length>0).sort((A,L)=>A.localeCompare(L)),g=[];p.length>0&&g.push(`validate_command_references_stale_pm_ids:${p.length}`),f.length>0&&g.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let b=n?Number.POSITIVE_INFINITY:St,E=W(p,b),v=W(_,b),I=W([...a].sort((A,L)=>A.localeCompare(L)),b),T=W(f,b);return{check:{name:"command_references",status:g.length===0?"ok":"warn",ok:g.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:I.values,unique_referenced_pm_ids_truncated:I.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:T.values,untrusted_linked_tests_truncated:T.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:_.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:E.values,stale_pm_id_reference_rows_truncated:E.truncated}},warnings:g}}function fO(e,t){let n=zc(e.map(c=>({ref:c.id,version:jc(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let o=t?Number.POSITIVE_INFINITY:St,i=W(n.outdated,o),s=W(n.ahead,o),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:jr,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var dc="pm validate auto-fix";async function pO(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:dc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",h.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function cc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function mO(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>cc(a)===null))try{await pO(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>cc(a)!==null)){let a=cc(s),c=i.get(a);c?c.push(s):i.set(a,[s])}for(let s of i.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Om(a.item_id,{remove:c,message:dc},t):await Im(a.item_id,{remove:c,message:dc},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}function _O(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function gO(e,t,n,r){let o=await wf(e,new Set(t.map(b=>b.id)),n,{schema:r.schema,extensionFieldNames:et(V())}),i=[];o.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${o.unreadable_item_files.length}`),o.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${o.duplicate_item_ids.length}`),o.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${o.history_conflict_marker_streams.length}`),o.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${o.history_unparseable_streams.length}`),o.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${o.resurrected_items.length}`),o.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${o.unparseable_config_files.length}`);let s=i.length,a=await Ef(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await na(e,Io(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await bt(e),d=l===null?null:await ra(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await Ut(l??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:_}=Id(f);p.length>0&&i.push(`validate_merge_decisions_unreviewed:${p.length}`),_O(i,u.invalid_evidence_count);let g=s>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:g,ok:g==="ok",details:{...o,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),lossless_merge_receipt_count:_.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(_.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function ot(e,t,n){n&&TI(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function hO(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let o=MI(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,ot(t,o,n)}if(e.requestedChecks.has("resolution")){let o=FI(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,ot(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=aO(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,ot(t,o,n),ot(t,UI(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await cO(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,ot(t,o,n)}return e.requestedChecks.has("command_references")&&ot(t,await uO(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&ot(t,await zm(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ot(t,fO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ot(t,await gO(e.pmRoot,e.items,le(e.settings,V()).type_to_folder,e.settings),n),t}function yO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...ef(t.closeReasonBackfillRows)),r.push(...Qu(t.resolutionBackfillRows)),r.push(...tf(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...nf(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...rf(t.staleLinkPruneRows)),r}async function bO(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=yO(e,t,n),{applicable:a,gated:c}=sf(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await mO(a,o,i);d.push(...f.applied.map(ir)),u.push(...f.failed.map(({fix:p,error:_})=>({...ir(p),error:_ instanceof Error?_.message:String(_)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,p)=>f.localeCompare(p)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(ir),applied_fixes:d,gated_fixes:c.map(f=>({...ir(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function e_(e,t,n={}){Rl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",h.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",h.USAGE);let o=of(e.fixScope),i=ne(process.cwd(),t.path);await Oe(i);let s=await Q(i),a=Sn(s.schema),c=le(s,V()),l=SI(e),d=[],u=await Um({includeBody:l.has("history_drift")||l.has("metadata"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let ee=await Tm(i);ee.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${ee.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=cI(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=fI(p,f,s.validation.metadata_required_fields),g=aI(s),b=lI(e.dependencyCycleSeverity),E=dI(e.parentCycleSeverity),v=_I(e.scanMode),I=gI(i),T=await hO({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:I,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:g,dependencyCycleSeverity:b,parentCycleSeverity:E,fileScanMode:v,initialWarnings:[...new Set(d)]}),A=r?await bO(e,T,s,o,t,n):void 0,L=[...new Set(T.warnings)].sort((ee,pe)=>ee.localeCompare(pe)),ie={ok:!T.checks.some(ee=>ee.status==="error"),has_warnings:L.length>0,checks:T.checks,warnings:L,...A!==void 0?{fixes:A}:{},generated_at:q(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?ie:{...sI(ie),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var t_=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),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]="8d85d220-dad2-5234-8819-65632275eb47")}catch{}})();var wO=4;async function vO(e){try{return{status:"fulfilled",value:await _a(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function EO(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function kO(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.force?e.pendingReceipts:e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Ms(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function TO(e,t){let n=e.dryRun===!0,r=ne(process.cwd(),t.path),o=await bt(r),i=await Ut(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(i.invalid_evidence_count>0)throw new y(`Merge reconciliation refused ${i.invalid_evidence_count} invalid receipt evidence file(s).`,h.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let s=i.receipts,a=new Map;for(let T of s){let A=a.get(T.item_id)??[];A.push(T),a.set(T.item_id,A)}let c=Object.fromEntries([...a].map(([T,A])=>[T,{merge:{receipts:A.map(We)}}])),l=Object.fromEntries([...a].map(([T,A])=>[T,{gitWorkspaceRoot:o,receipts:A}])),d=await Xu({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:c,...s.length>0?{mergeReceiptProofById:l}:{}},t),u=new Set(d.streams.map(T=>T.id)),f=[...a.keys()].filter(T=>!u.has(T)),p=await t_(f,wO,T=>vO({id:T,dryRun:n,options:e,global:t,auditContext:c[T],mergeReceiptProof:l[T]}));EO({receiptOnlyIds:f,results:p,repair:d});let _=await kO({dryRun:n,force:e.force===!0,pendingReceipts:s,repair:d,gitWorkspaceRoot:o}),g=await e_({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),b=g.checks.every(T=>T.status==="ok"),E=n?s.length===0:_===s.length,v=d.totals.failed===0&&b&&E,I=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:v?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:v,dry_run:n,repair:d,receipts:{pending_before:s.length,reconciled:_,summaries:s.map(We)},validation:g,guidance:I,generated_at:g.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="687855bf-7432-5691-a809-1f0406b5d8a8")}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]="00dc29ff-60e0-5755-b7f1-4f69e438e87f")}catch{}})();export{md as ITEM_LATEST_TIMESTAMP_FIELDS,pd as ITEM_UNION_COLLECTION_FIELDS,Ks as MERGE_DRIVER_ARTIFACT_VALUES,ea as PM_GITATTRIBUTES_END,Yn as PM_GITATTRIBUTES_START,Ao as PM_GITATTRIBUTES_V2_END,Ht as PM_GITATTRIBUTES_V2_START,na as auditMergeAttributeFence,ra as auditMergeDriverConfiguration,Co as buildMergeAttributePatterns,bt as findGitWorkspaceRoot,gk as installMergeFence,Cd as listMergeReceipts,Ms as markMergeReceiptReconciled,xs as mergeHistoryStreams,Is as mergeItemDocuments,Os as mergeJsonDocuments,Cs as mergeRelationshipEventStreams,mk as refreshMergeAttributeFenceIfInstalled,cu as resolveMergeInstallContext,Io as resolveProjectMergeTypeFolders,ok as runMergeDriver,_k as runMergeInstall,bv as runMergeReceiptReport,TO as runMergeReconcile,We as summarizeMergeReceipt};
108
+ `)}function BS(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 If(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 GS(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 HS(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 Af(e,t){let n=e.replaceAll(/\s+/g," ").trim(),r=n.length>160?`${n.slice(0,157)}...`:n,o=HS(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} ${yn} to read piped stdin input.`}function VS(e){let t=Cf(e).trim();if(t.length===0||!t.includes(`
109
+ `)&&!t.startsWith("-")&&!t.startsWith("*")&&!t.startsWith("+"))return null;let n={},r,o=Ea(t).split(`
110
+ `).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]=If(s[3].trim()),r=a;continue}if(r&&xf.has(r.toLowerCase())){n[r]=`${n[r]}
111
+ ${i}`;continue}return null}return n}function bn(e,t){let n=Cf(e).trim();if(!n)throw new h(`${t} cannot be empty`,g.USAGE);let r=VS(n);if(r)return r;let o={},i,s=BS(n);for(let a of s){let c=GS(a);if(c>=0){let l=a.slice(0,c).trim();if(!l)throw new h(Af(e,t),g.USAGE);let d=If(a.slice(c+1).trim());o[l]=d,i=l;continue}if(i&&xf.has(i.toLowerCase())){o[i]=`${o[i]},${a}`;continue}throw new h(Af(e,t),g.USAGE)}return o}var WS=/^[A-Za-z]:[\\/]/,KS=/^(?:[-*+]\s+)?[A-Za-z_][A-Za-z0-9_.-]*\s*=/;function ka(e){let t=e.trim();return WS.test(t)?!1:KS.test(t)}function Of(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 wn(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 YS(e){if(process.stdin.isTTY===!0)throw new h(`${e} value "${yn}" 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(Ea(r))}),process.stdin.on("error",o=>{n(o)})})}function fr(){let e,t,n=async i=>{if(t&&t!==i)throw new h(`Only one option may use "${yn}" stdin token per command invocation. Already used by ${t}.`,g.USAGE);return t=i,e||(e=YS(i)),await e};return{resolveValue:async(i,s,a=!0)=>{if(!a)return i;if(i!==void 0)return i.trim()!==yn?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()===yn?f:-1).filter(u=>u>=0);if(c.length===0)return i;if(c.length>1)throw new h(`${s} accepts "${yn}" stdin token at most once per command invocation`,g.USAGE);let l=await n(s),d=[...i];return d[c[0]]=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]="411f4336-eb02-5167-9dce-ea99822a8a14")}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]="a97ee152-4d20-54f1-add9-fdb991ab6b33")}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]="4a376062-2e23-5991-80a5-27183909caf3")}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]="806bf35f-dc7e-55a8-9bb9-64be87111c22")}catch{}})();var XS={critical:0,high:1,medium:2,low:3,minimal:4},JS=Object.keys(XS),Rz=`numbers 0..4 (0=critical, 1=high, 2=medium, 3=low, 4=minimal) or names (${JS.join(", ")}), case-insensitive`;(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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 Kz=new Map(yi.map(e=>[e.toLowerCase(),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]="43a56374-808c-5fa6-bd6c-5d93175df0d2")}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]="c4e316a0-823d-5722-9e15-6d741ae44f1b")}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]="12bfc6e7-8979-58e8-8276-98cc859f3e32")}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]="d8d5f7e9-5293-564b-bc44-f5ba30336893")}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]="b5ce7132-0024-5d42-9cb8-585933beb7c7")}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]="af754be6-8026-530a-8a20-b03d4ed742e1")}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]="61c0153b-8fa5-5c26-aa88-ca9807f2d160")}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]="2c518b97-bc75-5e3f-91e8-d6779d565558")}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]="98c8d03c-bdde-5ac4-b80d-395d885f7442")}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]="4b3ad5fc-0f86-5f20-a23b-19d447cb0973")}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]="7939a590-3662-5c66-99aa-3835a0dbaecc")}catch{}})();import{createRequire as hA}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 yA=/(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|credentials|bearer|dsn)/i,eB=new RegExp(`\\b(${yA.source})\\s*[:=]\\s*([^\\s,;]+)`,"giu");var tB=hA(import.meta.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]="e896db69-ed90-53f1-a227-e3d061b3bc8d")}catch{}})();var oB=new Map([[g.USAGE,"invalid_command_usage"],[g.NOT_FOUND,"item_not_found"],[g.CONFLICT,"lock_conflict"],[g.DEPENDENCY_FAILED,"dependency_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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 wA=[{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"}],mB=new Map(wA.map(e=>[e.action,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]="3ad30a32-0f83-5473-b0a3-349e271d8378")}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]="dff9b113-2b29-5154-afbf-f191f2f556a6")}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]="376bb9d2-e202-57e7-86c8-d70a7d3fa7ab")}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]="c43dd9f2-78ac-5c22-970a-0016a06b87b3")}catch{}})();var EB=Object.freeze({"&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'","&amp;":"&"});(function(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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(){try{var e=typeof window<"u"?window:typeof 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{}})();import LB from"node:readline/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]="6783b122-a1a8-5f86-9ac5-2c3e811622ed")}catch{}})();import kA from"node:crypto";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]="26ea62d9-874d-5826-9822-83c5523b673b")}catch{}})();var XB=Ta.join("runtime","telemetry","events.jsonl"),JB=Ta.join("runtime","telemetry","state.json"),ZB=Ta.join("runtime","telemetry","otel-spans.jsonl");var QB=3600*1e3;var eG=globalThis.fetch,TA=["user","automation","test","dogfood"],tG=Promise.resolve(),nG=Promise.resolve();var rG=new Set(TA);var oG=kA.randomUUID();var Ff="(?:token|secret|password|passwd|api[_-]?key|apikey|authorization|cookie|session|credentials|bearer|literals?|regex(?:es)?|replacements?)",iG=new RegExp(`\\b(${Ff})\\s*([:=])\\s*([^\\s,;]+)`,"giu"),sG=new RegExp(`(--${Ff})(=|\\s+)([^\\s,;]+)`,"giu");(function(){try{var e=typeof window<"u"?window:typeof 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{}})();(function(){try{var e=typeof window<"u"?window:typeof 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 Sa=[{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}],$f=Sa.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),jf=Sa.filter(e=>e.repeatable===!0).map(e=>({target:e.target,keys:e.keys})),Aa=[{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}],xa=Aa.filter(e=>e.repeatable!==!0).map(e=>({target:e.target,keys:e.keys})),Uf=Aa.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 le(e){return e.map(t=>({...t}))}var Ca=[{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"}],zf=[{param:"updatedAfter",flag:"--updated-after"},{param:"updatedBefore",flag:"--updated-before"},{param:"createdAfter",flag:"--created-after"},{param:"createdBefore",flag:"--created-before"}],LA=[{param:"today",flag:"--today",booleanish:!0},{param:"recent",flag:"--recent",booleanish:!0},...zf],qf=[{param:"assignee",flag:"--assignee"},{param:"assigneeFilter",flag:"--assignee-filter"},{param:"parent",flag:"--parent"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"}],MA=[{param:"assignee",flag:"--assignee"},{param:"sprint",flag:"--sprint"},{param:"release",flag:"--release"},{param:"parent",flag:"--parent"}],FA=[...Ca,...qf],Bf=[{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"}],$A=[{param:"filterAcMissing",flag:"--filter-ac-missing"},{param:"filterEstimatesMissing",flag:"--filter-estimates-missing"},{param:"filterResolutionMissing",flag:"--filter-resolution-missing"},{param:"filterMetadataMissing",flag:"--filter-metadata-missing"}],Gf=[{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"}],Ia=[{param:"for",flag:"--for"},{param:"tokenBudget",flag:"--token-budget"},...le(Ca),...le(LA),{param:"ids",flag:"--ids"},...le(qf),...le($A),...le(Bf),...le(Gf),{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"}],Oa=[{param:"groupBy",flag:"--group-by"},{param:"sum",flag:"--sum"},{param:"avg",flag:"--avg"},...le(FA)],Ra=[{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"},...le(Ca),...le(zf),...le(MA),...le(Bf),...le(Gf),{param:"fields",flag:"--fields"},{param:"limit",flag:"--limit"},{param:"after",flag:"--after"}],Hf=[{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"}],Xo=le(Hf),Vf=[{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"}],Na=le(Vf),Wf=[{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"}],Da=le(Wf),Pa=[{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"}],La=le(Pa),Ma=le(Pa);var Fa=[{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}],$a=[{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"}];(function(){try{var e=typeof window<"u"?window:typeof 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{}})();function T(e,t,n,r={}){return{name:e,required:n,variadic:r.variadic===!0,value_kind:t,polymorphic:r.polymorphic===!0}}function Kf(e){let t=e.replaceAll("-"," ");return`${t.charAt(0).toUpperCase()}${t.slice(1)}`}var z=T("id","item_id",!0),pr=T("id","item_id",!1),mr=T("text","string",!1),_r=T("plan-id","item_id",!0),Yf=T("step","string",!0),UA=["--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"],ja=["--allow-multiple-active","--depends-on","--file","--force","--message","--step-blocked-reason","--step-body","--step-evidence","--step-owner","--step-status","--step-title","--test"],zA={"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."},vn=[{command:"plan create",parent:"plan",action:"create",slots:[T("title","string",!1,{polymorphic:!0})],accepted_flags:UA,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:[_r],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:[_r],accepted_flags:ja,description:"Append one ordered step to a Plan item.",example:'pm plan add-step pm-a1b2 --step-title "Run tests"'},...Object.entries(zA).map(([e,t])=>({command:`plan ${e}`,parent:"plan",action:e,slots:[_r,Yf],accepted_flags:ja,description:t,example:`pm plan ${e} pm-a1b2 plan-step-001`})),{command:"plan reorder-step",parent:"plan",action:"reorder-step",slots:[_r,Yf,T("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:[_r],accepted_flags:ja,description:`${Kf(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:[T("kind","string",!0),...e==="list"?[]:[T("id","string",!0)]],accepted_flags:e==="put"?["--author","--definition","--message"]:e==="remove"?["--author","--message"]:[],description:`${Kf(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:[T("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:[T("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:[T("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:[T("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:[T("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:[T("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:[T("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:[T("target","string",!0)],accepted_flags:[],description:"Delete one workspace snapshot target.",example:"pm workspace snapshot delete before-migration"}],qA=[...vn].sort((e,t)=>t.command.length-e.command.length),BA=new Map([["append",[z,mr]],["assurance",[T("action","action",!0),T("kind","string",!1),T("id","string",!1)]],["beads import",[T("file","string",!1)]],["changelog export",[T("file","string",!1)]],["claim",[pr]],["close",[z,mr]],["close-task",[z,T("reason","string",!1)]],["comments",[z,mr]],["completion",[T("shell","string",!1)]],["config",[T("scope","string",!1,{polymorphic:!0}),T("action","action",!1),T("key","string",!1),T("value","string",!1,{polymorphic:!0})]],["copy",[z]],["create",[T("type-or-title","string",!1,{polymorphic:!0}),T("title","string",!1)]],["delete",[z]],["deps",[z]],["docs",[z]],["event",[T("title","string",!0)]],["files",[z]],["files discover",[z]],["files lookup",[T("paths","string",!0,{variadic:!0})]],["focus",[pr]],["get",[z]],["graph",[T("subcommand","action",!0),pr,T("target","item_id",!1)]],["guide",[T("topic","string",!1)]],["history",[z]],["history-compact",[pr]],["history-redact",[z]],["history-repair",[pr]],["init",[T("prefix-or-path","string",!1,{polymorphic:!0})]],["item complete",[z,T("reason","string",!1)]],["item reopen",[z,T("reason","string",!0)]],["learnings",[z,mr]],["meet",[T("title","string",!0)]],["merge",[T("subcommand","action",!0),T("artifact","string",!1),T("base","string",!1),T("ours","string",!1),T("theirs","string",!1)]],["notes",[z,mr]],["package",[T("target","string",!1,{polymorphic:!0})]],["package list",[]],["package scaffold",[T("target","string",!0)]],["package upgrade",[T("target","string",!1)]],["packages",[T("target","string",!1,{polymorphic:!0})]],["packages list",[]],["packages scaffold",[T("target","string",!0)]],["packages upgrade",[T("target","string",!1)]],["pause-task",[z]],["plan",[T("subcommand","action",!0),T("id","item_id",!1,{polymorphic:!0}),T("step","string",!1),T("new-order","integer",!1)]],["profile",[T("subcommand","action",!0),T("name","string",!1)]],["release",[z]],["remind",[T("title","string",!0)]],["restore",[z,T("target","string",!0)]],["schema",[T("subcommand","action",!0),T("name","string",!1)]],["search-advanced",[T("keywords","string",!0,{variadic:!0})]],["search",[T("keywords","string",!0,{variadic:!0})]],["start-task",[z]],["telemetry",[T("namespace-or-subcommand","action",!1,{polymorphic:!0}),T("subcommand","action",!1)]],["test",[z]],["update",[z]],["workspace snapshot",[T("action","action",!0),T("target","string",!1)]],...["activate","adopt","deactivate","init","uninstall"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!0)]])),...["describe"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("target","string",!1)]])),...["install"].flatMap(e=>["extension","package","packages"].map(t=>[`${t} ${e}`,[T("targets","string",!1,{variadic:!0})]])),["vcs abandon",[z]],["vcs create",[T("title","string",!0)]],["vcs merge",[z]],["vcs propose",[z]],["vcs ref-create",[T("name","string",!0)]],["vcs show",[z]]]);function GA(e){return e.trim().toLowerCase().replace(/\s+/gu," ")}function HA(e){let t=GA(e);return qA.find(n=>n.command===t||t.startsWith(`${n.command} `))}function $(e,t,n,r,o){return o.map(i=>({command:i,noun:e,target:t,disposition:n,owner:r}))}var VA=[...$("item","item","target_noun","pm-pbyu",["item","item complete","item mutate","item reopen"]),...$("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"]),...$("item","item files","consolidation","pm-ya7x55",["files discover","files lookup"]),...$("list","list","target_noun","pm-pfqi",["list"]),...$("list","list --group-by","consolidation","pm-xkgq",["aggregate"]),...$("context","context","target_noun","pm-pbyu",["context"]),...$("context","context","consolidation","pm-kcs4",["ctx","focus","next"]),...$("search","search","target_noun","pm-pbyu",["search"]),...$("search","search","package_owned","package:search-advanced",["reindex","search-advanced"]),...$("search","search duplicates","consolidation","pm-3i9q8g",["duplicates"]),...$("graph","graph","target_noun","pm-pbyu",["graph"]),...$("graph","graph show","consolidation","pm-yql1",["deps"]),...$("history","history","target_noun","pm-pbyu",["history"]),...$("history","history","consolidation","pm-tqel",["activity","events","history-author-acknowledge","history-compact","history-redact","history-repair","merge","restore"]),...$("history","history","package_owned","package:builtin-vcs-exemplar",["vcs abandon","vcs create","vcs log","vcs merge","vcs propose","vcs ref-create","vcs show"]),...$("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"]),...$("workspace","workspace init","consolidation","pm-n7rr",["init"]),...$("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"]),...$("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"]),...$("package","package","package_owned","package:beads",["beads import"]),...$("package","package","package_owned","package:pm-changelog",["changelog export","changelog generate"]),...$("package","package calendar","package_owned","pm-o3fh",["event","meet","remind"]),...$("ops","ops","consolidation","pm-6apl",["assurance","config","eval","gc","health","profile","schema","stats","telemetry","test-all","validate"]),...$("ops","ops assurance","consolidation","pm-2tan",vn.filter(({parent:e})=>e==="assurance").map(({command:e})=>e)),...$("plan","plan","target_noun","pm-pbyu",["plan"]),...$("plan","plan","target_noun","pm-2tan",vn.filter(({parent:e})=>e==="plan").map(({command:e})=>e)),...$("contracts","contracts","target_noun","pm-pbyu",["contracts"]),...$("help","help","target_noun","pm-pbyu",["help"]),...$("help","help","package_owned","package:builtin-guide-shell",["completion","completion-statuses","completion-tags","completion-types","guide"])],WA=[...new Set(VA.map(({command:e})=>e))].map(e=>({command:e,slots:HA(e)?.slots??BA.get(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]="f73e79d8-2a65-5a25-8c6f-ec9b06651634")}catch{}})();function Ua(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{}})();var Xf=ji.map(e=>({flag:e.flag,...e.aliases?{aliases:[...e.aliases]}:{},...e.value_name?{value_name:e.value_name}:{}})),KA=[...Xf,{flag:"--version"}],Jf=[{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"}],Zf=[{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"}],Zo=Ha([{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"},...Jf,{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"])),Qf=[{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}],ep=[{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 Ha(e,t){return e.map(n=>t.has(n.flag)?{...n,cursor_semantics:"presentation"}:n)}var tp=[{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"}],np=[{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"}],rp=[{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"}],op=[{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"}],ip=[{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"}],sp=[{flag:"--dry-run"},{flag:"--output"},{flag:"--item-path"},{flag:"--prefer"}],ap=[{flag:"--id",value_name:"item-id"},{flag:"--literal"},{flag:"--regex"},{flag:"--replacement"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],cp=[{flag:"--id",value_name:"item-id"},{flag:"--all"},{flag:"--dry-run"},{flag:"--normalize-provenance"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],lp=[{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"}],dp=[{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"}],up=[{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"}],fp=[{flag:"--dry-run"},{flag:"--author"},{flag:"--force"}],Va=[{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"}],pp=[{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"}],mp=[{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"}],Wa=[{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"}],it=[{flag:"--project"},{flag:"--local"},{flag:"--global"}],_p=[...it,{flag:"--capability"}],za=[...Wa,{flag:"--declarative"}],YA=[..._p,{flag:"--declarative"}];var XA=[...it,{flag:"--markdown"},{flag:"--output"}];var JA=[...it,{flag:"--dry-run"}],ZA=[...it,{flag:"--runtime-probe"},{flag:"--fix-managed-state"}],QA=[...it,{flag:"--watch"}],ex=[...it,{flag:"--detail"},{flag:"--trace"},{flag:"--fix-managed-state"},{flag:"--isolated"},{flag:"--ignore-global"},{flag:"--strict-exit"},{flag:"--fail-on-warn"}],tx=[...it,{flag:"--fields",list:!0}],nx=[...it,{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],gp=[{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--gh"},{flag:"--github"},{flag:"--ref"}],hp=[{flag:"--dry-run"},{flag:"--cli-only"},{flag:"--packages-only"},{flag:"--project"},{flag:"--local"},{flag:"--global"},{flag:"--repair"},{flag:"--tag"},{flag:"--package-name"}];var yp=[{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"}],bp=[{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"},...Zf,{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"}],wp=[{flag:"--id",value_name:"item-id"},{flag:"--body",short:"-b"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],vp=[{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"]}],Ep=[{flag:"--id",value_name:"item-id"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],kp=[{flag:"--id",value_name:"item-id"},{flag:"--dry-run"},{flag:"--author"},{flag:"--message"},{flag:"--force"}],Tp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Sp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],Ap=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--force"}],xp=[{flag:"--id",value_name:"item-id"},{flag:"--author",aliases:["--assignee"]},{flag:"--message"},{flag:"--validate-close",value_name:"off|warn|strict"},{flag:"--force"}],Cp=[{flag:"--parent"},{flag:"--allow-missing-parent"},{flag:"--tags"},{flag:"--priority"},{flag:"--body"},{flag:"--description"},{flag:"--author"},{flag:"--message"}],Ka=[{flag:"--start"},{flag:"--duration"},{flag:"--end"},{flag:"--location"},{flag:"--timezone"},{flag:"--all-day"},...Cp],Ip=Ka,Op=[{flag:"--at"},{flag:"--text"},...Cp],Rp=[{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"}],Np=[{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"}],Dp=[{flag:"--limit"}],Pp=[{flag:"--status"},{flag:"--limit"},{flag:"--stream"},{flag:"--tail"},{flag:"--force"},{flag:"--author"}],Lp=[{flag:"--dry-run"},{flag:"--scope"}],Mp=[{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"}],Fp=[{flag:"--status",repeatable:!0,list:!0},{flag:"--since"},{flag:"--threshold"},{flag:"--limit"}],$p=[{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"}],jp=[{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"}],Ya=[{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"}],Up=[{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"}],zp=[{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"}],qp=[{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"]}],qa=[{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"},...Up,...zp,{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"}],Bp=[{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"}],Gp=[{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"}],Hp=[{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"}],Vp=[{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"}],Wp=[{flag:"--id",value_name:"item-id"},{flag:"--clear"}],Kp=[{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"},...qp,...Up,{flag:"--fixed_version"},...zp,{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"}],Yp=[{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"},...Zf,{flag:"--dry-run"},{flag:"--rollback"},{flag:"--no-checkpoint"},{short:"-t",flag:"--title"},{short:"-d",flag:"--description"},{short:"-b",flag:"--body"},...qp,{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"}],Ba=[{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"}],Xp=[{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"}],Jp=[{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"}],Ga=Ha([{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"])),Zp=[{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"}],Qp=[{flag:"--list"},{flag:"--format"},{flag:"--depth"}],em=[{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}],tm=[{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"}],nm=[{flag:"--mode"},{flag:"--k"},{flag:"--fail-under"},{flag:"--queries"},{flag:"--format"}],ot=[{flag:"--dry-run"},{flag:"--force"},{flag:"--author"},{flag:"--message"}],rm=[],om=[{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"]}],im=Ha([{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"},...Jf],new Set(["--highlight","--compact","--full","--fields","--format","--limit","--token-budget","--after"])),sm=[{flag:"--action"},{flag:"--command"},{flag:"--summary"},{flag:"--schema-only"},{flag:"--flags-only"},{flag:"--availability-only"},{flag:"--runtime-only"},{flag:"--active-only"},{flag:"--full"}],am=[{flag:"--eager-tags"}];var rx=["list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled"],ox=Zo.filter(e=>e.flag!=="--status"&&e.flag!=="--all"),ix=Zo.filter(e=>e.flag!=="--status");function Jo(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 sx=Jo(Va),ax=Jo(Ya),cx=new Map([["assurance",ax],["plan",sx],["workspace",Jo(rm)],["workspace snapshot",Jo(ot)]]);function cm(e=vn){return e.map(({command:t,parent:n,accepted_flags:r})=>{let o=cx.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 lx=cm(),i5=new Map([["list",Zo],["list-all",ix],...rx.map(e=>[e,ox]),["templates",qa],["cal",Ba],["ctx",Ga],["test-runs-worker",Pp],["init",pp],["config",mp],["extension",Wa],["package",za],["packages",za],["install",gp],["upgrade",hp],["create",qa],["item mutate",Bp],["item complete",Gp],["item reopen",Hp],["copy",Vp],["focus",Wp],["aggregate",Qf],["calendar",Ba],["context",Ga],["get",Zp],["guide",Qp],["search",im],["next",om],["eval",nm],["workspace",ot],["workspace position",rm],["workspace snapshot",ot],["workspace snapshot create",ot],["workspace snapshot list",ot],["workspace snapshot inspect",ot],["workspace snapshot restore",ot],["workspace snapshot delete",ot],["history",ip],["history-redact",ap],["history-repair",cp],["history-author-acknowledge",lp],["history-compact",dp],["merge",sp],["schema",up],["profile",fp],["plan",Va],["activity",Xp],["events",Jp],["restore",Ep],["update",Kp],["update-many",Yp],["close",yp],["close-many",bp],["delete",kp],["append",wp],["comments",ep],["notes",tp],["learnings",np],["files",rp],["docs",op],["deps",em],["graph",tm],["test",Rp],["test-all",Np],["telemetry",Dp],["health",$p],["assurance",Ya],...lx,["validate",jp],["gc",Lp],["stats",Mp],["duplicates",Fp],["contracts",sm],["completion",am],["claim",vp],["release",Tp],["start-task",Sp],["pause-task",Ap],["close-task",xp],["meet",Ka],["event",Ip],["remind",Op]]);(function(){try{var e=typeof window<"u"?window:typeof 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 lm={oneOf:[{type:"number"},{type:"array",items:{type:"string"}}]},dm={if:{required:["field"]}};Reflect.set(dm,"then",{oneOf:[{required:["equals"]},{required:["state"]}]});var um={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:[dm],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:lm,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:lm,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 gr={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:uo,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"}},fm={assurance:{definition:um,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}}},dx=["create","show","add-step","update-step","complete-step","block-step","reorder-step","remove-step","link","unlink","decision","discovery","validation","resume","approve","materialize"],Xa={subcommand:{type:"string",enum:[...dx]},stepRef:{type:"string"},reorderTo:{anyOf:[{type:"string"},{type:"number"}]},scope:{type:"string"},harness:{type:"string",enum:[...Ec]},mode:{type:"string",enum:[...vc]},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:[...Rr]},stepEvidence:{type:"string"},stepBlockedReason:{type:"string"},stepReplacement:{type:"string"},dependsOn:{type:"string"},link:{type:"string"},linkKind:{type:"string",enum:[...kc]},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"}}]}},Ja={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"]}},hr={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"]}},pm={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 fx=["json","quiet","profile","noExtensions","noPager","tokenAccounting","path","pmExecutable","timeoutMs"],px=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession","outputCursor","outputRowContract"],mx=new Set(["action","cwd","options",...Object.keys(gr).filter(e=>e!=="severity")]);var _x={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"]},bm=["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"],b5=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(gt.filter(e=>e==="upgrade"||e==="install"||e==="extension"||e==="package"||e.startsWith("extension-")||e.startsWith("package-")).map(e=>[e,["project","local","global"]]))});function Te(e){return Ua(e)}var gx=Te([...Na.map(e=>e.param),...Xo.map(e=>e.param),"assignee","closeReason","completedAt"]),wm=Te([...Da.map(e=>e.param),...Xo.map(e=>e.param),"force"]),hx=Te([...La.map(e=>e.param),...wm.filter(e=>e!=="allowMissingParent"&&e!=="completedAt"),"dryRun","rollback","noCheckpoint"]),yx=Te([...Ma.map(e=>e.param),"reason","completedAt","resolution","expectedResult","actualResult","validateClose","dryRun","rollback","noCheckpoint","author","message","force"]),mm=Te([...$a.map(e=>e.param),"past","section"]),bx=Te([...Fa.map(e=>e.param),"stream"]),Za=Te([...Ia.map(e=>e.param),"all","includeBody","noTruncate","strictRead","compact","brief","full"]),En=Za.filter(e=>e!=="all"&&e!=="status"),wx=Za.filter(e=>e!=="status"),At=[[{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"}}]],vx=[[{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}}]],Ex=Te([...Oa.map(e=>e.param),"count","completion","includeUnparented"]),kx=Te(["query","keywords","mode","semantic","hybrid","includeLinked","titleExact","phraseExact","highlight","compact","full",...Ra.map(e=>e.param)]),_m=Te(["type","tag","priority","assignee","assigneeFilter","sprint","release","parent","limit","blockedLimit","readyOnly","format","includeDecisions","tokenBudget","explainRanking"]),ge=["author","message","force"],vm=["text","reason","closeReason","completedAt","duplicateOf","validateClose","resolution","expectedResult","actualResult"],yr=["author","assignee","message","force"],Tx=["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 gm(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:Tx}}}var hm={required:["title"],optional:["start","duration","end","location","timezone","allDay","parent","allowMissingParent","tags","priority","body","description","author","message"]},ym={optional:["target","scope","dryRun","cliOnly","packagesOnly","repair","tag","packageName"]},Qo={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"]},...gm("extension"),...gm("package"),"package-upgrade":ym,install:{optional:["target","github","scope","ref"],anyOfRequired:[["target"],["github"]]},upgrade:ym,create:{required:["title","description","type","status","priority","message"],optional:gx},copy:{required:["id"],optional:["title","author","message","allowDuplicate"]},focus:{optional:["id","clear"],mutuallyExclusive:[["id","clear"]]},list:{optional:Za,mutuallyExclusiveWhen:At},"list-all":{optional:wx,mutuallyExclusiveWhen:At},"list-draft":{optional:En,mutuallyExclusiveWhen:At},"list-open":{optional:En,mutuallyExclusiveWhen:At},"list-in-progress":{optional:En,mutuallyExclusiveWhen:At},"list-blocked":{optional:En,mutuallyExclusiveWhen:At},"list-closed":{optional:En,mutuallyExclusiveWhen:At},"list-canceled":{optional:En,mutuallyExclusiveWhen:At},aggregate:{optional:Ex},guide:{optional:["list","format","depth"]},context:{optional:mm},ctx:{optional:mm},get:{required:["id"],optional:["for","tokenBudget","at","depth","full","fields","tree","treeDepth","format"]},search:{optional:kx,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:hm,event:hm,remind:{required:["title"],optional:["at","text","parent","allowMissingParent","tags","priority","body","description","author","message"]},next:{optional:[..._m,"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",...ge],anyOfRequired:[["literal"],["regex"]]},"history-repair":{optional:["id","all","dryRun","normalizeProvenance",...ge],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",...ge]},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",...bm,"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",...ge]},activity:{optional:bx},restore:{required:["id","target"],optional:ge},update:{required:["id"],optional:wm,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},"update-many":{optional:hx,mutuallyExclusive:[["acceptanceCriteria","addAc"],["acceptanceCriteria","removeAc"]]},close:{required:["id"],optional:[...vm,...ge]},"close-many":{optional:yx},delete:{required:["id"],optional:["dryRun",...ge]},append:{required:["id","body"],optional:ge},comments:{required:["id"],optional:["text","add","stdin","edit","delete","limit","full","ifAbsent",...ge],mutuallyExclusive:[["edit","ifAbsent"],["delete","ifAbsent"]]},notes:{required:["id"],optional:["text","add","addJson","stdin","edit","delete","limit","since","eventType","includeMeta","full","ifAbsent",...ge],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",...ge],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",...ge],anyOfRequired:[["id"],["lookupPath"]],dependentAnyOfRequired:[{property:"addNote",anyOfRequired:[["add"],["addGlob"]]}]},docs:{required:["id"],optional:["add","addGlob","remove","migrate","addNote","list","validatePaths",...ge],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",...ge],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:vx},completion:{required:["shell"],optional:["eagerTags"]},claim:{optional:["id","next","ifAvailable","maxAttempts","includeDecisions",..._m,...yr],oneOfRequired:[["id"],["next"]]},release:{required:["id"],optional:yr},"start-task":{required:["id"],optional:yr},"pause-task":{required:["id"],optional:yr},"close-task":{required:["id"],optional:["text","validateClose",...yr]},"item-reopen":{required:["id","reason"],optional:["status","author","message","force"]}},Sx=Object.freeze(Object.fromEntries(gt.map(e=>[e,Qo[e]])));function Em(e){return e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/[_-]/g," ").trim().replace(/^./,t=>t.toUpperCase()).concat(".")}function Ax(e,t){let n=typeof t=="object"&&t!==null?{...t}:{},r=hr[e];return{...n,description:r?.description??Em(e),...r?.examples?{examples:r.examples}:{}}}function xx(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(Ja,t))return Ja[t];let n=pm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:hr[t]}function Cx(e,t,n){let r=typeof n=="object"&&n!==null?{...n}:{},o=xx(e,t);return{...r,description:o?.description??Em(t),...o?.examples?{examples:o.examples}:{}}}function Ix(e,t){let n=fm[e];return n&&Object.prototype.hasOwnProperty.call(n,t)?n[t]:e==="plan"&&Object.prototype.hasOwnProperty.call(Xa,t)?Xa[t]:(e==="get"||e==="history"||e==="search")&&t==="format"?{type:"string",enum:["json","toon"]}:gr[t]}function Ox(e,t){let n={action:{const:e,description:hr.action?.description??"Tool action to execute."}};for(let r of t){if(r==="action")continue;let o=Ix(e,r);o&&(n[r]=Cx(e,r,o))}return n}function Rx(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 Nx(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:Te(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 km(e){if(!Object.prototype.hasOwnProperty.call(Qo,e))return;let t=Qo[e],n=_x[e]??[];return Te(["action",...fx,...Un(e)!==void 0?px:[],...n,...t.required??[],...t.optional??[]])}function Dx(e){let t=Qo[e],n=Te(t.required??[]),r=km(e),o={type:"object",additionalProperties:!1,required:["action",...n],title:`pm action "${e}" parameters`,properties:Ox(e,r)};t.anyOfRequired&&t.anyOfRequired.length>0&&(o.anyOf=t.anyOfRequired.map(s=>({required:[...s]}))),t.oneOfRequired&&t.oneOfRequired.length>0&&(o.oneOf=Rx(e,t.oneOfRequired));let i=Nx(t);return i.length>0&&(o.allOf=i),o}function Tm(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 Qa="4.10.1",Sm=Qa.split(".")[0],Am="1.4.0",Px=Tm(()=>({$schema:"https://json-schema.org/draft/2020-12/schema",$id:`https://schema.unbrained.dev/pm-cli/tool-parameters-v${Sm}.schema.json`,title:"pm-cli tool parameters (action-scoped strict schema)","x-schema-version":Qa,type:"object",oneOf:gt.map(e=>Dx(e))}));function Lx(e,t){let n=Ax(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 Mx(){let e={action:{type:"string",description:hr.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(gr).sort())e[t]=Lx(t,gr[t]);return{title:"pm-cli tool parameters (provider-compatible flat schema)","x-schema-version":Am,type:"object",additionalProperties:!1,required:["action"],properties:e}}var Fx=Tm(Mx);(function(){try{var e=typeof window<"u"?window:typeof 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 S5=new Set([...Yl,...Xl]);(function(){try{var e=typeof window<"u"?window:typeof 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]="01742f33-d1e8-5684-a585-2add88ddb73c")}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]="fde4fea5-94d6-53e2-bfbc-bff71d828c01")}catch{}})();var Wx=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),OW=new Set([...Wx].filter(e=>e!=="file"));(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b389e521-f689-5895-a5f4-08c3866b3ea3")}catch{}})();var Kx="2026-07-15T06:22:12.276Z",Yx=Date.parse(Kx),Xx=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],xm=e=>typeof e=="string"?e:"",Jx=e=>{let t=e??{},n=xm(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),o=+(Date.parse(xm(t.ts))>=Yx);return Xx[r][o]};function Zx(e,t,n=20,r=new Set,o=!1){let i=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[f,p]of t.split(/\r?\n/).entries()){let _;try{_=JSON.parse(p)}catch{continue}l+=1;let y=Jx(_);if(y!=="attributed"){if(d+=1,y==="actionable_unknown"&&r.has(`${e}:${f+1}`)){u+=1;continue}a[y]+=1,o&&y==="actionable_unknown"&&s.push({item_id:e,line:f+1}),i.length<c&&i.push({item_id:e,line:f+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:i,samples_truncated:a.legacy_unknown+a.actionable_unknown>i.length,actionable_events:s}}function Qx(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let i=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof i!="object"||i===null||!Array.isArray(i.events)))for(let s of i.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var Cm=async(e,t=20,n=!1)=>{let r=tc.join(e,"history"),o;try{o=(await ec.readdir(r)).filter(E=>E.endsWith(".jsonl")).sort((E,v)=>E.localeCompare(v))}catch{o=[]}let i=new Set,s=[],a=[],c=0,l=0,d=0,u=0,f=0,p=0,_="_workspace.jsonl",y=new Set;if(o.includes(_))try{y=Qx(await ec.readFile(tc.join(r,_),"utf8"))}catch{y=new Set}for(let E of o){let v;try{v=await ec.readFile(tc.join(r,E),"utf8")}catch{continue}let C=E.slice(0,-6),k=Zx(C,v,t-s.length,y,n);c+=1,l+=k.checked_events,d+=k.unknown_event_count,u+=k.legacy_unknown_event_count,f+=k.actionable_unknown_event_count,p+=k.acknowledged_actionable_event_count,k.unknown_event_count>0&&i.add(C),s.push(...k.samples),n&&a.push(...k.actionable_events)}let b=u+f;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:f,acknowledged_actionable_event_count:p,affected_item_ids:[...i].sort((E,v)=>E.localeCompare(v)),samples:s,samples_truncated:b>s.length,...n?{actionable_events:a}:{}}};import eC from"node:fs/promises";import De from"node:path";import tC from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="accd0229-6974-5950-8cea-74f517706878")}catch{}})();var nC=["path","scope","note"],rC=["pattern","glob","path","scope","note"],oC=["path"],iC=["from","to"],sC=new Set(["note","scope"]);function Om(e){let t=e??"project";if(!bi.includes(t))throw new h(`Invalid scope "${e}". Valid scopes: ${bi.join(", ")} (default: project).`,g.USAGE);return t}function nc(e){if(e.startsWith("```")||e.includes(`
112
+ `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e))return!0;let t=e.indexOf(","),n=e.slice(0,t>=0?t:e.length),r=n.indexOf("=");return r>=0&&!/\s/u.test(e)&&(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)||/^(?:[A-Za-z]:[\\/]|[\\/]{1,2}|\.\.?(?:[\\/]))/u.test(e)||[e.indexOf("/"),e.indexOf("\\")].some(o=>o>=0&&o<r))?!1:n.includes("=")||ka(e)}function aC(e){let t=0;for(let n of e)if(n==="("&&(t+=1),n===")"&&(t-=1),t<0)return!1;return t===0}function cC(e){if(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(e)&&!nc(e))return{path:e,scope:"project",note:void 0};let t=e.indexOf("](");if(e.startsWith("[")&&t>0&&e.endsWith(")")){let i=e.slice(t+2,-1).trim();if(i.length>0&&aC(i))return{path:i,scope:"project",note:e.slice(1,t).trim()||void 0}}let n=e.indexOf(",");if(n<0)return;let r=e.slice(0,n).trim(),o=e.slice(n+1).trim();if(!(r.length===0||!/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(o)))return{path:o,scope:"project",note:r}}function lC(e,t){return e?e.flatMap(n=>{let r=n.trim();if(t==="doc"){let i=cC(r);if(i!==void 0)return[i]}Of(r,"--add",`${t} path`,nc(r));let o=nc(r)?bn(n,"--add"):{path:r};if(wn(o,"--add",nC),!o.path)throw new h(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return[{path:o.path,scope:Om(o.scope),note:o.note?.trim()||void 0}]}):[]}function dC(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=bn(n,"--add-glob");wn(r,"--add-glob",rC);let o=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!o)throw new h("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:o,scope:Om(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function uC(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=bn(n,"--remove"),o=Object.keys(r).filter(i=>sC.has(i.toLowerCase()));if(o.length>0)throw new h(`--remove identifies a linked artifact by path only and does not accept ${o.map(i=>`"${i}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(wn(r,"--remove",oC),!r.path)throw new h("--remove key/value form requires path=<value>",g.USAGE);return r.path}return n}):[]}function fC(e){return e?e.map(t=>{let n=bn(t,"--migrate");wn(n,"--migrate",iC);let r=n.from?.trim(),o=n.to?.trim();if(!r||!o)throw new h("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:r,to:o}}):[]}function br(e,t){let n=e;for(let r of t)n.startsWith(r.from)&&(n=`${r.to}${n.slice(r.from.length)}`);return n}function pC(e,t,n=[]){if(e.length===0||t.length===0)return;let r=new Set(e.map(i=>br(i.path,n))),o=[...new Set(t.map(i=>br(i,n)).filter(i=>r.has(i)))].sort((i,s)=>i.localeCompare(s));if(o.length!==0)throw new h(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${o.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,g.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function ei(e){return e.split(De.sep).join("/")}function rc(e,t,n=process.cwd()){let r=e.trim();if(dr(r))return r;if(De.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return ei(r.replaceAll("\\",De.sep));let o=De.relative(t,n);return o.startsWith(`..${De.sep}`)||o===".."||De.isAbsolute(o)?ei(De.normalize(r)):ei(De.relative(t,De.resolve(n,r)))}async function mC(e,t=process.cwd(),n=process.cwd()){let r=[];for(let o of e){let i=De.isAbsolute(o.pattern),s=await tC(o.pattern,{cwd:n,absolute:i,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>rc(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)r.push({path:c,scope:o.scope,note:o.note})}return r}function _C(e,t,n){if(t===void 0)return e;if(!n)throw new h("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let r=t.trim();return r.length===0?e:e.map(o=>o.note===void 0?{...o,note:r}:o)}function gC(e){return`${e.path}::${e.scope}`}function Rm(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function Nm(e){return[...new Map(e.map(t=>[gC(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function hC(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),r=[],o=[],i=[],s=[];for(let a of n){if(dr(a)){s.push(a.trim());continue}let c=De.isAbsolute(a)?a:De.resolve(t,a);try{(await eC.stat(c)).isFile()?r.push(a):i.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&xn(l)){o.push(a);continue}i.push(a)}}return{checked:n.length,existing_files:r,missing_paths:o,non_file_paths:i,remote_references:s}}function yC(e,t,n,r){let o=0;for(let s=0;s<e.length;s+=1){let a=br(e[s].path,r);a!==e[s].path&&(e[s]={...e[s],path:a},o+=1)}return{adds:t.map(s=>{let a=br(s.path,r);return a!==s.path&&(o+=1),{...s,path:a}}),removes:n.map(s=>br(s,r)),count:o}}function bC(e,t,n,r){for(let i of t)e.some(s=>s.path===i.path&&s.scope===i.scope)||e.push(i);if(n.length>0)for(let i=e.length-1;i>=0;i-=1)n.includes(e[i].path)&&e.splice(i,1);let o=Nm(e);return r?o:Rm(o)}async function Im(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths||e.changed?await hC(t,e.workspaceRoot):void 0}}async function ti(e,t,n,r){let{metadataKey:o}=r,i=fr(),s=re(process.cwd(),n.path),a=Wr(s),c=process.cwd();await Oe(s);let l=await te(s),d=ue(l,Y()),u=await i.resolveList(t.add,"--add"),f=await i.resolveList(t.addGlob,"--add-glob"),p=await i.resolveList(t.remove,"--remove"),_=await i.resolveList(t.migrate,"--migrate"),y=lC(u,r.bareNoun).map(se=>({...se,path:rc(se.path,a,c)})),b=dC(f),E=await mC(b,a,c),v=_C([...y,...E],t.note,y.length>0||b.length>0),C=uC(p).map(se=>rc(se,a,c)),k=fC(_);if(pC(v,C,k),!(v.length>0||C.length>0||k.length>0)){let se=await Ue(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!se)throw new h(`Item ${e} not found`,g.NOT_FOUND);let W=(await Ne(se,{schema:l.schema})).document.metadata[o]??[];return Im({id:se.id,artifacts:W,changed:!1,options:t,workspaceRoot:a})}let P=Fe(t.author,l.author_default),M=await Ho({pmRoot:s,settings:l,id:e,op:r.op,author:P,message:t.message,force:t.force,skipNoop:!0,mutate(se){let O=se.metadata,W=O[o]??[],ze=[...W],ct=yC(ze,v,C,k),kn=bC(ze,ct.adds,ct.removes,r.supportsAppendStable&&t.appendStable===!0);kn.length>0?O[o]=kn:delete O[o];let mc=!xe(W,kn);return{changedFields:mc?[o]:[],warnings:mc&&ct.count>0?[`path_migrations_applied:${ct.count}`]:[]}}}),L=M.item[o]??[],V=M.warnings.find(se=>se.startsWith("path_migrations_applied:")),J=V?Number(V.slice(24)):0;return Im({id:M.item.id,artifacts:L,changed:M.changedFields.includes(o),migrationsApplied:J,options:t,workspaceRoot:a})}function ni(e,t){let n={};for(let[r,o]of Object.entries(e))n[r==="artifacts"?t:r]=o;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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Dm(e,t,n){let r=await ti(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ni(r,"docs")}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}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]="ed504f2b-8b78-5fca-a4a7-7b0709a65533")}catch{}})();async function Pm(e,t,n){let r=await ti(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ni(r,"files")}import{readFileSync as wC}from"node:fs";import ri 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]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var vC=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Fm=new Set(["--pm-path","--path","--author"]),EC={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},kC=new Set(["-p","--package"]),TC=new Set(["-c","--call"]),SC=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),AC=new Set(["-C","--prefix","--userconfig","--cache"]);var xC=new Set(["exec","x"]);function CC(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function IC(e,t=process.cwd()){let n=OC(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[r,...o]=n;if(Lm(r)||Mm(r,t))return o;if(r==="node"&&o[0]&&Mm(o[0],t))return o.slice(1);let i=r==="npx"||r==="bunx"?oc(o):r==="pnpm"?DC(o):r==="npm"?PC(o):null;return i&&(Lm(i.command)||NC(i.command))?i.args:null}var $m=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let o=n.slice(0,r);if(o.length===0)return[];let i=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of CC(i)){let c=IC(a),l=c?LC(c):null,d=l&&vC.has(l.subcommand)?MC(l.remaining,EC[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${o}-`)===!0&&u.length>o.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function OC(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function Lm(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function RC(e){let t=e.trim();if(!t.startsWith("@")){let o=t.indexOf("@");return o===-1?t:t.slice(0,o)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function NC(e){let t=RC(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Mm(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let r=ri.resolve(t,e);try{return JSON.parse(wC(ri.join(ri.dirname(ri.dirname(r)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function oc(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let o=/^(?:-c|--call)=(.*)$/.exec(r);if(o){let i=o[1];return i?{command:i,args:e.slice(t+1)}:null}if(TC.has(r)){t+=1;break}t+=kC.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function jm(e,t){let n=0;for(;n<e.length;){let r=e[n];if(r==="--"){n+=1;continue}if(r.startsWith("-")){if(r.includes("=")){n+=1;continue}if(t.has(r)){n+=2;continue}n+=1;continue}return{subcommand:r,args:e.slice(n+1)}}return null}function DC(e){let t=jm(e,SC);return t?.subcommand!=="dlx"?null:oc(t.args)}function PC(e){let t=jm(e,AC);return!t||!xC.has(t.subcommand)?null:oc(t.args)}function LC(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Fm.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function MC(e,t=new Set){for(let n=0;n<e.length;n+=1){let r=e[n];if(r==="--")return e[n+1];if(!r.startsWith("-"))return r;!r.includes("=")&&(Fm.has(r)||t.has(r))&&(n+=1)}}import{execFile as FC}from"node:child_process";import{readFile as $C}from"node:fs/promises";import jC from"node:path";import{promisify as UC}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="30a61f26-5db8-50ba-af37-1990a4742ce8")}catch{}})();var zC=UC(FC),ic=1,qC="linked-test-trust.json";function BC(e){return jC.join(Yr(e),qC)}function Um(){return{version:ic,acknowledged:{}}}async function GC(e){try{let t=JSON.parse(await $C(BC(e),"utf8"));return t.version!==ic||typeof t.acknowledged!="object"||t.acknowledged===null||Array.isArray(t.acknowledged)?Um():{version:ic,acknowledged:t.acknowledged}}catch{return Um()}}async function zm(e=process.cwd()){let t=process.env.GITHUB_HEAD_REF?.trim()||process.env.GITHUB_REF_NAME?.trim();if(t&&t!=="merge")return t;try{let{stdout:n}=await zC("git",["symbolic-ref","--quiet","--short","HEAD"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),r=n.trim();return r.length===0?void 0:r}catch{return}}function qm(e=process.cwd()){return process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||e}function HC(e){return e===null||typeof e!="object"?!1:typeof e.author=="string"&&e.author.trim().length>0&&typeof e.created_at=="string"&&Pe(e.created_at)&&(e.source_kind==="local_mutation"||e.source_kind==="merge_union")}function wr(e,t){return{...e?{source_ref:e}:{},...t?{current_source_ref:t}:{}}}function VC(e){return ae(R({command:e.command??null,path:e.path??null,scope:e.scope,pm_context_mode:e.pm_context_mode??null,workspace_context_mode:e.workspace_context_mode??null,env_set:e.env_set??null,env_clear:e.env_clear??null,shared_host_safe:e.shared_host_safe??null,provenance:e.provenance??null,provenance_invalid:e.provenance_invalid??null}))}function WC(e,t,n){let r=VC(e),o=e.provenance?.source_ref;if(e.provenance===void 0&&e.provenance_invalid!==!0)return{fingerprint:r,trusted:!0,reason:"legacy"};let i=Object.hasOwn(n.acknowledged,r);return e.provenance_invalid===!0||!HC(e.provenance)?i?{fingerprint:r,trusted:!0,reason:"acknowledged",...wr(void 0,t)}:{fingerprint:r,trusted:!1,reason:"invalid_provenance",...wr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o===void 0?{fingerprint:r,trusted:!0,reason:"local_mutation",...wr(void 0,t)}:e.provenance.source_kind==="local_mutation"&&o!==void 0&&o===t?{fingerprint:r,trusted:!0,reason:"local_source_ref",source_ref:o,current_source_ref:t}:i?{fingerprint:r,trusted:!0,reason:"acknowledged",...wr(o,t)}:{fingerprint:r,trusted:!1,reason:"foreign_source_ref",...wr(o,t)}}async function Bm(e,t,n){let r=await GC(e);return t.map(o=>WC(o,n,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]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Gm(e){return e.includeBody?Go(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):sr(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8bec3c39-b871-5c7c-907c-6da66274d9be")}catch{}})();var KC=5;async function Hm(e,t,n){let r=await Vo(e,t),i=[["validate_history_drift_missing_streams",r.missingStreams.length],["validate_history_drift_unreadable_streams",r.unreadableStreams.length],["validate_history_drift_hash_mismatches",r.hashMismatches.length],["validate_history_drift_chain_mismatches",r.chainMismatches.length],["validate_history_drift_version_skews",r.versionSkews.length],["validate_history_drift_workspace_state_mismatches",r.workspaceStateMismatches.length],["validate_history_drift_workspace_state_missing",r.workspaceStateMissing.length],["validate_history_drift_workspace_state_unreadable",r.workspaceStateUnreadable.length]].filter(([,c])=>c>0).map(([c,l])=>`${c}:${l}`),s=n?Number.POSITIVE_INFINITY:KC,a=r.driftedItems.slice(0,s);return{check:{name:"history_drift",status:i.length===0?"ok":"warn",ok:i.length===0,details:{checked_items:t.length,drifted_items_count:r.driftedItems.length,drifted_items:a,drifted_items_truncated:a.length<r.driftedItems.length,counts:{missing_streams:r.missingStreams.length,unreadable_streams:r.unreadableStreams.length,hash_mismatches:r.hashMismatches.length,chain_mismatches:r.chainMismatches.length,version_skews:r.versionSkews.length,workspace_state_mismatches:r.workspaceStateMismatches.length,workspace_state_missing:r.workspaceStateMissing.length,workspace_state_unreadable:r.workspaceStateUnreadable.length},workspace_state_mismatches:r.workspaceStateMismatches,workspace_state_missing:r.workspaceStateMissing,workspace_state_unreadable:r.workspaceStateUnreadable,version_skews:r.versionSkews.slice(0,s)}},warnings: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]="77a3c404-bbcd-5a5e-80bf-cb61c45af55d")}catch{}})();function sc(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),o=[n],i=new Set([n]),s=a=>{for(let c of(t.get(a)??[]).filter(l=>r.has(l))){if(c===n&&o.length>1)return o.push(n),!0;if(!i.has(c)){if(i.add(c),o.push(c),s(c))return!0;o.pop(),i.delete(c)}}return!1};return s(n)?[...o]:[...e,n]}function YC(e,t){if(typeof e!="string")return;let n=e.trim().toLowerCase();return n.length>0?t.get(n):void 0}function XC(e,t,n,r){for(let o of e.dependencies??[]){if(typeof o!="object"||o===null||typeof o.id!="string")continue;let i=r.resolve(o.kind);if(!i?.hierarchy)continue;let s=n.get(o.id.toLowerCase());s&&(i.hierarchyDirection==="source_parent"?t.get(s).push(e.id):t.get(e.id).push(s))}}function Vm(e,t=Yt()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),r=new Map(e.map(o=>[o.id,[]]));for(let o of[...e].sort((i,s)=>i.id.localeCompare(s.id))){let i=r.get(o.id),s=YC(o.parent,n);s&&i.push(s),XC(o,r,n,t)}for(let[o,i]of r)r.set(o,[...new Set(i)].sort());return r}function Wm(e,t,n=Yt()){let r=ba(e,s=>t?Ti(s,t):s==="closed"||s==="canceled",n),o=Vm(e,n),i=r.cycles.map(s=>s.item_ids);return{cycle_count:i.length,active_cycle_count:r.cycles.filter(s=>!s.legacy_terminal).length,legacy_cycle_count:r.cycles.filter(s=>s.legacy_terminal).length,cycle_item_ids:[...new Set(i.flat())].sort(),cycle_sample_paths:i.map(s=>sc(s,o).join("->")),cardinality_violation_count:r.cardinality_violations.length,active_cardinality_violation_count:r.cardinality_violations.filter(s=>!s.legacy_terminal).length,legacy_cardinality_violation_count:r.cardinality_violations.filter(s=>s.legacy_terminal).length,cardinality_violation_rows:r.cardinality_violations.map(s=>`${s.child_id}:${s.parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`),parent_divergence_count:r.divergences.length,active_parent_divergence_count:r.divergences.filter(s=>!s.legacy_terminal).length,legacy_parent_divergence_count:r.divergences.filter(s=>s.legacy_terminal).length,parent_divergence_rows:r.divergences.map(s=>`${s.child_id}:scalar=${s.scalar_parent_id}:dependencies=${s.dependency_parent_ids.join(",")}:${s.legacy_terminal?"legacy":"active"}`)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cd7acf28-cb93-516e-9058-54c32625ec26")}catch{}})();function Km(e,t,n=25){let r=e.definitions.filter(s=>s.roles.length===0).map(s=>s.id).sort((s,a)=>s.localeCompare(a)),o=new Set(r),i=t.filter(s=>{let a=tn(s.status,e);return a!==void 0&&o.has(a)}).map(s=>s.id).sort((s,a)=>s.localeCompare(a));return{roleless_status_count:r.length,roleless_statuses:r.slice(0,n),roleless_statuses_truncated:r.length>n,affected_item_count:i.length,affected_item_ids:i.slice(0,n),affected_item_ids_truncated:i.length>n}}function Ym(e){return e.roleless_status_count===0?[]:[`schema_status_missing_lifecycle_role:${e.roleless_status_count}`]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="de2cc648-965a-59c9-b688-0fe12edeec82")}catch{}})();function xt(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ac(e){return xt(e).replace(/\/+$/,"")}function Xe(e){let t=de(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))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]="cde10e58-cfeb-5718-a471-3e4acf46cfe7")}catch{}})();var eI=["src","tests","docs"],tI=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],nI=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),rI=["resolution","expected_result","actual_result"],oI=["default","tracked-all","tracked-all-strict"],Xm=["core","strict","custom"],si=["off","warn","error"],dc=["author","acceptance_criteria","estimated_minutes","close_reason"],e_=[...dc,"reviewer","risk","confidence","sprint","release"],pc=Array.from(new Set(e_)),iI={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},sI={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},aI={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},cI={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},lI={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},dI=32*1024*1024,uI=1e4,t_=40,at=5,fI=4096,pI=255,mI=QC(ZC);function n_(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?n_(r):r);return t}function _I(e){return{...e,checks:e.checks.map(t=>({...t,details:n_(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function ci(e,t){return Dt(e,t)??e}function vr(e,t){return t.terminal_statuses.has(ci(e,t))}function Ct(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function oi(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function gI(e){let t=Ct(gi),n={blocked_reason:Ct(Ot.blocked_reason),resolution:Ct(Ot.resolution),actual_result:Ct(Ot.actual_result)},r=Ct(e.validation.lifecycle_stale_blocker_reason_patterns),o={blocked_reason:Ct(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:Ct(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:Ct(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:oi(r,t)?"default":"settings",closure_like_metadata_field_patterns:o,closure_like_metadata_field_pattern_sources:{blocked_reason:oi(o.blocked_reason,n.blocked_reason)?"default":"settings",resolution:oi(o.resolution,n.resolution)?"default":"settings",actual_result:oi(o.actual_result,n.actual_result)?"default":"settings"}}}function hI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Xm.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${Xm.join(", ")}.`,g.USAGE)}function yI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(si.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${si.join(", ")}.`,g.USAGE)}function bI(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(si.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${si.join(", ")}.`,g.USAGE)}function wI(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>iI[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function vI(e,t,n){let r=wI(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...dc],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...e_],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:r.length>0?{profile:e,profile_source:t,required_fields:r,configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...dc],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var EI=new Set(["acceptance_criteria","estimated_minutes"]);function kI(e,t,n,r){return!r&&EI.has(t)&&vr(e.status,n)?!1:t==="author"?!de(e.author):t==="acceptance_criteria"?!de(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?ci(e.status,n)===n.close_status&&!de(e.close_reason):t==="reviewer"?!de(e.reviewer):t==="risk"?!de(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!de(e.confidence):t==="sprint"?!de(e.sprint):!de(e.release)}function TI(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new h(`Unknown --scan-mode value "${e}". Supported values: ${oI.join(", ")}.`,g.USAGE)}function SI(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return he.resolve(t);let n=he.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return he.dirname(he.dirname(n));let o=he.resolve(process.cwd()),i=Jm(n),s=Jm(o),a=he.relative(i,s);return a.length===0||!a.startsWith("..")&&!he.isAbsolute(a)?n:o}function Jm(e){try{return JC.native(e)}catch{return he.resolve(e)}}function AI(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function r_(e,t,n){let r=t.length>0?he.join(e,t):e,o;try{o=await fc.readdir(r,{withFileTypes:!0})}catch(i){if(K(i))return;throw i}for(let i of o){if(i.name.startsWith("."))continue;let s=t.length>0?he.join(t,i.name):i.name;if(i.isDirectory()){if(nI.has(i.name))continue;await r_(e,s,n);continue}i.isFile()&&n.push(xt(s))}}async function Zm(e){let t=[];for(let n of eI)await r_(e,n,t);for(let n of tI){let r=he.join(e,n);try{(await fc.stat(r)).isFile()&&t.push(xt(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function xI(e){try{let{stdout:t}=await mI("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:dI,windowsHide:!0,timeout:uI}),n=t.split("\0").map(r=>xt(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,o)=>r.localeCompare(o))}catch{return null}}function CI(e,t){let n=new Set,r=ac(Xt);r.length>0&&n.add(r);let o=ac(he.relative(t,e));return o.length>0&&!o.startsWith("..")&&n.add(o),[...n].sort((i,s)=>i.localeCompare(s))}function Qm(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function II(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await xI(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let o=await Zm(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:o,candidateTotal:o.length,candidateScanned:o.length}}let n=await Zm(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function X(e,t=at){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function It(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=X(e,t_);return{values:n.values,truncated:n.truncated,total:e.length}}var OI={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},RI={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function NI(e){let t=e.missing_fields.map(n=>`${OI[n]} "${RI[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function DI(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,o=r?n.filter(s=>typeof s=="string"):ef(t);if(o.length===0)return;let i=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:o,...i?{fix_hints_truncated:!0}:{}}}function PI(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var LI="validate_metadata_duplicate_issue_codes";function MI(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:at,r=e.slice(0,n);return{rows:r.map(i=>({code:i.code,count:i.count,ids:i.ids,titles:i.titles,remediation_hint:`Items ${i.ids.join(", ")} share issue code "${i.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${LI}:${e.length}`]}}function FI(){return Object.fromEntries(pc.map(e=>[e,[]]))}function $I(e,t,n){let r=FI();for(let o of e)for(let i of pc)kI(o,i,t,n)&&r[i].push(o.id);return r}function jI(e,t,n){let r=[...e.warnings];for(let o of e.required_fields){let i=t[o];i.length>0&&r.push(`${sI[o]}:${i.length}`)}return r.push(...n),r}function UI(e,t){let n={};for(let r of e.required_fields){let o=t[r],i=o?o.length:0,s=aI[r];n[s]=i}return n}function zI(e,t,n){let r=[];for(let o of e.required_fields){let i=t[o];if(i)for(let s of i){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";r.push({item_type:c,field:o})}}return r}function qI(e,t,n,r){for(let o of t.required_fields){let i=n[o];if(!i||i.length===0)continue;let s=cI[o],a=lI[o];if(!s||!a)continue;let c=X(i,r?i.length:at);e[s]=c.values,e[a]=c.truncated}}function BI(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(o=>({id:o,resolution:de(n.get(o)?.resolution)})):[]}function GI(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(o=>({id:o,type:de(n.get(o)?.type)})):[]}function HI(e,t,n,r,o){let i=new Map(e.map(E=>[E.id,E])),s=t.profile==="strict",a=$I(e,n,s),c=uf(e,{configuredPrefixes:o}),l=MI(c,r),d=jI(t,a,l.warnings),u=UI(t,a),f=zI(t,a,i),p=ff(f),_={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...pc],counts:u,missing_by_type:p,duplicate_issue_codes_count:c.length,duplicate_issue_codes:l.rows,duplicate_issue_codes_truncated:l.truncated};t.configured_custom_fields.length>0&&(_.configured_custom_required_fields=[...t.configured_custom_fields]),qI(_,t,a,r);let y=BI(t,a,i),b=GI(t,a,i);return{check:{name:"metadata",status:d.length===0?"ok":"warn",ok:d.length===0,details:_},warnings:d,closeReasonBackfillRows:y,estimateBackfillRows:b}}function VI(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let o=e.filter(f=>r.has(ci(f.status,t))),i=[],s=[];for(let f of o){let p=rI.filter(_=>!de(f[_]));p.length!==0&&(i.push({id:f.id,missing_fields:p}),s.push({id:f.id,missing_fields:p,close_reason:de(f.close_reason)}))}let a=i.length>0?[`validate_resolution_missing_fields:${i.length}`]:[],c=n?Number.POSITIVE_INFINITY:at,l=X(i.map(f=>`${f.id}:${f.missing_fields.join(",")}`),c),d=i.map(f=>NI(f)),u=X(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:o.length,missing_resolution_items:i.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function WI(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function KI(e,t="pm",n=dn()){let r=new Set(e.map(i=>i.id)),o=[...e].sort((i,s)=>i.id.localeCompare(s.id));return new Map(o.map(i=>{let s=new Set,a=Xe(i.blocked_by);a&&r.has(a)&&s.add(a),(i.dependencies??[]).filter(l=>{let d=Xe(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>Xe(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=Xe(i.definition_of_ready);return XI(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[i.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function YI(e,t,n){let r=vf(e,n?d=>vr(d,n):void 0),o=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),i=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:at,a=X(o,s),c=X(i,s),l=X(r.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:o.length===0?"ok":"warn",ok:o.length===0,details:{checked_items:e.length,dangling_reference_count:o.length+i.length,active_dangling_reference_count:o.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:i.length,legacy_closed_dangling_reference_count:r.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:r.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:o.length>0?[`validate_dangling_dependency_references:${o.length}`]:[]}}function XI(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${WI(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(o=>o[1].toLowerCase()))].sort((o,i)=>o.localeCompare(i))}function JI(e){let t=0,n=new Map,r=new Map,o=[],i=new Set,s=[],a=d=>{n.set(d,t),r.set(d,t),t+=1,o.push(d),i.add(d);for(let f of e.get(d)??[])n.has(f)?i.has(f)&&r.set(d,Math.min(r.get(d),n.get(f))):(a(f),r.set(d,Math.min(r.get(d),r.get(f))));if(r.get(d)!==n.get(d))return;let u=[];for(;o.length>0;){let f=o.pop();if(i.delete(f),u.push(f),f===d)break}u.sort((f,p)=>f.localeCompare(p)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function ZI(e,t="pm"){let n=KI(e,t),r=JI(n),o=[...new Set(r.flat())].sort((s,a)=>s.localeCompare(a)),i=r.map(s=>sc(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:o,cycle_sample_paths:i}}function QI(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function ai(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function eO(e,t){let n=ai(e).split("/").filter(Boolean),r=ai(t).split("/").filter(Boolean),o=0;for(;o<n.length&&o<r.length&&n[o]===r[o];)o+=1;return o}function tO(e,t){let n=ai(t),r=ai(e),o=t.endsWith("/")?t:`${t}/`,i=e.startsWith(o),s=n.length>0&&n===r,a=eO(e,t);return!i&&!s&&a===0?null:i?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function nO(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function rO(e,t,n){let r=t==="docs_unowned"?"docs":"files",o;return n.flatMap(i=>(r==="docs"?i.docs??[]:i.files??[]).map(s=>({item:i,link:s}))).forEach(({item:i,link:s})=>{if(s.scope!=="project")return;let a=xt(s.path);if(a.length===0||a===e)return;let c=tO(e,a);c!==null&&nO(o,i,c.score)&&(o={item:i,score:c.score,confidence:c.confidence})}),o?{id:o.item.id,type:o.item.type,title:o.item.title,status:o.item.status,confidence:o.confidence}:null}function oO(e,t){return e.map(n=>{let r=QI(n),o=r==="docs_unowned"?"docs":"files",i=rO(n,r,t),s=i?.id??"<id>";return{path:n,classification:r,owner_candidate:i,remediation_hint:`pm ${o} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function iO(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function sO(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let o=Xe(e[n]);return o?r.some(i=>o.toLowerCase().includes(i)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function aO(e,t,n,r,o){let i=Xe(t.parent),s=i?n.get(r.get(i.toLowerCase())??i):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!vr(s.status,o)}}function cO(e,t,n,r){let o=Xe(e.blocked_by),i=Xe(e.blocked_reason),s=i?.toLowerCase(),a=ci(e.status,n),c=[];return t.has(a)?(!o&&!i&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&r.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(o&&c.push("non_blocked_status_has_blocked_by"),i&&c.push("non_blocked_status_has_blocked_reason"),c)}function lO(e,t,n,r){let o=new Map(e.map(c=>[c.id,c])),i=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!vr(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=sO(c,r);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=Xe(c.parent),u=d?o.get(i.get(d.toLowerCase())??d):void 0;if(u&&vr(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(aO(c,u,o,i,n))),t){let f=cO(c,s,n,r);f.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(f)].sort((p,_)=>p.localeCompare(_))})}}return a}function dO(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function ii(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function cc(e,t,n){return n>0&&t!=="off"?`${e}:${n}`:null}function uO(e,t,n,r,o){let i=[];e.closureLikeRows.length>0&&i.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&i.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&i.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let s=ii("validate_lifecycle_dependency_cycles",n,o.dependencyCycles),a=ii("validate_hierarchy_parent_cycle",r,o.activeHierarchyCycles),c=ii("validate_hierarchy_cardinality_violation",r,o.activeHierarchyCardinality),l=ii("validate_hierarchy_parent_divergence",r,o.activeHierarchyDivergence),d=cc("validate_legacy_hierarchy_parent_cycle",r,o.legacyHierarchyCycles),u=cc("validate_legacy_hierarchy_cardinality_violation",r,o.legacyHierarchyCardinality),f=cc("validate_legacy_hierarchy_parent_divergence",r,o.legacyHierarchyDivergence);return[...i,...s?[s]:[],...a?[a]:[],...c?[c]:[],...l?[l]:[],...d?[d]:[],...u?[u]:[],...f?[f]:[]]}function fO(e){let t=xt(e);return t.length>fI||t.split(/[\\/]/).some(n=>n.length>pI)}async function pO(e,t){let n=he.isAbsolute(t)?t:he.resolve(e,t);if(fO(n))return!1;try{let r=await fc.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return AI(r,["ENOENT","ENOTDIR"])}}async function mO(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(o=>[...(o.files??[]).map(i=>({item:o,artifact:i,link_kind:"files"})),...(o.docs??[]).map(i=>({item:o,artifact:i,link_kind:"docs"}))]);for(let{item:o,artifact:i,link_kind:s}of r){if(i.scope!=="project")continue;if(dr(i.path)){n.remoteLinkedPaths.add(i.path.trim());continue}let a=xt(i.path);a.length!==0&&(n.linkedProjectPaths.add(a),await pO(t,i.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:o.id,path:a,link_kind:s})))}return n}function _O(e,t,n,r,o,i){let s=r==="tracked-all-strict",a=s&&!o,c=o||s,l=c?[]:CI(t,n),d=l.length===0?[]:e.candidateFiles.filter(p=>Qm(p,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(p=>!Qm(p,l)),f={};if(d.length>0){let p=It(d,i);f.pm_internals={count:d.length,paths:p.values,paths_truncated:p.truncated,paths_total:p.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:f}}function gO(e,t,n,r,o,i,s,a="pm"){let c=lO(e,t,o,i);dO(c);let l=ZI(c.activeItems,a),d=Wm(e,o),u=Km(o,e,s?Number.POSITIVE_INFINITY:at),f=[...uO(c,t,n,r,{dependencyCycles:l.cycle_count,activeHierarchyCycles:d.active_cycle_count,activeHierarchyCardinality:d.active_cardinality_violation_count,activeHierarchyDivergence:d.active_parent_divergence_count,legacyHierarchyCycles:d.legacy_cycle_count,legacyHierarchyCardinality:d.legacy_cardinality_violation_count,legacyHierarchyDivergence:d.legacy_parent_divergence_count}),...Ym(u)],p=s?Number.POSITIVE_INFINITY:at,_=X(c.closureLikeRows.map(L=>`${L.id}:${L.fields.join(",")}`),p),y=X(c.terminalParentRows.map(L=>`${L.id}:${L.parent_id}:${L.parent_status}`),p),b=X(c.staleBlockerRows.map(L=>`${L.id}:${L.status}:${L.reasons.join(",")}`),p),E=X(l.cycle_item_ids,p),v=X(l.cycle_sample_paths,p),C=X(d.cycle_item_ids,p),k=X(d.cycle_sample_paths,p),S=X(d.cardinality_violation_rows,p),P=X(d.parent_divergence_rows,p),M=l.cycle_count>0&&n==="error"||(d.active_cycle_count>0||d.active_cardinality_violation_count>0||d.active_parent_divergence_count>0)&&r==="error";return{check:{name:"lifecycle",status:M?"error":f.length===0?"ok":"warn",ok:!M&&f.length===0,details:{checked_active_items:c.activeItems.length,lifecycle_status_roles:u,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:_.values,active_closure_like_metadata_rows_truncated:_.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:y.values,active_terminal_parent_rows_truncated:y.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:b.values,stale_blocker_rows_truncated:b.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:E.values,dependency_cycle_item_ids_truncated:E.truncated,dependency_cycle_sample_paths:v.values,dependency_cycle_sample_paths_truncated:v.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,active_parent_cycle_count:d.active_cycle_count,legacy_parent_cycle_count:d.legacy_cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:C.values,parent_cycle_item_ids_truncated:C.truncated,parent_cycle_sample_paths:k.values,parent_cycle_sample_paths_truncated:k.truncated,hierarchy_cardinality_violation_count:d.cardinality_violation_count,active_hierarchy_cardinality_violation_count:d.active_cardinality_violation_count,legacy_hierarchy_cardinality_violation_count:d.legacy_cardinality_violation_count,hierarchy_cardinality_violation_rows:S.values,hierarchy_cardinality_violation_rows_truncated:S.truncated,hierarchy_parent_divergence_count:d.parent_divergence_count,active_hierarchy_parent_divergence_count:d.active_parent_divergence_count,legacy_hierarchy_parent_divergence_count:d.legacy_parent_divergence_count,hierarchy_parent_divergence_rows:P.values,hierarchy_parent_divergence_rows_truncated:P.truncated,stale_blocker_reason_patterns:[...i.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:i.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...i.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:i.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...i.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:i.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...i.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:i.closure_like_metadata_field_pattern_sources.actual_result}},warnings:f,terminalParentFixRows:c.terminalParentFixRows}}async function hO(e,t,n,r,o,i){let s=await mO(e,t),a=new Map(e.map(O=>[O.id,O])),c=[...new Set(s.missingLinkedPaths)].sort((O,W)=>O.localeCompare(W)),l=await II(t,r),d=_O(l,n,t,r,o,i),u=d.candidateFiles.filter(O=>!s.linkedProjectPaths.has(O)),f=oO(u,e),p=_f(c,d.candidateFiles),_=new Map(p.map(O=>[O.path,O.classification])),y=p.filter(O=>O.classification==="moved").length,b=s.staleLinkRows.map(O=>({...O,classification:_.get(O.path)??"deleted"})).sort((O,W)=>O.item_id.localeCompare(W.item_id)||O.path.localeCompare(W.path)||O.link_kind.localeCompare(W.link_kind)),E=[];d.strictModeForcesPmInternals&&E.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&E.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&E.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((O,W)=>O.localeCompare(W)),C=It(v,i),k=It(c,i),S=It(u,i),P=It(f.map(O=>`${O.path}:${O.classification}:owner_candidate=${O.owner_candidate?.id??"unowned"}`),i),M=i?f:It(iO(f),!1).values,L=It(gf(p),i),V=b.map(O=>({item_id:O.item_id,path:O.path,link_kind:O.link_kind,classification:O.classification})),J=yf(V,O=>{let W=a.get(O);return W?{type:W.type,title:W.title,status:W.status}:void 0}),se=i?J:It(bf(J),!1).values;return{check:{name:"files",status:E.length===0?"ok":"warn",ok:E.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:i?"full":"summary",file_list_summary_limit:t_,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:o,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:C.total,remote_linked_paths:C.values,remote_linked_paths_truncated:C.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:k.total,missing_linked_paths:k.values,missing_linked_paths_truncated:k.truncated,missing_linked_paths_moved_count:y,missing_linked_paths_deleted_count:c.length-y,missing_linked_path_classifications:L.values,missing_linked_path_classifications_truncated:L.truncated,missing_linked_path_rows_count:J.length,missing_linked_path_rows:se,orphaned_paths_count:u.length,orphaned_paths_total:S.total,orphaned_paths:S.values,orphaned_paths_truncated:S.truncated,orphaned_path_classifications:P.values,orphaned_path_classifications_truncated:P.truncated,orphaned_path_rows_count:f.length,orphaned_path_rows:M}},warnings:E,staleLinkPruneRows:b}}function o_(e){let t=e.trim().replaceAll(/\s+/g," ");return t.length>120?`${t.slice(0,117)}...`:t}function yO(e,t,n){return`${e}:${t}:${o_(n)}`}function bO(e,t){let n=[];return e.forEach(({item:r,linkedTest:o},i)=>{let s=t[i];if(s.trusted)return;let a=o_(o.command??"");n.push(`${r.id}:${s.source_ref??"unknown"}->${s.current_source_ref??"unknown"}:${a}`)}),n}async function wO(e,t,n,r){let o=new Set(e.map(S=>S.id.toLowerCase())),i=0,s=0,a=new Set,c=[],l=e.flatMap(S=>(S.tests??[]).map(P=>({item:S,linkedTest:P}))),d=await zm(qm()),u=await Bm(r,l.map(({linkedTest:S})=>S),d),f=bO(l,u);for(let{item:S,linkedTest:P}of l){if(typeof P.command!="string"||P.command.trim().length===0)continue;i+=1;let M=$m(P.command,t);if(M.length!==0){s+=M.length;for(let L of M)a.add(L),o.has(L.toLowerCase())||c.push(yO(S.id,L,P.command))}}let p=[...new Set(c)].sort((S,P)=>S.localeCompare(P)),_=[...new Set(p.map(S=>S.split(":")[1]??""))].filter(S=>S.length>0).sort((S,P)=>S.localeCompare(P)),y=[];p.length>0&&y.push(`validate_command_references_stale_pm_ids:${p.length}`),f.length>0&&y.push(`validate_linked_test_trust_unacknowledged:${f.length}`);let b=n?Number.POSITIVE_INFINITY:at,E=X(p,b),v=X(_,b),C=X([...a].sort((S,P)=>S.localeCompare(P)),b),k=X(f,b);return{check:{name:"command_references",status:y.length===0?"ok":"warn",ok:y.length===0,details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:a.size,unique_referenced_pm_ids:C.values,unique_referenced_pm_ids_truncated:C.truncated,linked_test_trust_current_source_ref:d??null,untrusted_linked_tests_count:f.length,untrusted_linked_tests:k.values,untrusted_linked_tests_truncated:k.truncated,stale_pm_id_references_count:p.length,stale_pm_ids_count:_.length,stale_pm_ids:v.values,stale_pm_ids_truncated:v.truncated,stale_pm_id_reference_rows:E.values,stale_pm_id_reference_rows_truncated:E.truncated}},warnings:y}}function vO(e,t){let n=qc(e.map(c=>({ref:c.id,version:Uc(c)}))),r=[];n.outdated.length>0&&r.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&r.push(`validate_format_version_ahead_items:${n.ahead.length}`);let o=t?Number.POSITIVE_INFINITY:at,i=X(n.outdated,o),s=X(n.ahead,o),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:Ur,outdated_items_count:n.outdated.length,outdated_items:i.values,outdated_items_truncated:i.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var uc="pm validate auto-fix";async function EO(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:uc};if(e.kind==="set_resolution"?r.resolution=e.value:e.kind==="set_close_reason"?r.closeReason=e.value:e.kind==="set_estimate"?r.estimatedMinutes=e.value:e.kind==="reparent"?r.parent=e.parent_id:r.unset=["parent"],!n.runUpdate)throw new h("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.USAGE);await n.runUpdate(e.item_id,r,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function lc(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function kO(e,t,n){let r=[],o=[],i=new Map;for(let s of e.filter(a=>lc(a)===null))try{await EO(s,t,n),r.push(s)}catch(a){o.push({fix:s,error:a})}for(let s of e.filter(a=>lc(a)!==null)){let a=lc(s),c=i.get(a);c?c.push(s):i.set(a,[s])}for(let s of i.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Pm(a.item_id,{remove:c,message:uc},t):await Dm(a.item_id,{remove:c,message:uc},t),r.push(...s)}catch(l){o.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:o}}function TO(e,t){t>0&&e.push(`merge_receipt_evidence_invalid:${t}`)}async function SO(e,t,n,r){let o=await kf(e,new Set(t.map(b=>b.id)),n,{schema:r.schema,extensionFieldNames:nt(Y())}),i=[];o.unreadable_item_files.length>0&&i.push(`validate_storage_unreadable_items:${o.unreadable_item_files.length}`),o.duplicate_item_ids.length>0&&i.push(`validate_storage_duplicate_item_ids:${o.duplicate_item_ids.length}`),o.history_conflict_marker_streams.length>0&&i.push(`validate_storage_history_conflict_markers:${o.history_conflict_marker_streams.length}`),o.history_unparseable_streams.length>0&&i.push(`validate_storage_unparseable_history:${o.history_unparseable_streams.length}`),o.resurrected_items.length>0&&i.push(`validate_storage_resurrected_items:${o.resurrected_items.length}`),o.unparseable_config_files.length>0&&i.push(`validate_storage_unparseable_config:${o.unparseable_config_files.length}`);let s=i.length,a=await Sf(e);a.tracked_path_count>0&&i.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ra(e,No(r));c.status==="drift"&&i.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await kt(e),d=l===null?null:await oa(l);d!==null&&d.status!=="ok"&&i.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=await tt(l??e,{includeLossless:!0,pmRoot:e}),f=u.receipts,{pendingDecisions:p,lossless:_}=Nd(f);p.length>0&&i.push(`validate_merge_decisions_unreviewed:${p.length}`),TO(i,u.invalid_evidence_count);let y=s>0?"error":i.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:y,ok:y==="ok",details:{...o,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:p.length,pending_merge_decision_items:[...new Set(p.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),lossless_merge_receipt_count:_.length,invalid_merge_receipt_evidence_count:u.invalid_evidence_count,lossless_merge_receipt_items:[...new Set(_.map(b=>b.item_id))].sort((b,E)=>b.localeCompare(E)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:i}}function st(e,t,n){n&&DI(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function AO(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,r=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let o=HI(e.items,e.metadataPolicy,e.statusRegistry,r,[e.settings.id_prefix]);t.closeReasonBackfillRows=o.closeReasonBackfillRows,t.estimateBackfillRows=o.estimateBackfillRows,st(t,o,n)}if(e.requestedChecks.has("resolution")){let o=VI(e.items,e.statusRegistry,r);t.resolutionBackfillRows=o.resolutionBackfillRows,st(t,o,n)}if(e.requestedChecks.has("lifecycle")){let o=gO(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=o.terminalParentFixRows,st(t,o,n),st(t,YI(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let o=await hO(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=o.staleLinkPruneRows,st(t,o,n)}return e.requestedChecks.has("command_references")&&st(t,await wO(e.items,e.settings.id_prefix,r,e.pmRoot),n),e.requestedChecks.has("history_drift")&&st(t,await Hm(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&st(t,vO(e.items,r),n),e.requestedChecks.has("storage_integrity")&&st(t,await SO(e.pmRoot,e.items,ue(e.settings,Y()).type_to_folder,e.settings),n),t}function xO(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...rf(t.closeReasonBackfillRows)),r.push(...nf(t.resolutionBackfillRows)),r.push(...of(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...sf(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...af(t.staleLinkPruneRows)),r}async function CO(e,t,n,r,o,i){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=xO(e,t,n),{applicable:a,gated:c}=lf(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let f=await kO(a,o,i);d.push(...f.applied.map(lr)),u.push(...f.failed.map(({fix:p,error:_})=>({...lr(p),error:_ instanceof Error?_.message:String(_)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((f,p)=>f.localeCompare(p)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(lr),applied_fixes:d,gated_fixes:c.map(f=>({...lr(f),gate_hint:`Withheld: re-run with --fix-scope ${f.gate} to apply.`})),failed_fixes:u}}async function i_(e,t,n={}){Nl(e.counts===!0,e.full===!0,"--counts");let r=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!r)throw new h("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",g.USAGE);let o=cf(e.fixScope),i=re(process.cwd(),t.path);await Oe(i);let s=await te(i),a=On(s.schema),c=ue(s,Y()),l=PI(e),d=[],u=await Gm({includeBody:l.has("history_drift")||l.has("metadata"),pmRoot:i,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let V=await Cm(i);V.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${V.actionable_unknown_event_count}`)}let f=typeof e.metadataProfile=="string"?"option":"settings",p=hI(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),_=vI(p,f,s.validation.metadata_required_fields),y=gI(s),b=yI(e.dependencyCycleSeverity),E=bI(e.parentCycleSeverity),v=TI(e.scanMode),C=SI(i),k=await AO({requestedChecks:l,options:e,global:t,pmRoot:i,workspaceRoot:C,settings:s,items:u,statusRegistry:a,metadataPolicy:_,lifecyclePatternPolicy:y,dependencyCycleSeverity:b,parentCycleSeverity:E,fileScanMode:v,initialWarnings:[...new Set(d)]}),S=r?await CO(e,k,s,o,t,n):void 0,P=[...new Set(k.warnings)].sort((V,J)=>V.localeCompare(J)),L={ok:!k.checks.some(V=>V.status==="error"),has_warnings:P.length>0,checks:k.checks,warnings:P,...S!==void 0?{fixes:S}:{},generated_at:q(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?L:{..._I(L),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4d3c62e9-9116-5cdc-bbda-48bbd2e39476")}catch{}})();var s_=async(e,t,n)=>{if(!Number.isInteger(t)||t<1)throw new RangeError("concurrency must be a positive integer");let r=new Array(e.length),o=0,i=Array.from({length:Math.min(t,e.length)},async()=>{for(;o<e.length;){let s=o;o+=1,r[s]=await n(e[s])}});return await Promise.all(i),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]="8d85d220-dad2-5234-8819-65632275eb47")}catch{}})();var IO=4;async function OO(e){try{return{status:"fulfilled",value:await ga(e.id,{dryRun:e.dryRun,author:e.options.author??e.global.author,message:e.options.message??"record field-aware branch merge provenance",force:e.options.force,auditOperation:"merge_reconcile",auditContext:e.auditContext,forceAuditEntry:!0,mergeReceiptProof:e.mergeReceiptProof},e.global)}}catch(t){return{status:"rejected",reason:t}}}function RO(e){e.results.forEach((t,n)=>{let r=e.receiptOnlyIds[n];if(t.status==="fulfilled"){let o=t.value.changed?"repaired":"skipped_clean";e.repair.streams.push({id:r,outcome:o,entries_rehashed:t.value.history.entries_rehashed,entries_patch_repaired:t.value.history.entries_patch_repaired,reconciled_with_item:t.value.history.reconciled_with_item,...t.value.merge_receipt_proof?{merge_receipt_proof:t.value.merge_receipt_proof}:{},warnings:t.value.warnings}),e.repair.totals[o]+=1;return}e.repair.streams.push({id:r,outcome:"failed",error:t.reason instanceof Error?t.reason.message:String(t.reason)}),e.repair.totals.failed+=1})}async function NO(e){if(e.dryRun||e.repair.totals.failed>0)return 0;let t=new Set(e.repair.streams.flatMap(r=>r.merge_receipt_proof?.trusted?r.merge_receipt_proof.receipt_ids:[])),n=e.force?e.pendingReceipts:e.pendingReceipts.filter(r=>t.has(r.id));return await Promise.all(n.map(r=>Fs(e.gitWorkspaceRoot??process.cwd(),r,{requireExisting:!0}))),n.length}async function DO(e,t){let n=e.dryRun===!0,r=re(process.cwd(),t.path),o=await kt(r),i=await tt(o??process.cwd(),{includeLossless:!0,pmRoot:r});if(i.invalid_evidence_count>0)throw new h(`Merge reconciliation refused ${i.invalid_evidence_count} invalid receipt evidence file(s).`,g.CONFLICT,{code:"merge_receipt_evidence_invalid",required:"Every clone-local and durable receipt candidate must pass bounded-file, schema, and identity validation.",recovery:{suggested_retry:"pm health --check-only --full"}});let s=i.receipts,a=new Map;for(let k of s){let S=a.get(k.item_id)??[];S.push(k),a.set(k.item_id,S)}let c=Object.fromEntries([...a].map(([k,S])=>[k,{merge:{receipts:S.map(We)}}])),l=Object.fromEntries([...a].map(([k,S])=>[k,{gitWorkspaceRoot:o,receipts:S}])),d=await Qu({dryRun:n,author:e.author??t.author,message:e.message??"post-merge reconciliation of field-aware tracker history",force:e.force,auditOperation:"merge_reconcile",auditContextById:c,...s.length>0?{mergeReceiptProofById:l}:{}},t),u=new Set(d.streams.map(k=>k.id)),f=[...a.keys()].filter(k=>!u.has(k)),p=await s_(f,IO,k=>OO({id:k,dryRun:n,options:e,global:t,auditContext:c[k],mergeReceiptProof:l[k]}));RO({receiptOnlyIds:f,results:p,repair:d});let _=await NO({dryRun:n,force:e.force===!0,pendingReceipts:s,repair:d,gitWorkspaceRoot:o}),y=await i_({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),b=y.checks.every(k=>k.status==="ok"),E=n?s.length===0:_===s.length,v=d.totals.failed===0&&b&&E,C=n?["Review repair.streams, then rerun pm merge reconcile without --dry-run to apply audited repairs.","No Git hook is installed automatically; invoke this command from an explicit post-merge hook only when your repository policy opts in."]:v?["Reconciliation is complete; commit changed history streams with the merge result.","Rerun pm merge reconcile --dry-run after future tracker-data merges as a non-mutating integrity check."]:["Reconciliation remains incomplete; inspect repair failures and non-green validation checks before retrying.","Do not commit repaired history streams as reconciled until pm merge reconcile returns ok=true."];return{ok:v,dry_run:n,repair:d,receipts:{pending_before:s.length,reconciled:_,summaries:s.map(We)},validation:y,guidance:C,generated_at:y.generated_at}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a26f1126-3c87-5b0d-8712-2846fc9dcbb3")}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]="00dc29ff-60e0-5755-b7f1-4f69e438e87f")}catch{}})();export{hd as ITEM_LATEST_TIMESTAMP_FIELDS,gd as ITEM_UNION_COLLECTION_FIELDS,Ys as MERGE_DRIVER_ARTIFACT_VALUES,ta as PM_GITATTRIBUTES_END,Qn as PM_GITATTRIBUTES_START,Io as PM_GITATTRIBUTES_V2_END,Wt as PM_GITATTRIBUTES_V2_START,ra as auditMergeAttributeFence,oa as auditMergeDriverConfiguration,Ro as buildMergeAttributePatterns,kt as findGitWorkspaceRoot,tt as inspectMergeReceiptEvidence,Tk as installMergeFence,Rd as listMergeReceipts,Fs as markMergeReceiptReconciled,Cs as mergeHistoryStreams,Os as mergeItemDocuments,Rs as mergeJsonDocuments,Is as mergeRelationshipEventStreams,Ek as refreshMergeAttributeFenceIfInstalled,uu as resolveMergeInstallContext,No as resolveProjectMergeTypeFolders,fk as runMergeDriver,kk as runMergeInstall,xv as runMergeReceiptEvidenceReport,Av as runMergeReceiptReport,DO as runMergeReconcile,We as summarizeMergeReceipt};
113
113
  //# sourceMappingURL=sdk-merge.js.map