@unbrained/pm-cli 2026.8.8 → 2026.8.9

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 (144) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +19 -0
  3. package/dist/cli-bundle/bundle-manifest.json +154 -154
  4. package/dist/cli-bundle/chunks/chunk-2DTCZXSD.js +13 -0
  5. package/dist/cli-bundle/chunks/{chunk-ALDHXLPS.js → chunk-5JO6R4BS.js} +2 -2
  6. package/dist/cli-bundle/chunks/chunk-5KN4DZYV.js +194 -0
  7. package/dist/cli-bundle/chunks/chunk-EF43KODO.js +2 -0
  8. package/dist/cli-bundle/chunks/{chunk-NUXRRNAB.js → chunk-GMX5YOI3.js} +25 -25
  9. package/dist/cli-bundle/chunks/chunk-HUV2Z7IS.js +28 -0
  10. package/dist/cli-bundle/chunks/{chunk-SQ7QZFQ6.js → chunk-MHBVCUF2.js} +2 -2
  11. package/dist/cli-bundle/chunks/chunk-PYO5GZU6.js +5 -0
  12. package/dist/cli-bundle/chunks/{chunk-CBLA33YK.js → chunk-RJC7TPF4.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-2ZMXX3Q6.js → chunk-YC3UF2IO.js} +64 -64
  14. package/dist/cli-bundle/chunks/{register-list-query-WFZAMJHZ.js → register-list-query-BUE7PTCU.js} +2 -2
  15. package/dist/cli-bundle/chunks/{register-mutation-SOKKOTHQ.js → register-mutation-FC3XLVIK.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-operations-5XQETS6E.js → register-operations-YH2WAOXU.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-setup-2HL5ZHMK.js → register-setup-UQDTNTLJ.js} +2 -2
  18. package/dist/cli-bundle/focused-chunks/chunk-2VVP5RAA.js +153 -0
  19. package/dist/cli-bundle/focused-chunks/{chunk-IAS7PMLG.js → chunk-3GSFUDAI.js} +2 -2
  20. package/dist/cli-bundle/focused-chunks/chunk-3WVHTUAW.js +5 -0
  21. package/dist/cli-bundle/focused-chunks/chunk-4H6MVCK3.js +16 -0
  22. package/dist/cli-bundle/focused-chunks/{chunk-ZOLDTUU7.js → chunk-54TZJ4BM.js} +2 -2
  23. package/dist/cli-bundle/focused-chunks/{chunk-YKPE4PPY.js → chunk-5NK5TJ5D.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-ANTMGYLI.js → chunk-6DO4YQWZ.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/chunk-73FIJONU.js +2 -0
  26. package/dist/cli-bundle/focused-chunks/{chunk-PL2EYDJK.js → chunk-C3GCHDSQ.js} +29 -27
  27. package/dist/cli-bundle/focused-chunks/{chunk-U646T7Z6.js → chunk-JGRSQZJT.js} +3 -3
  28. package/dist/cli-bundle/focused-chunks/{chunk-YSAHYUXX.js → chunk-KNEHLPBF.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/chunk-MRWVJ3ZG.js +2 -0
  30. package/dist/cli-bundle/focused-chunks/chunk-NL57J7BZ.js +4 -0
  31. package/dist/cli-bundle/focused-chunks/{chunk-DMKOMTTY.js → chunk-P6BBIQRG.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-GWI6YIKJ.js → chunk-PZAGVQNN.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-QDAO3XEK.js +14 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-SM2PJGP3.js → chunk-T4IGQCSY.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-U46GQJNY.js +2 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-TCSAPH33.js → chunk-VRXJSGIT.js} +6 -6
  37. package/dist/cli-bundle/focused-chunks/{chunk-FI6DWU2M.js → chunk-XC2ZW3CJ.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-ZG54B4XG.js +2 -0
  39. package/dist/cli-bundle/main.js +2 -2
  40. package/dist/cli-bundle/sdk-authoring.js +1 -1
  41. package/dist/cli-bundle/sdk-contracts.js +1 -1
  42. package/dist/cli-bundle/sdk-core.js +29 -29
  43. package/dist/cli-bundle/sdk-governance.js +1 -1
  44. package/dist/cli-bundle/sdk-graph.js +1 -1
  45. package/dist/cli-bundle/sdk-merge.js +1 -1
  46. package/dist/cli-bundle/sdk-query.js +1 -1
  47. package/dist/cli-bundle/sdk-runtime.js +1 -1
  48. package/dist/cli-bundle/sdk-testing.js +1 -1
  49. package/dist/cli-bundle/sdk.js +2 -2
  50. package/dist/core/diagnostics/remediation.js +12 -2
  51. package/dist/core/history/history.js +13 -4
  52. package/dist/core/item/actionability.d.ts +7 -1
  53. package/dist/core/item/actionability.js +71 -15
  54. package/dist/core/shared/author.d.ts +25 -0
  55. package/dist/core/shared/author.js +114 -9
  56. package/dist/sdk/actionability.d.ts +1 -1
  57. package/dist/sdk/actionability.js +3 -3
  58. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +8 -0
  59. package/dist/sdk/cli-contracts/runtime-contracts.js +17 -2
  60. package/dist/sdk/core-governance.d.ts +1 -1
  61. package/dist/sdk/core-governance.js +3 -3
  62. package/dist/sdk/dependencies.d.ts +2 -0
  63. package/dist/sdk/dependencies.js +7 -6
  64. package/dist/sdk/extension/bundled-catalog.js +19 -6
  65. package/dist/sdk/generated-error-code-catalog.js +38 -2
  66. package/dist/sdk/governance/health.js +29 -10
  67. package/dist/sdk/governance/provenance-health.d.ts +26 -0
  68. package/dist/sdk/governance/provenance-health.js +139 -0
  69. package/dist/sdk/governance/validate.js +13 -8
  70. package/dist/sdk/governance.d.ts +1 -0
  71. package/dist/sdk/governance.js +3 -2
  72. package/dist/sdk/graph/assembly.d.ts +4 -0
  73. package/dist/sdk/graph/assembly.js +22 -2
  74. package/dist/sdk/graph/run.d.ts +2 -0
  75. package/dist/sdk/graph/run.js +3 -2
  76. package/dist/sdk/lifecycle/close.js +13 -8
  77. package/dist/sdk/lifecycle/create.js +6 -12
  78. package/dist/sdk/lifecycle/plan.js +6 -3
  79. package/dist/sdk/lifecycle/update.js +6 -20
  80. package/dist/sdk/merge/driver.d.ts +2 -1
  81. package/dist/sdk/merge/driver.js +7 -4
  82. package/dist/sdk/merge/install.js +3 -3
  83. package/dist/sdk/merge/receipts.d.ts +14 -1
  84. package/dist/sdk/merge/receipts.js +36 -8
  85. package/dist/sdk/merge/reconcile.js +21 -4
  86. package/dist/sdk/merge/three-way.d.ts +6 -2
  87. package/dist/sdk/merge/three-way.js +24 -10
  88. package/dist/sdk/query/get.d.ts +11 -0
  89. package/dist/sdk/query/get.js +37 -3
  90. package/dist/sdk/read-output-contracts.d.ts +1 -1
  91. package/dist/sdk/read-output-contracts.js +23 -4
  92. package/dist/sdk/relationship-kinds/contract.d.ts +48 -0
  93. package/dist/sdk/relationship-kinds/contract.js +22 -0
  94. package/dist/sdk/relationships.d.ts +6 -41
  95. package/dist/sdk/relationships.js +12 -126
  96. package/dist/sdk/runtime-primitives.d.ts +1 -1
  97. package/dist/sdk/runtime-primitives.js +3 -3
  98. package/dist/sdk/similarity.d.ts +5 -0
  99. package/dist/sdk/similarity.js +40 -10
  100. package/dist/sdk/structured-mutations.js +5 -2
  101. package/dist/sdk/test/linked-command-detection.d.ts +2 -7
  102. package/dist/sdk/test/linked-command-detection.js +22 -9
  103. package/docs/AGENT_GUIDE.md +2 -1
  104. package/docs/COMMANDS.md +19 -1
  105. package/docs/DEPENDENCY_KIND_CONTRACT.md +29 -0
  106. package/docs/ITEM_READ_PROJECTIONS.md +26 -0
  107. package/docs/MERGE_SAFETY.md +10 -3
  108. package/docs/RELATIONSHIP_GRAPH.md +1 -1
  109. package/docs/SDK_AGENT_SESSION_CONTEXT.md +35 -2
  110. package/docs/SDK_CONTEXT_INTEGRITY.md +16 -1
  111. package/docs/SENTRY_CONTRACT_EPOCHS.md +20 -0
  112. package/docs/agent-task-token-baseline.json +2 -2
  113. package/marketplace.json +2 -2
  114. package/package.json +1 -1
  115. package/packages/pm-beads/package.json +1 -1
  116. package/packages/pm-calendar/package.json +1 -1
  117. package/packages/pm-command-kit/package.json +1 -1
  118. package/packages/pm-digital-twin/package.json +1 -1
  119. package/packages/pm-governance-audit/package.json +1 -1
  120. package/packages/pm-guide-shell/package.json +1 -1
  121. package/packages/pm-kanban/package.json +1 -1
  122. package/packages/pm-lifecycle-hooks/package.json +1 -1
  123. package/packages/pm-linked-test-adapters/package.json +1 -1
  124. package/packages/pm-search-advanced/package.json +1 -1
  125. package/packages/pm-templates/package.json +1 -1
  126. package/packages/pm-todos/package.json +1 -1
  127. package/packages/pm-vcs/package.json +1 -1
  128. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  129. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  130. package/sdk/public-surface.json +231 -27
  131. package/dist/cli-bundle/chunks/chunk-GKA54IJM.js +0 -5
  132. package/dist/cli-bundle/chunks/chunk-KRY7SRUO.js +0 -2
  133. package/dist/cli-bundle/chunks/chunk-MNJ4NNSY.js +0 -26
  134. package/dist/cli-bundle/chunks/chunk-OJPCFDDY.js +0 -13
  135. package/dist/cli-bundle/chunks/chunk-PFSD3DAN.js +0 -194
  136. package/dist/cli-bundle/focused-chunks/chunk-54EU2UVO.js +0 -2
  137. package/dist/cli-bundle/focused-chunks/chunk-5FLBTZJQ.js +0 -2
  138. package/dist/cli-bundle/focused-chunks/chunk-5GJ57YKN.js +0 -2
  139. package/dist/cli-bundle/focused-chunks/chunk-CMDS3KYT.js +0 -14
  140. package/dist/cli-bundle/focused-chunks/chunk-F5B3HBEZ.js +0 -5
  141. package/dist/cli-bundle/focused-chunks/chunk-FNOKJG6N.js +0 -16
  142. package/dist/cli-bundle/focused-chunks/chunk-FPDYXZBK.js +0 -4
  143. package/dist/cli-bundle/focused-chunks/chunk-HCUC62AB.js +0 -2
  144. package/dist/cli-bundle/focused-chunks/chunk-HGNKPSCB.js +0 -153
@@ -1,2 +0,0 @@
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]="50ad61f1-6719-541c-b4e0-4a88468725cf")}catch{}})();var N=["commands","renderers","hooks","schema","importers","search","parser","preflight","services"],fe=2,pe=Object.freeze({migration:"schema",validation:"schema"}),yt=Object.freeze({version:fe,capabilities:[...N],legacy_aliases:{...pe}}),P=["off","warn","enforce"],j=["off","warn","enforce"],V=["none","restricted","strict"],ht=["block","warn"],F=["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"],K=["output_format","error_format","help_format","lock_acquire","lock_release","history_append","item_store_write","item_store_delete","context_relevance","command_result"];function B(){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]="2a2072c1-f4a7-579e-ac11-4c75758d76d3")}catch{}})();var me=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],St=me,At=["draft","open","in_progress","blocked","closed","canceled"],Tt=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],Nt=["string","number","boolean","string_array","array","object"],It=["create","update","update_many","list","search","calendar","context"],kt=["allow","warn","reject"],wt=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","supersedes","task","verifies"],Rt=["project","global"],xt=["low","medium","high","critical"],vt=["low","medium","high","critical"],Ct=["low","medium","high"];var Dt=["minimal","default","strict","custom"],Lt=["none","warn","strict"],Mt=["progressive","strict"],Ut=["off","warn","strict"],Pt=["off","warn","strict"];var jt=["daily","weekly","monthly","yearly"],ge=["mon","tue","wed","thu","fri","sat","sun"];function Vt(e){return ge.indexOf(e)}var Ft=["draft","research","review","approved","executing","paused","completed","superseded"],Kt=["pending","in_progress","completed","blocked","skipped","superseded"],Bt=["codex","claude-code","cursor","generic"],Gt=["related","blocks","blocked_by","depends_on","discovered_from","implements","verifies","supersedes"],Xt=["brief","standard","deep","full"],Yt=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="36b908f0-ea19-5adc-8ccd-320ad3c3b1fe")}catch{}})();var Ee=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"]}]),be=Object.freeze({draft_status:"draft",open_status:"open",in_progress_status:"in_progress",blocked_status:"blocked",close_status:"closed",canceled_status:"canceled"}),Wt=".agents/pm",$t="settings.json";var ye=["","epics","features","tasks","chores","issues","schema","history","search","extensions","locks"],he=["decisions","events","reminders","milestones","meetings","plans"],Ht=[...ye,...he],Jt={Epic:"epics",Feature:"features",Task:"tasks",Chore:"chores",Issue:"issues",Decision:"decisions",Event:"events",Reminder:"reminders",Milestone:"milestones",Meeting:"meetings",Plan:"plans"},Oe=["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"],Zt=["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",...Oe,"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={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}},Ae=["no active blocker","ready for planned execution sequencing","work completed","work is closed"],I={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 G(e){return e?[...e]:void 0}var Qt={version:1,id_prefix:"pm-",ids:{token_length:4},author_default:"",agent_identity:{probes_enabled:!0,identity_vocabulary:{version:1,aliases:{}},harness_signals:[]},mutation_guard:{require_attributed_author:!1,secret_guard:"advise",stale_in_progress_hours:72},item_format:"toon",locks:{ttl_seconds:1800,wait_ms:3e3},checkpoints:{retention_days:14},output:{default_format:"toon"},history:{missing_stream:"auto_create",compact_policy:{enabled:!1,max_entries:500,trigger:"health_warn"}},validation:{sprint_release_format:"warn",parent_reference:"warn",metadata_profile:"core",metadata_required_fields:[],lifecycle_stale_blocker_reason_patterns:[...Ae],lifecycle_closure_like_blocked_reason_patterns:[...I.blocked_reason],lifecycle_closure_like_resolution_patterns:[...I.resolution],lifecycle_closure_like_actual_result_patterns:[...I.actual_result],estimate_defaults_by_type:{}},governance:{preset:"minimal",...Se.minimal},workflow:{definition_of_done:[]},testing:{record_results_to_items:!1},telemetry:{enabled:!0,first_run_prompt_completed:!1,capture_level:"redacted",endpoint:"https://pm-cli.unbrained.dev/v1/events",installation_id:"",retention_days:365},agent_guidance:{prompt_completed:!1,declined:!1,declined_at:"",template_version:1,last_checked_files:[]},item_types:{definitions:[]},schema:{version:1,files:{types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"},statuses:Ee.map(e=>({...e,aliases:G(e.aliases),roles:G(e.roles)})),fields:[],workflow:{...be},unknown_field_policy:"allow"},extensions:{enabled:[],disabled:[],policy:B()},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:""}}},en={metadata:{},body:""},f={SUCCESS:0,GENERIC_FAILURE:1,USAGE:2,NOT_FOUND:3,CONFLICT:4,DEPENDENCY_FAILED:5,NO_EFFECT:6,PARTIAL_EFFECT:7},tn=Object.freeze({unknown_command:"usage",unknown_option:"usage",missing_required_option:"usage",missing_required_argument:"usage",invalid_command_usage:"usage",linked_test_value_not_quoted:"usage",invalid_argument_value:"validation",health_findings:"validation",validation_findings:"validation",close_through_update:"validation",no_update_fields:"validation",unsupported_update_option:"validation",tracker_not_initialized:"validation",item_not_found:"validation",ownership_conflict:"conflict",lock_conflict:"conflict",terminal_state_conflict:"conflict",dependency_failed:"runtime",init_gitignore_unwritable:"runtime",merge_git_config_unwritable:"runtime",command_failed:"runtime",unknown_error:"runtime"});(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c2c9251e-86bf-5a92-acdb-581e59d269d8")}catch{}})();var _=class extends Error{exitCode;code;context;constructor(t,n,o={}){super(t),this.name="PmCliError",this.exitCode=n,this.context=o,this.code=o.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]="15daa637-4d30-5794-bdb5-87585d443cd3")}catch{}})();var Te=[...N],Ne=[...K],Ie=[...P],rn=[...j],an=[...V],ke=[...F],X=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],cn=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],we=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Y={help:"Commander help rendering has no SDK operation result.",item:"The item namespace only groups lifecycle subcommands already exposed as actions.",packages:"The plural package alias only renders package-oriented help."},z=Object.freeze(X.flatMap(e=>e in Y?[]:e==="extension"||e==="package"?[...we.map(t=>`${e}-${t}`),e]:[e]));function dn(e=X,t=z,n=Y){let o=new Set(t),s=new Set(e);return{missing_cli_actions:e.filter(r=>!o.has(r)&&n[r]===void 0),waived_cli_actions:e.filter(r=>!o.has(r)&&n[r]!==void 0),stale_waivers:Object.keys(n).filter(r=>!s.has(r)||o.has(r))}}function un(e){return z.includes(e)}function ln(e){return Te.includes(e)}function _n(e){return Ne.includes(e)}function fn(e){return Ie.includes(e)}function pn(e){return ke.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]="ae6fbd4a-6c4e-5639-93ac-f107a336e95b")}catch{}})();function k(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Re(e,t){let n=e;for(let o of t.split(".")){if(!k(n))return;n=n[o]}return n}function q(e,t,n){let o=t.split("."),s={...e},r=e,i=s;for(let a of o.slice(0,-1)){let c=r[a],u={...c};i[a]=u,r=c,i=u}return i[o.at(-1)]=n,s}function w(e){let t=e.row_contract;return k(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function p(e){return w(e).flatMap(t=>{let n=Re(e,t);return Array.isArray(n)||k(n)?[{path:t,value:n}]:[]})}function h(e){return p(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function O(e,t){let n=e;for(let o of p(n)){let s=Array.isArray(o.value)?o.value.map((r,i)=>t(r,o.path,i)):Object.fromEntries(Object.entries(o.value).map(([r,i],a)=>[r,t(i,o.path,a)]));n=q(n,o.path,s)}return n}function W(e,t){let n=e,o=!1;for(let s of p(n)){let r=Array.isArray(s.value)?s.value:Object.entries(s.value);if(r.length<=t)continue;o=!0;let i=Array.isArray(s.value)?r.slice(0,t):Object.fromEntries(r.slice(0,t));n=q(n,s.path,i)}return{result:n,truncated: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]="04ad0d11-1fb7-5eb4-8ff0-d81a7090c4ff")}catch{}})();var R=256,$=1e4,xe=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,ve=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,Ce=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),De=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&xe.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=R,reason:`token_budget must be a safe integer of at least ${R}.`},{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<=$&&e.seen_item_ids.every(t=>typeof t=="string"&&ve.test(t)),reason:`seen_item_ids must contain at most ${$} portable item identifiers.`}];function A(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function S(e){throw new _(`--output-session ${e}`,f.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function x(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{S("must be a valid JSON object.")}A(t)||S("must be a JSON object.");let n=Object.keys(t).filter(r=>!Ce.has(r));n.length>0&&S(`contains unknown field "${n.sort()[0]}".`);let o=De.find(r=>!r.valid(t));o!==void 0&&S(o.reason);let s=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:s}}function H(e){if(A(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:A(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function Le(e){let t=new Set,n=0;for(let o of p(e)){let s=Array.isArray(o.value)?o.value:Object.values(o.value);for(let r of s){if(!A(r))continue;if(typeof r.context_ref=="string"){n+=1;continue}let i=H(r);i!==void 0&&t.add(i)}}return{deliveredIds:t,suppressedRepeatCount:n}}function J(e,t){let n=new Set(t.seen_item_ids);return O(e,o=>{let s=H(o);return s!==void 0&&n.has(s)?{id:s,context_ref:`session:${t.id}:${s}`}:o})}function v(e,t){let{deliveredIds:n,suppressedRepeatCount:o}=Le(e),s=[...new Set([...t.seen_item_ids,...n])].sort(),r={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:n.size,suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:s}},i={...e,read_session:r},a=l=>{r.spent_this_call_tokens=l,r.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,l),r.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+r.charged_this_call_tokens),r.remaining_tokens=Math.max(0,t.token_budget-r.spent_total_tokens),r.exhausted=r.remaining_tokens<R,r.next_state.spent_tokens=r.spent_total_tokens},c=0,u=0;for(let l=0;l<8;l+=1){a(c);let d=Math.ceil(Buffer.byteLength(JSON.stringify(i),"utf8")/4);if(d===c)return i;u=Math.max(u,d),c=d}return a(u),i}function Z(e){return Math.max(0,e.token_budget-e.spent_tokens)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1726fdce-dc71-5707-ae75-b588691e813d")}catch{}})();var Me=8,Ue=64;function Pe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function C(e,t){return typeof e=="string"?e.length<=240?e:(t.compacted=!0,`${e.slice(0,240)}\u2026`):Array.isArray(e)?e.map(n=>C(n,t)):Pe(e)?Object.fromEntries(Object.entries(e).map(([n,o])=>[n,C(o,t)])):e}function m(e,t){let n=t.estimated_tokens;for(let o=0;o<Me;o+=1){t.estimated_tokens=n;let s=Math.ceil(Buffer.byteLength(JSON.stringify(e),"utf8")/4);if(s===n)return;n=s}t.estimated_tokens=n}function je(e,t,n){for(let o=0;o<Ue;o+=1){if(m(e,t),t.estimated_tokens<=n)return;let s=p(e).filter(r=>(Array.isArray(r.value)?r.value.length:Object.keys(r.value).length)>1).map(r=>({collection:r,length:Array.isArray(r.value)?r.value.length:Object.keys(r.value).length})).sort((r,i)=>i.length-r.length||r.collection.path.localeCompare(i.collection.path))[0]?.collection;if(!s)return;if(Array.isArray(s.value))s.value.splice(-Math.max(1,Math.ceil(s.value.length/2)));else{let r=Object.keys(s.value);for(let i of r.slice(-Math.max(1,Math.ceil(r.length/2))))delete s.value[i]}t.rows_compacted=!0,e.has_more=!0,e.truncated=!0,typeof e.count=="number"&&(e.count=h(e))}}function Q(e,t,n){let o={compacted:!1},s=C(e,o);return t.strings_compacted=o.compacted,s.read_output=t,je(s,t,n),m(s,t),s}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="27f3a09b-9b90-5c85-9e41-21cfed5dc0ce")}catch{}})();var g=["include","amount","cost","encoding"],se=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","files","docs","stats","aggregate"],re=["canonical","legacy","intent","default"],M={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},wn=Object.freeze(g.map(e=>M[e])),Rn=Object.freeze(["--output-session"]),Ve={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],cost:["--token-budget"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary","--verbose"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded"],encoding:["--stream"]},validate:{include:["--counts","--full","--verbose"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{}},Fe=new Set(["--fields","--section"]),Ke=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding."});function ie(e){return e.slice(2).replaceAll("-","_")}function Be(e,t){let n=Ke[e];if(n!==void 0)return n;let o=t==="include"?Fe.has(e)?"<csv>":ie(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${M[t]} ${o}.`}function Ge(e){let t=Ve[e],n=Object.freeze(Object.fromEntries(g.map(o=>[o,Object.freeze({dimension:o,canonical_option:M[o],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[o]??[]).map(s=>Object.freeze({flag:s,migration_hint:Be(s,o),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:re})}var Xe=Object.freeze(se.map(Ge)),Ye=new Map(Xe.map(e=>[e.command,e]));function ae(e){let t=e.trim().toLowerCase().split(/\s+/u)[0],n=t.startsWith("list-")?"list":t==="ctx"?"context":t;return se.includes(n)?n:void 0}var ze=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session"],qe={comments:["add","body","stdin","file","edit","delete"],notes:["add","addJson","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"]};function We(e){return ze.some(t=>e[t]!==void 0)}var $e=[{keys:["outputInclude","output_include"],valid:e=>D(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||E(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>E(e)!==void 0,message:"--output-budget must be a positive integer."},{keys:["outputFormat","output_format"],valid:e=>e==="toon"||e==="json",message:"--output-format must be toon or json."},{keys:["outputSession","output_session"],valid:e=>(x(e),!0),message:"--output-session must be a valid session-state object."}];function xn(e,t){if(!We(t))return;let n=ae(e);if(!n)throw new _(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,f.USAGE);if((qe[n]??[]).some(o=>t[o]!==void 0&&t[o]!==!1))throw new _(`Universal output controls cannot be combined with a ${n} mutation.`,f.USAGE);for(let o of $e){let s=o.keys.map(r=>t[r]).find(r=>r!==void 0);if(s!==void 0&&!o.valid(s))throw new _(o.message,f.USAGE)}}function He(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}function Je(e,t){let n=He(t);if(Object.hasOwn(e,n))return e[n];let o=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,o))return e[o];if(t==="--no-truncate"&&e.truncate===!1)return!0}function Ze(e){return e!==void 0&&e!==!1&&e!==null}function D(e){let n=(Array.isArray(e)?e:[e]).flatMap(o=>typeof o=="string"?o.split(","):[]).map(o=>o.trim()).filter(Boolean);return n.length>0?[...new Set(n)]:void 0}function E(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function Qe(e,t,n){for(let o of e.legacy_aliases){let s=Je(t,o.flag),r={value:s,flag:o.flag};if(Ze(s)&&n(r))return r}}function ee(e,t){let n=D(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:D(t.value)??[ie(t.flag)]}}function te(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=E(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let o=E(t.value);return o===void 0?void 0:{source:"legacy",value:o}}function ne(e,t){let n=E(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let o=E(t.value);return o===void 0?void 0:{source:"legacy",value:o}}function oe(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function ce(e,t){let n=ae(e);if(!n)return;let o=Ye.get(n),s={include:c=>ee(void 0,c),amount:c=>te(void 0,c),cost:c=>ne(void 0,c),encoding:c=>oe(void 0,c)},r=Object.fromEntries(g.map(c=>[c,Qe(o.dimensions[c],t,u=>s[c](u)!==void 0)])),i=g.flatMap(c=>{let u=r[c];return u?[u.flag]:[]}),a=g.flatMap(c=>{let u=r[c];return u?[o.dimensions[c].legacy_aliases.find(d=>d.flag===u.flag).migration_hint]:[]});return{command:n,include:ee(t.outputInclude??t.output_include,r.include),amount:te(t.outputLimit??t.output_limit,r.amount),cost:ne(t.outputBudget??t.output_budget,r.cost),encoding:oe(t.outputFormat??t.output_format,r.encoding),legacy_aliases_used:i,migration_hints:a,precedence:re}}function b(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var U=new Set(["applied_bound","applied_limit","completeness","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","row_contract","sorting","total","truncated"]);function de(e,t){let n=new Set(t.map(o=>o.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([o])=>n.has(o)))}function et(e){let t=b(e.item)?e.item:{},n=Object.keys(t).sort((s,r)=>s.localeCompare(r)),o=Object.keys(e).filter(s=>s!=="item"&&s!=="read_output"&&!U.has(s)).sort((s,r)=>s.localeCompare(r));return{item:t,itemFields:n,sections:o,valid:[...n,"item",...n.map(s=>`item.${s}`),...o]}}function tt(e,t){let n=et(e),o=t.filter(d=>!n.valid.includes(d));if(o.length>0)throw new _(`Unknown --output-include selector(s) for get: ${o.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,f.USAGE);let s=t.includes("item"),r=t.flatMap(d=>d.startsWith("item.")?[d.slice(5)]:n.itemFields.includes(d)?[d]:[]).filter((d,le,_e)=>_e.indexOf(d)===le);if(s&&r.length>0)throw new _("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",f.USAGE);let i=new Set(t.filter(d=>n.sections.includes(d))),a=Object.fromEntries(Object.entries(e).filter(([d])=>U.has(d)||i.has(d)));s?a.item=n.item:r.length>0&&(a.item=de(n.item,r));let c=[...s?[]:r.length>0?n.itemFields.filter(d=>!r.includes(d)).map(d=>({name:`item.${d}`,restore_with:`--output-include item.${d}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(d=>!i.has(d)).map(d=>({name:d,restore_with:`--output-include ${d}`}))],l=[...b(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:l.length>0,omitted_field_group_count:l.length,omitted_field_groups:l},a}function nt(e,t,n){if(e==="get")return tt(t,n);let o=w(t),s=n.flatMap(i=>o.flatMap(a=>i.startsWith(`${a}.`)?[i.slice(a.length+1)]:[])),r=n.some(i=>Object.hasOwn(t,i.split(".")[0])&&!o.some(a=>i.startsWith(`${a}.`)));if(o.length>0&&(!r||s.length>0)){let i={...t};return O(i,a=>b(a)?de(a,s.length>0?s:n):a)}return Object.fromEntries(Object.entries(t).filter(([i])=>n.some(a=>a.split(".")[0]===i)||U.has(i)))}function ot(e,t){if(t==="unbounded")return e;let{result:n,truncated:o}=W(e,t);return o&&(n.has_more=!0,n.truncated=!0,typeof n.count=="number"&&(n.count=h(n)),n.applied_bound={kind:"output_limit",source:"explicit",value:t}),n}function st(e){return g.filter(t=>e[t]!==void 0)}function L(e,t,n){let o=v(e,t);for(let s=0;s<8;s+=1){let r=n.estimated_tokens,i=o.read_session.spent_this_call_tokens;m(o,n),o=v(o,t);let a=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===r&&a===i)return o}return o}function rt(e,t,n){let o={...e};return t.include?.source==="canonical"&&(o=nt(t.command,o,t.include.value)),t.amount?.source==="canonical"&&(o=ot(o,t.amount.value)),n===void 0?o:J(o,n)}function it(e,t){let n=[...e.cost?.source==="canonical"?[e.cost.value]:[],...t===void 0?[]:[Z(t)]];return n.length===0?void 0:Math.min(...n)}function at(e,t,n,o){let s={contract_version:1,command:e.command,requested_dimensions:t,precedence:e.precedence,legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0},r={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Increase --output-budget or narrow the read."},read_output:s},i=n===void 0?r:L(r,n,s);if(n===void 0&&m(i,s),n!==void 0&&s.estimated_tokens>o)throw new _("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",f.USAGE);return i}function vn(e,t,n){let o=ce(e,t);if(!o)return n;let s=x(t.outputSession??t.output_session),r=st(o);if(r.filter(l=>o[l]?.source==="canonical").length===0&&s===void 0)return n;let a=rt(n,o,s),c={contract_version:1,command:o.command,requested_dimensions:r,precedence:o.precedence,legacy_aliases_used:o.legacy_aliases_used,migration_hints:o.migration_hints,estimated_tokens:0,within_budget:!0,strings_compacted:!1,rows_compacted:!1,result_omitted:!1};a.read_output=c,a=s===void 0?a:L(a,s,c),m(a,c);let u=it(o,s);return u!==void 0&&c.estimated_tokens>u&&(a=Q(a,c,u),s!==void 0&&(a=L(a,s,c))),u!==void 0&&c.estimated_tokens>u?at(o,r,s,u):a}function Cn(e){return b(e)&&b(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function Dn(e,t){let n=ce(e,t)?.encoding;return n?.value==="json"||n?.value==="toon"?n.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="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]="47bfb287-bdd9-5984-9db4-cb996845d98c")}catch{}})();var ct=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:"--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"}]),Pn=new Set(ct.flatMap(e=>[e.flag,...e.aliases??[]]));import dt 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 ut(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 lt(e){let t=Object.keys(e).sort(),n={};for(let o of t){let s=e[o];s!==void 0&&(n[o]=T(s))}return n}function T(e){let t=ut(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(o=>T(o));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let o=n.toJSON();if(o!==e)return T(o)}return lt(e)}function Fn(e){return JSON.stringify(T(e))}function ue(e,t,n,o){for(let s=0;s<t.length;s+=1)if(!n.has(s)&&o(e,t[s]))return n.add(s),!0;return!1}function _t(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function ft(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function pt(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],o=new Set;for(let s of e)if(!ue(s,n,o,y))return!1;return!0}function mt(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()],o=new Set;for(let[s,r]of e.entries())if(!ue([s,r],n,o,([a,c],[u,l])=>y(a,u)&&y(c,l)))return!1;return!0}function gt(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,o)=>y(n,t[o]))}function Et(e,t){let n=Object.keys(e).sort((s,r)=>s.localeCompare(r)),o=Object.keys(t).sort((s,r)=>s.localeCompare(r));if(n.length!==o.length)return!1;for(let s=0;s<n.length;s+=1){let r=n[s];if(r!==o[s]||!y(e[r],t[r]))return!1}return!0}var bt=[_t,ft,pt,mt,gt];function y(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 bt){let o=n(e,t);if(o!==void 0)return o}return Et(e,t)}function Kn(e){return dt.createHash("sha256").update(e,"utf8").digest("hex")}function Bn(e,t){let n={};for(let s of t){let r=e[s];r!==void 0&&(n[s]=r)}let o=Object.keys(e).filter(s=>!t.includes(s)).sort((s,r)=>s.localeCompare(r));for(let s of o){let r=e[s];r!==void 0&&(n[s]=r)}return n}export{N as a,fe as b,pe as c,yt as d,P as e,j as f,V as g,ht as h,F as i,K as j,B as k,me as l,St as m,At as n,Tt as o,Nt as p,It as q,kt as r,wt as s,Rt as t,xt as u,vt as v,Ct as w,Dt as x,Lt as y,Mt as z,Ut as A,Pt as B,jt as C,ge as D,Vt as E,Ft as F,Kt as G,Bt as H,Gt as I,Xt as J,Yt as K,Ee as L,be as M,Wt as N,$t as O,ye as P,Ht as Q,Jt as R,Zt as S,Se as T,Ae as U,I as V,Qt as W,en as X,f as Y,_ as Z,ct as _,Pn as $,Fn as aa,y as ba,Kn as ca,Bn as da,Te as ea,Ne as fa,Ie as ga,rn as ha,an as ia,ke as ja,X as ka,cn as la,we as ma,Y as na,z as oa,dn as pa,un as qa,ln as ra,_n as sa,fn as ta,pn as ua,$ as va,x as wa,J as xa,v as ya,Z as za,g as Aa,se as Ba,wn as Ca,Rn as Da,Xe as Ea,ae as Fa,xn as Ga,ce as Ha,vn as Ia,Cn as Ja,Dn as Ka};
2
- //# sourceMappingURL=chunk-54EU2UVO.js.map
@@ -1,2 +0,0 @@
1
- import{$ as u,aa as p}from"./chunk-HGNKPSCB.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bf429f76-9722-5e34-a5f0-6ced8d1ed667")}catch{}})();var D="blocked_by",B="no-active-blocker";function d(e){return e.trim().toLowerCase()}function b(e){let t=new Set,n=typeof e.blocked_by=="string"?e.blocked_by.trim():"";n.length>0&&n.toLowerCase()!==B&&t.add(n);for(let o of e.dependencies??[])o.kind===D&&typeof o.id=="string"&&o.id.trim().length>0&&o.id.trim().toLowerCase()!==B&&t.add(o.id.trim());return[...t].sort((o,c)=>o.localeCompare(c))}function k(e,t,n){return b(e).map(o=>{let c=t.get(d(o));return c?{id:o,title:c.title,status:c.status,resolved:p(c.status,n)}:{id:o,title:null,status:null,resolved:!1}})}function C(e,t){let n=new Map(e.map(s=>[d(s.id),s])),o=new Set([...I(t),...t.blocked_statuses]),c=new Set;for(let s of e){let l=u(s.status,t);if(!o.has(l))continue;(t.blocked_statuses.has(l)||k(s,n,t).some(a=>!a.resolved))&&c.add(d(s.id))}return c}function I(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function E(e,t,n){let o=[d(e)],c=new Set;for(;o.length>0;){let s=o.pop();if(!c.has(s)){c.add(s);for(let l of t.get(s)??[]){if(!p(l.status,n))return!0;o.push(d(l.id))}}}return!1}function T(e){let t=new Map,n=new Map,o=new Map;for(let c of e){t.set(d(c.id),c);let s=typeof c.parent=="string"?c.parent.trim():"";if(s.length>0){let l=d(s),i=n.get(l)??[];i.push(c),n.set(l,i)}for(let l of b(c)){let i=d(l),a=o.get(i)??[];a.push(c.id),o.set(i,a)}}return{itemsById:t,childrenByParent:n,blockedByReverse:o}}function x(e,t,n){let{itemsById:o,childrenByParent:c,blockedByReverse:s}=T(t),l=new Set([...I(n),...n.blocked_statuses]),i=new Set(t.filter(r=>!p(r.status,n)).map(r=>d(r.id))),a=[],y=[],m=0,h=0;for(let r of e){if(!l.has(u(r.status,n)))continue;if(m+=1,E(r.id,c,n)){h+=1;continue}let w=k(r,o,n).filter(f=>!f.resolved),v=(s.get(d(r.id))??[]).filter(f=>i.has(d(f))).sort((f,S)=>f.localeCompare(S)),_={item:r,open_blockers:w,unblocks:v},g=n.blocked_statuses.has(u(r.status,n));w.length===0&&!g?a.push(_):y.push(_)}return{ready:a,blocked:y,active_count:m,container_count:h}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9184e723-8269-5e45-8c6a-52fd02da60e6")}catch{}})();export{b as a,k as b,C as c,x as d};
2
- //# sourceMappingURL=chunk-5FLBTZJQ.js.map
@@ -1,2 +0,0 @@
1
- import{pa as g,qa as S,sa as b,ta as D}from"./chunk-U646T7Z6.js";import{La as I,Va as _,Za as w,db as h}from"./chunk-HGNKPSCB.js";import{D as p,J as y}from"./chunk-FPDYXZBK.js";import{Y as u,Z as m}from"./chunk-54EU2UVO.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="13c02696-29a7-598e-888a-3502fd88bfbe")}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]="078456b8-ed61-5c47-afc7-7553833934e1")}catch{}})();var k=3,x=20,U=.8,N=100,M=1e3,A=1e6;function oe(e){return e===void 0?[]:[`likely_duplicates:${e.result.items.map(t=>t.id).join(",")}`]}function R(e){let t=e.limit??k,r=e.threshold??U;if(!Number.isSafeInteger(t)||t<0||t>x)throw new m(`Similarity limit must be an integer from 0 to ${x}.`,u.USAGE);if(!Number.isFinite(r)||r<0||r>1)throw new m("Similarity threshold must be a number from 0 to 1.",u.USAGE);return{limit:t,threshold:r}}function O(e){let t=e.limit??N;if(!Number.isSafeInteger(t)||t<0||t>M)throw new m(`Duplicate cluster limit must be an integer from 0 to ${M}.`,u.USAGE);let r=e.since===void 0?void 0:new Date(e.since);if(r&&Number.isNaN(r.getTime()))throw new m("Duplicate cluster --since must be a valid ISO timestamp.",u.USAGE);return{limit:t,since:r}}async function $(e,t){let r=y(e.cwd??process.cwd(),e.pmRoot),a=await I(r),n=p(a),i=e.statuses?new Set(e.statuses.map(o=>o.trim()).filter(Boolean)):void 0;return(await h(r,a.item_format,n.type_to_folder,void 0,a.schema)).filter(o=>(!i||i.has(o.status))&&(!t||new Date(o.created_at).getTime()>=t.getTime())).sort((o,d)=>o.id.localeCompare(d.id)).map(o=>({item:o,prepared:S(o.title)}))}function E(e,t=A){let r=new Set,a=[new Map,new Map,new Map];for(let[n,i]of e.entries()){let o=[[i.prepared.normalized],i.prepared.issueCodes,i.prepared.tokens];for(let[d,s]of o.entries())for(let c of s){let l=a[d].get(c)??[];for(let f of l)r.add(`${f}:${n}`);if(r.size>t)throw new m(`Duplicate sweep exceeded ${A} candidate pairs; narrow it with statuses or since.`,u.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the batch duplicate query until its deterministic candidate set fits the disclosed safety bound."});l.push(n),a[d].set(c,l)}}return r}var se={buildDuplicateClusters:L,collectDuplicateCandidatePairs:E,createDuplicateUnionFind:C};function C(e){let t=Array.from({length:e},(a,n)=>n);return{parent:t,findRoot:a=>{let n=a;for(;t[n]!==n;)n=t[n];for(;t[a]!==a;){let i=t[a];t[a]=n,a=i}return n}}}function q(e,t,r,a){let n=[];for(let i of t){let[o,d]=i.split(":").map(f=>Number.parseInt(f,10)),s=D(e[o].prepared,e[d].prepared);if(s.score<r)continue;let c=a.findRoot(o),l=a.findRoot(d);c!==l&&(a.parent[l]=c),n.push({left_id:e[o].item.id,right_id:e[d].item.id,...s})}return n}function L(e,t,r,a){let n=new Map;for(let i of e.keys()){let o=r.findRoot(i),d=n.get(o)??[];d.push(i),n.set(o,d)}return[...n.values()].filter(i=>i.length>1).map(i=>{let o=new Set(i.map(s=>e[s].item.id)),d=t.filter(s=>o.has(s.left_id)&&o.has(s.right_id)).sort((s,c)=>c.score-s.score||s.left_id.localeCompare(c.left_id)||s.right_id.localeCompare(c.right_id));return{id:e[i[0]].item.id,items:i.map(s=>{let c=e[s].item;return{id:c.id,title:c.title,status:c.status,type:c.type}}),matches:d,max_score:d[0]?.score??0}}).sort((i,o)=>o.max_score-i.max_score||i.id.localeCompare(o.id)).slice(0,a)}function F(e,t,r,a,n){return t.filter(i=>!r.has(i.id)).map(i=>({id:i.id,title:i.title,status:i.status,type:i.type,...b(e,i.title)})).filter(i=>i.score>=a).sort((i,o)=>o.score-i.score||i.id.localeCompare(o.id)).slice(0,n)}async function P(e,t={}){let r=e.title.trim();if(r.length===0)throw new m("Similarity candidate title must not be empty.",u.USAGE);let{limit:a,threshold:n}=R(t),i=y(t.cwd??process.cwd(),t.pmRoot),o=await I(i),d=p(o),s=await w(i,Object.values(d.type_to_folder)),c=g(r),l=s&&c.length>0?await _({pmRoot:i,expectedSourceCursor:s.source_cursor,query:c.map(v=>`"${v.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(a*10,50)}):null,f=l===null?await h(i,o.item_format,d.type_to_folder,void 0,o.schema):l.items,T=F(r,f,new Set(e.excludeIds??[]),n,a);return{items:T,count:T.length,threshold:n,source:l?"persistent_index":"metadata_fallback"}}async function de(e={}){let{threshold:t}=R({...e,limit:void 0}),{limit:r,since:a}=O(e),n=await $(e,a),i=E(n),o=C(n.length),d=q(n,i,t,o),s=L(n,d,o,r);return{clusters:s,count:s.length,threshold:t,source:"metadata_scan",cost:{item_count:n.length,candidate_pairs:i.size,scored_pairs:i.size}}}async function ce(e,t){if(t.mode==="off")return;let r=await P(e,t);if(r.count===0)return;let a=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!a){let n=r.items.map(i=>`${i.id} (${i.status}): ${i.title}`).join("; ");throw new m(`Likely duplicate item(s) found: ${n}. Reuse the canonical item or pass --allow-duplicate with explicit intent.`,u.CONFLICT,{code:"likely_duplicate",required:"Reuse an existing item, or explicitly acknowledge the duplicate with --allow-duplicate.",recovery:{suggested_flags:["--allow-duplicate"]}})}return{mode:t.mode,bypassed:a,result: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]="412fc2d2-daee-5d87-82ab-5411a1503087")}catch{}})();function me(e,t){let r=t??{};return e.filter(a=>r[a.id]!==a.updated_at).map(a=>a.id).sort((a,n)=>a.localeCompare(n))}export{oe as a,se as b,P as c,de as d,ce as e,me as f};
2
- //# sourceMappingURL=chunk-5GJ57YKN.js.map
@@ -1,14 +0,0 @@
1
- import{f as xe,g as Ze}from"./chunk-IAS7PMLG.js";import{a as qt,g as Xe,i as Ht}from"./chunk-ZOLDTUU7.js";import{f as hn}from"./chunk-HCUC62AB.js";import{s as he,t as fn,u as ge,v as pn,wa as _n}from"./chunk-U646T7Z6.js";import{Ca as J,Da as an,Fa as sn,Ia as on,Ja as cn,K as le,L as ne,La as L,P as Jt,Ua as ln,V as Xt,W as Zt,Z as Qt,Za as dn,_ as en,ab as Ce,ba as Qe,bb as Ie,cb as un,da as tn,eb as mn,hb as Te,k as Y,na as nn,q as Yt,za as rn}from"./chunk-HGNKPSCB.js";import{D as H,I as Ut,J as j,K as _e,Ka as Vt,M as B,P as zt,T as M,_ as Gt,aa as Ke,h as Lt,o as $t,p as N,q as jt,r as pe,u as Ve,v as Bt}from"./chunk-FPDYXZBK.js";import{i as Kt}from"./chunk-FI6DWU2M.js";import{N as Nt,U as Mt,V as Ee,Y as _,Z as h,aa as Ye,ba as Wt,ca as Je,t as He}from"./chunk-54EU2UVO.js";import{readFile as Oe,realpath as rt,writeFile as wi}from"node:fs/promises";import{execFile as ki}from"node:child_process";import T from"node:path";import{promisify as vi}from"node:util";import{readFile as fi,writeFile as pi}from"node:fs/promises";import ye 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]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var yn="# pm-cli:runtime-cache:start",et="# pm-cli:runtime-cache:end",wn=".agents/pm",tt=["runtime/","search/","locks/","transactions/","checkpoints/"],_i=["search/eval-queries.json"];async function gn(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new h("The workspace .gitignore is not writable.",_.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function kn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function nt(e){let t=e.replaceAll("\\","/");return ye.isAbsolute(e)||t===".."||t.startsWith("../")}function hi(e=wn){let t=kn(e);return[yn,...tt.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),..._i.map(n=>`!${t}/${n}`),et].join(`
2
- `)}async function vo(e,t={}){let n=ye.join(e,".gitignore"),r=wn;if(t.pmRoot!==void 0){let d=kn(ye.relative(ye.resolve(e),ye.resolve(t.pmRoot)));if(nt(d))return{path:n,changed:!1};d.length>0&&(r=d)}let i="";try{i=await gn(()=>fi(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let a=i.indexOf(yn),s=i.indexOf(et),c=(a>=0&&s>=a?`${i.slice(0,a)}${i.slice(s+et.length)}`:i).trimEnd(),l=`${c.length>0?`${c}
3
-
4
- `:""}${hi(r)}
5
- `;return l===i?{path:n,changed:!1}:(await gn(()=>pi(n,l,"utf8")),{path:n,changed:!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]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var gi="PM_SOURCE_CONTEXT_ACCESS",yi="PM_ALLOW_SOURCE_CONTEXT_WRITES";function vn(e){let t=e[gi],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",r=n==="read_only"&&e[yi]?.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]="fce8fc1d-b9ca-55bc-9c5a-f4f9728a7158")}catch{}})();var it=vi(ki),se="# pm-cli:merge-drivers:start",we="# pm-cli:merge-drivers:end",bi="merge-fence";function bn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Rn(){let e=Bt(import.meta.url,["../../.."]);return`${bn(process.execPath)} ${bn(T.join(e,"dist","cli.js"))}`}var An=[{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 Si(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=e.environment.PM_SOURCE_PM_PATH?.trim(),i=vn(e.environment),a=!!(n&&r),s=t===void 0&&a&&(e.dryRun||i.source_writes_allowed);if(t!==void 0){let o=j(e.cwd,t);return{pm_root:o,workspace_start:o,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}return s?{pm_root:T.resolve(r),workspace_start:T.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:i}:{pm_root:a?j(e.cwd,".agents/pm"):j(e.cwd),workspace_start:e.cwd,source_coordinates_available:a,source_context_selected:!1,source_policy:i}}async function ke(e){try{let{stdout:t}=await it("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await rt(t.trim())}catch{return null}}async function En(e){let t=await ke(e);if(t===null)throw new h("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function at(e,t){return T.relative(e,t).replaceAll("\\","/")}function V(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Sn(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 Ri(e,t){let n=Sn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let r=Sn(e,n.nextOffset+1);if(r===null||e.slice(r.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(T.basename(n.value))||T.basename(r.value)!=="cli.js"||T.basename(T.dirname(r.value))!=="dist"||!await N(n.value)||!await N(r.value))return!1;try{let i=T.dirname(T.dirname(r.value)),a=JSON.parse(await Oe(T.join(i,"package.json"),"utf8")),s=typeof a.bin=="object"&&a.bin!==null&&"pm"in a.bin?a.bin.pm:void 0;return a.name==="@unbrained/pm-cli"&&(a.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function st(e,t){let n=e.length>0?`${e}/`:"",r=[`${V(`${n}**/*.toon`)} merge=pm-item-toon`,`${V(`${n}**/*.md`)} merge=pm-item-markdown`];for(let i of t)r.push(`${V(`${n}${i}/*.toon`)} merge=pm-item-toon`),r.push(`${V(`${n}${i}/*.md`)} merge=pm-item-markdown`);return r.push(`${V(`${n}**/*.jsonl`)} merge=pm-relationship`),r.push(`${V(`${n}history/*.jsonl`)} merge=pm-history`),r.push(`${V(`${n}settings.json`)} merge=pm-json`),r.push(`${V(`${n}**/*.json`)} merge=pm-json`),r.push(`${V(`${n}extensions/**`)} -merge`),r.push(`${V(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),r}async function xn(e,t,n){let r=T.join(e,".gitattributes"),i="";try{i=await Oe(r,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let a=[se,...t,we].join(`
6
- `),s=i.indexOf(se),o=i.indexOf(we),l=(s>=0&&o>s?`${i.slice(0,s)}${i.slice(o+we.length)}`:i.replace(se,"").replace(we,"")).trimEnd(),d=`${l.length>0?`${l}
7
-
8
- `:""}${a}
9
- `;return d===i?{path:r,changed:!1}:(n||await wi(r,d,"utf8"),{path:r,changed:!0})}function Fe(e){let t=H(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,r)=>n.localeCompare(r))}async function Cn(e,t){let n=T.resolve(e),r=null,i="",a=n;for(let p=0;p<8;p+=1){let g=T.join(a,".gitattributes");try{let S=await Oe(g,"utf8");if(S.includes(se)){r=a,i=S;break}}catch{}let y=T.dirname(a);if(y===a)break;a=y}if(r===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=T.join(r,".gitattributes"),o=i.indexOf(se),c=i.indexOf(we),l=c>o?i.slice(o+se.length,c).split(`
10
- `).map(p=>p.trim()).filter(p=>p.length>0):[],d=st(at(r,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),k=l.filter(p=>!m.has(p));return{status:f.length>0||k.length>0?"drift":"ok",path:s,missing_patterns:f,stale_patterns:k,schema_scope:"project"}}async function In(e){let t=Rn(),n=[],r=[];for(let i of An){let a=`merge.${i.key}.driver`,s=` merge driver ${i.artifact} "%O" "%A" "%B"${i.itemPath===void 0?"":` --item-path ${i.itemPath}`}`,o=`${t}${s}`;try{let{stdout:c}=await it("git",["config","--local","--get",a],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==o&&!await Ri(l,s)&&r.push(a)}catch{n.push(a)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Bo(e){let t;try{t=await En(T.resolve(e))}catch{return{status:"no_git"}}let n=at(t,T.resolve(e)),r=await L(e),i=le(void 0,r.author_default),a=await Jt(e,bi,r.locks.ttl_seconds,i,!1,cn(r).force_required_for_stale_lock,r.locks.wait_ms);try{let s=T.join(t,".gitattributes"),o;try{o=await Oe(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:s};throw u}if(!o.includes(se))return{status:"not_installed",path:s};let c=await L(e),l=Fe(c),d=await xn(t,st(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await a()}}async function Uo(e,t){let n=Si({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),r=n.pm_root;if(!await N(B(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,_.NOT_FOUND);let i=await En(n.workspace_start);return Ai({pmRoot:r,workspaceRoot:i,dryRun:e.dryRun===!0})}async function Ai(e){let t=T.resolve(e.pmRoot),n=T.resolve(e.workspaceRoot),r=e.dryRun===!0,i,a;try{[i,a]=await Promise.all([rt(t),rt(n)])}catch(f){throw new h(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,_.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=at(a,i);if(nt(s))throw new h(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,_.USAGE);let o=await L(i),c=Fe(o),l=st(s,c),d=[],u=Rn();for(let f of An)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!r)try{for(let f of d)await it("git",["config","--local",f.key,f.value],{cwd:a,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new h(`Cannot install repository-local merge drivers in ${a}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,_.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 m=await xn(a,l,r);return{ok:!0,dry_run:r,workspace_root:a,pm_root:i,gitattributes:{path:m.path,changed:m.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 validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"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:ne()}}import Ne from"node:fs/promises";import Me from"node:path";import{Option as ic}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]="d44229ca-8c70-5d55-a168-32bfe66711e6")}catch{}})();function Ei(e,t){let n=[],r=new Set;for(let i of t.keys){if(!Object.hasOwn(e,i))continue;let a=e[i];if(a!=null){if(typeof a=="string"){n.push(a);continue}if(!Array.isArray(a)||!a.every(s=>typeof s=="string"))return;r.has(a)||(r.add(a),n.push(...a))}}return n.length>0?n.join("; "):void 0}function Pe(e,t){return e.find(r=>r.target===t)??{target:t,keys:[t]}}function w(e,t){return e[t]===!0?!0:void 0}function X(e,t){return e[t]===!1?!0:void 0}function xi(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Tn(e,t){for(let[n,r]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=r)}function On(e){let t=i=>Xe(e,Pe(xe,i)),n=i=>Ht(e,Pe(Ze,i)),r={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Ei(e,Pe(Ze,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:w(e,"replaceDeps"),replaceTests:w(e,"replaceTests"),replaceFiles:w(e,"replaceFiles"),replaceDocs:w(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:w(e,"clearDeps"),clearComments:w(e,"clearComments"),clearNotes:w(e,"clearNotes"),clearLearnings:w(e,"clearLearnings"),clearFiles:w(e,"clearFiles"),clearTests:w(e,"clearTests"),clearDocs:w(e,"clearDocs"),clearReminders:w(e,"clearReminders"),clearEvents:w(e,"clearEvents"),clearTypeOptions:w(e,"clearTypeOptions")};return Tn(r,e),r}function C(e,t){let n=Pe(qt,t),r=Xe(e,n);if(r!==void 0)return r;for(let i of n.keys){let a=e[i];if(Array.isArray(a)){let s=a.filter(o=>typeof o=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof a=="string")return a;if(typeof a=="number"&&Number.isFinite(a))return String(a)}}function Ci(e){let t=w(e,"filterFilesMissing"),n=w(e,"filterDocsMissing");return{filterReviewerMissing:w(e,"filterReviewerMissing"),filterRiskMissing:w(e,"filterRiskMissing"),filterConfidenceMissing:w(e,"filterConfidenceMissing"),filterSprintMissing:w(e,"filterSprintMissing"),filterReleaseMissing:w(e,"filterReleaseMissing"),hasNotes:w(e,"hasNotes"),hasLearnings:w(e,"hasLearnings"),hasFiles:w(e,"hasFiles"),hasDocs:w(e,"hasDocs"),hasTests:w(e,"hasTests"),hasComments:w(e,"hasComments"),hasDeps:w(e,"hasDeps"),hasBody:w(e,"hasBody"),hasLinkedCommand:w(e,"hasLinkedCommand"),noNotes:X(e,"notes"),noLearnings:X(e,"learnings"),noFiles:X(e,"files")??t,filterFilesMissing:t,noDocs:X(e,"docs")??n,filterDocsMissing:n,noTests:X(e,"tests"),noComments:X(e,"comments"),noDeps:X(e,"deps"),emptyBody:w(e,"emptyBody"),noLinkedCommand:X(e,"linkedCommand")}}function ot(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:w(e,"today"),recent:w(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:X(e,"truncate"),includeBody:w(e,"includeBody"),strictRead:w(e,"strictRead"),compact:w(e,"compact"),brief:w(e,"brief"),full:w(e,"full"),fields:C(e,"fields"),sort:C(e,"sort"),order:C(e,"order"),tree:w(e,"tree"),treeDepth:C(e,"treeDepth"),filterAcMissing:w(e,"filterAcMissing"),filterEstimatesMissing:xi(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:w(e,"filterResolutionMissing"),filterMetadataMissing:w(e,"filterMetadataMissing"),...Ci(e)};return Tn(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bcda2578-3b01-5e64-9d53-cd32c0f927b8")}catch{}})();function b(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function O(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Ii(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function ve(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fc(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new h(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new h(`${t} must be a finite integer.`,_.USAGE);return n}}function pc(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:b(e,"limit")??b(t,"limit")}function _c(e){let t=b(e,"outputFormat");return{json:!0,quiet:!0,author:b(e,"author"),path:b(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:b(e,"outputInclude"),outputLimit:O(e,"outputLimit"),outputBudget:O(e,"outputBudget"),outputSession:b(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Ti=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Oi=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"]),Fi=new Set(["files","files-discover","docs","test","test-all"]),Pi=new Set(["claim","release","start-task","pause-task","close-task"]),Di={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},Ni=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function Pn(e,t){let n={},r=t!==void 0&&Fi.has(t),i=t==="files"||t==="files-discover"||t==="docs";for(let[a,s]of Object.entries(e)){if(Array.isArray(s)&&Ti.has(a)){n[a]=s.join(",");continue}if(a==="note"&&i){n[a]=s;continue}if(typeof s=="string"&&Oi.has(a)){n[a]=[s];continue}if(typeof s=="string"&&r&&(a==="add"||a==="remove")){n[a]=[s];continue}n[a]=s}return n}function hc(e,t){let n=Gt(e.options),r={},i=c=>{n[c]!==void 0||e[c]===void 0||(r[c]=e[c])};for(let c of Di[t??""]??[])i(c);for(let c of Ni)i(c);let a=Pn({...r,...n},t),s=b(e,"author"),o=t!==void 0&&Pi.has(t)?b(e,"assignee")??b(a,"assignee"):void 0;return s&&a.author===void 0?{...a,author:s}:o&&a.author===void 0?{...a,author:o}:a}function gc(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function yc(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function wc(e){let t=[],n=!0;for(let r of e.trim().toLowerCase()){if(r>="a"&&r<="z"||r>="0"&&r<="9"){t.push(r),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function kc(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function dt(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function vc(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),r={};for(let[a,s]of Object.entries(e))n.has(a)||(r[a]=s);let i={...r,...t};return delete i.args,i}function bc(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function lt(e){return{type:O(e,"filterType"),tag:O(e,"filterTag"),priority:O(e,"filterPriority"),deadlineBefore:O(e,"filterDeadlineBefore"),deadlineAfter:O(e,"filterDeadlineAfter"),updatedAfter:O(e,"filterUpdatedAfter"),updatedBefore:O(e,"filterUpdatedBefore"),createdAfter:O(e,"filterCreatedAfter"),createdBefore:O(e,"filterCreatedBefore"),ids:Ii(e,"ids"),assignee:O(e,"filterAssignee"),assigneeFilter:O(e,"filterAssigneeFilter")??O(e,"filterAssignee_filter"),parent:O(e,"filterParent"),sprint:O(e,"filterSprint"),release:O(e,"filterRelease"),limit:O(e,"limit"),offset:O(e,"offset")}}function ct(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return dt(e)}function De(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Sc(e){let t=ct(e.kind),n=ct(e.exemptIsolate),r=ct(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:De(e.maxDepth),limit:De(e.limit),after:b(e,"after"),direction:b(e,"direction"),maxPaths:De(e.maxPaths),sample:De(e.sample),...n===void 0?{}:{exemptIsolate:n},...r===void 0?{}:{exemptIsolateType:r},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Rc(e){return{status:b(e,"filterStatus"),list:ve(e.list)?ot(e.list):lt(e),reason:b(e,"reason"),resolution:b(e,"resolution"),expectedResult:b(e,"expectedResult")??b(e,"expected_result")??b(e,"expected"),actualResult:b(e,"actualResult")??b(e,"actual_result")??b(e,"actual"),validateClose:b(e,"validateClose")??b(e,"validate_close"),author:b(e,"author"),message:b(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Mi=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Fn(e){let t={};for(let[n,r]of Object.entries(e))Mi.has(n)||(t[n]=r);return Dn(t)}function Dn(e){let t=Pn(e,"update-many");for(let n of xe)for(let r of n.keys){let i=t[r];typeof i=="number"&&Number.isFinite(i)&&(t[r]=String(i))}return On(t)}function Ac(e){if(ve(e.list)||ve(e.update)){let t=ve(e.update)?e.update:Fn(e);return{status:O(e,"filterStatus"),list:ve(e.list)?ot(e.list):lt(e),update:Dn(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:O(e,"filterStatus"),list:lt(e),update:Fn(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:b(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1: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]="4fd16197-979e-5269-bed7-f2fb0e2038c2")}catch{}})();function Z(e,t){throw new h(e,_.USAGE,t)}var Li="2026-07-15T06:22:12.276Z",$i=Date.parse(Li),ji=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],Nn=e=>typeof e=="string"?e:"",Mn=e=>{let t=e??{},n=Nn(t.author).trim().toLowerCase(),r=Number(["","unknown"].includes(n)),i=+(Date.parse(Nn(t.ts))>=$i);return ji[r][i]};function Ln(e,t,n=20,r=new Set,i=!1){let a=[],s=[],o={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let k;try{k=JSON.parse(f)}catch{continue}l+=1;let p=Mn(k);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&r.has(`${e}:${m+1}`)){u+=1;continue}o[p]+=1,i&&p==="actionable_unknown"&&s.push({item_id:e,line:m+1}),a.length<c&&a.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:o.legacy_unknown,actionable_unknown_event_count:o.actionable_unknown,acknowledged_actionable_event_count:u,samples:a,samples_truncated:o.legacy_unknown+o.actionable_unknown>a.length,actionable_events:s}}var Dc=(e,t,n=20,r=new Set)=>Ln(e,t,n,r);function Bi(e){let t=new Set;for(let n of e.split(/\r?\n/)){let r;try{r=JSON.parse(n)}catch{continue}let a=(typeof r=="object"&&r!==null&&typeof r.context=="object"&&r.context!==null?r.context:{}).author_acknowledgment;if(!(typeof a!="object"||a===null||!Array.isArray(a.events)))for(let s of a.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 ut=async(e,t=20,n=!1)=>{let r=Me.join(e,"history"),i;try{i=(await Ne.readdir(r)).filter(y=>y.endsWith(".jsonl")).sort((y,S)=>y.localeCompare(S))}catch{i=[]}let a=new Set,s=[],o=[],c=0,l=0,d=0,u=0,m=0,f=0,k="_workspace.jsonl",p=new Set;if(i.includes(k))try{p=Bi(await Ne.readFile(Me.join(r,k),"utf8"))}catch{p=new Set}for(let y of i){let S;try{S=await Ne.readFile(Me.join(r,y),"utf8")}catch{continue}let A=y.slice(0,-6),E=Ln(A,S,t-s.length,p,n);c+=1,l+=E.checked_events,d+=E.unknown_event_count,u+=E.legacy_unknown_event_count,m+=E.actionable_unknown_event_count,f+=E.acknowledged_actionable_event_count,E.unknown_event_count>0&&a.add(A),s.push(...E.samples),n&&o.push(...E.actionable_events)}let g=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...a].sort((y,S)=>y.localeCompare(S)),samples:s,samples_truncated:g>s.length,...n?{actionable_events:o}:{}}};function Ui(e,t){let n=e.length>0;return n&&t&&Z("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&Z("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:zi(e),all_actionable:t}}function zi(e){return e.map(t=>{let n=t.lastIndexOf(":"),r=t.slice(0,n).trim(),i=Number(t.slice(n+1)),a=r===J||/^[a-z0-9][a-z0-9-]*$/iu.test(r);return(n<1||!a||!Number.isSafeInteger(i)||i<1)&&Z(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:r,line:i}})}function Nc(e,t){let n=Ui(dt(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Gi(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:b(t,"attributedAuthor")??b(t,"attributed_author")??"",reviewer:b(t,"reviewer")??"",reason:b(t,"reason")??""})}async function Gi(e,t){let n=t.reviewer.trim(),r=t.attributed_author.trim(),i=t.reason.trim(),a=t.events??[],s=+(t.all_actionable===!0)+ +(a.length>0);s===0&&Z("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&Z("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let o=t.all_actionable===!0?(await ut(e,0,!0)).actionable_events:a;[o.length>0,n.length>0,n.toLowerCase()!=="unknown",r.length>0,r.toLowerCase()!=="unknown",i.length>0].includes(!1)&&Z("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(o.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){[m.item_id===J||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&Z(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let k;try{let g=(await Ne.readFile(Me.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];k=JSON.parse(g??"")}catch{Z(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Mn(k)!=="actionable_unknown"&&Z(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"})}let d=await L(e),u=await sn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:r}},message:i,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{execFile as Wi}from"node:child_process";import{randomUUID as qi}from"node:crypto";import{readdir as Hi,readFile as Vi}from"node:fs/promises";import be from"node:path";import{promisify as Ki}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var Yi=Ki(Wi);async function mt(e){try{let{stdout:t}=await Yi("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}}function $n(e){return`${e}.json`}function qc(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,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Je(Ye(t.retained)),discarded_hash:Je(Ye(t.discarded))}))}}async function Hc(e){let t=await mt(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,i=be.basename(r,be.extname(r)),a={version:1,id:qi(),item_path:r.replaceAll("\\","/"),item_id:i,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:ne()};return await $t(t),await pe(be.join(t,$n(a.id)),`${JSON.stringify(a,null,2)}
11
- `),a}async function ft(e,t={}){let n=await mt(e);if(n===null||!await N(n))return[];let r=[],i;try{i=await Hi(n)}catch{return[]}for(let a of i.sort((s,o)=>s.localeCompare(o)))if(a.endsWith(".json"))try{let s=JSON.parse(await Vi(be.join(n,a),"utf8"));s.version===1&&(t.includeReconciled||s.state==="pending")&&r.push(s)}catch{}return r.sort((a,s)=>a.created_at.localeCompare(s.created_at))}async function Vc(e,t){let n=await mt(e);n!==null&&await pe(be.join(n,$n(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:ne()},null,2)}
12
- `)}async function Kc(e){let t=await ft(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:ne()}}import de from"node:fs/promises";import ue 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 Ji(e,t){let n=[...new Set(Object.values(t))],r=[];return await Promise.all(n.map(async i=>{let a;try{a=await de.readdir(ue.join(e,i))}catch{return}for(let s of a)for(let o of Ut)if(s.toLowerCase().endsWith(o)){r.push({relativePath:`${i}/${s}`,id:s.slice(0,-o.length)});break}})),r.sort((i,a)=>i.relativePath.localeCompare(a.relativePath))}function Xi(e,t){let{id:n,relativePath:r,liveItemIds:i,out:a}=e,s=Qe(t);if(s){a.conflictMarkers.push({id:n,path:r,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let o=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");o=d}catch{a.unparseable.push({id:n,path:r,line:l.number,detail:"history line is not a valid JSON object"});return}o!==null&&(o.op==="delete"&&i.has(n)&&a.resurrected.push({id:n,deleted_at:typeof o.ts=="string"?o.ts:"",deleted_by:typeof o.author=="string"?o.author:""}),o.op==="history_repair"&&Array.isArray(o.patch)&&o.patch.length>0&&(a.repairReconciliations+=1))}function pt(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 Zi(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},r;try{r=await de.readdir(ue.join(e,"history"))}catch{return n}for(let i of r.sort((a,s)=>a.localeCompare(s))){if(!i.endsWith(".jsonl"))continue;n.scanned+=1;let a;try{a=await de.readFile(ue.join(e,"history",i),"utf8")}catch(s){n.unparseable.push({id:i.slice(0,-6),path:`history/${i}`,detail:pt("history stream",s)});continue}Xi({id:i.slice(0,-6),relativePath:`history/${i}`,liveItemIds:t,out:n},a)}return n}function jn(e){let t=Qe(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 Qi(e){let t=[],n=0,r=null;try{r=await jt(B(e))}catch(a){n+=1,t.push({path:"settings.json",detail:pt("configuration file",a)})}if(r!==null){n+=1;let a=jn(r);a!==null&&t.push({path:"settings.json",detail:a})}let i;try{i=await de.readdir(ue.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let a of i.sort((s,o)=>s.localeCompare(o))){if(!a.endsWith(".json"))continue;n+=1;let s;try{s=await de.readFile(ue.join(e,"schema",a),"utf8")}catch(c){t.push({path:`schema/${a}`,detail:pt("configuration file",c)});continue}let o=jn(s);o!==null&&t.push({path:`schema/${a}`,detail:o})}return{scanned:n,unparseable:t}}async function Bn(e,t,n,r={}){let i=await Ji(e,n),a=new Set(i.map(u=>u.id)),s=new Map;for(let u of i){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let o=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,k)=>f.localeCompare(k))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(i.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=ue.join(e,u.relativePath);return tn(await de.readFile(m,"utf8"),{format:m.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 Zi(e,a),d=await Qi(e);return{item_files_on_disk:i.length,item_ids_on_disk:a.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:o,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 It from"node:fs/promises";import{realpathSync as hs}from"node:fs";import{execFile as gs}from"node:child_process";import $ from"node:path";import{promisify as ys}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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var ea=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:"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_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 validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{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_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{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 ta(e){if(typeof e!="string")return;let t=e.trim();for(let n of ea)if(t===n.code||t.startsWith(`${n.code}:`))return n}function na(e){let t={};for(let n of e){let r=ta(n);r!==void 0&&!Object.prototype.hasOwnProperty.call(t,r.code)&&(t[r.code]=r.command)}return t}function Un(e){return Object.values(na(e))}import me from"node:fs/promises";import{createHash as ra}from"node:crypto";import Gn 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var Wn=3,ia="history-drift-cache.json";function qn(e){return Gn.join(e,"runtime",ia)}async function aa(e){try{let t=await me.readFile(qn(e),"utf8"),n=JSON.parse(t);return n.version!==Wn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function Hn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function sa(e,t,n,r,i){let a=an(e),s;try{s=await me.stat(a)}catch(l){return Hn(l,"ENOENT")||i.unreadableStreams.push(J),!1}let o=i.missingStreams.length,c=await Kn({itemId:J,historyPath:a,stat:s,cached:t[J],verifyCacheHitByContent:r,accumulator:i});return c.verification?(c.verification.chainOk||i.chainMismatches.push(J),n[J]={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},c.cacheDirty):(i.missingStreams.splice(o),c.cacheDirty)}function Vn(e){return ra("sha256").update(e).digest("hex")}async function oa(e){let t=await me.readFile(e,"utf8");return Vn(t)}async function ca(e){let t=await me.readFile(e,"utf8"),n=Vn(t);if(t.trim().length===0)return null;let r=[],i=null;for(let a of t.split(/\r?\n/)){let s=a.trim();if(s.length===0)continue;let o=JSON.parse(s);if(typeof o.after_hash!="string"||o.after_hash.trim().length===0)throw new Error("missing after_hash");r.push(o),i=o.after_hash}return i?{latestAfterHash:i,chainOk:rn(r).ok,contentHash:n}:null}function la(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function zn(e,t,n){try{let r=await ca(t);return r||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Kn(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(la(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await zn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let r;if(e.verifyCacheHitByContent)try{r=await oa(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else r=t;return!e.verifyCacheHitByContent||r===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:r},cacheDirty:!1}:{verification:await zn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Yn(e,t,n={}){let r={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},a=(await aa(e))?.entries??{},s={},o=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=zt(e,u.id),f;try{f=await me.stat(m)}catch(A){Hn(A,"ENOENT")?r.missingStreams.push(u.id):r.unreadableStreams.push(u.id);continue}let k=a[u.id],p=await Kn({itemId:u.id,historyPath:m,stat:f,cached:k,verifyCacheHitByContent:c,accumulator:r});if(o||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||r.chainMismatches.push(u.id),s[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:p.verification.contentHash,latest_after_hash:p.verification.latestAfterHash,chain_ok:p.verification.chainOk};let{body:g,...y}=u;nn({metadata:y,body:g})!==p.verification.latestAfterHash&&r.hashMismatches.push(u.id)}let l=await sa(e,a,s,c,r);if(o||=l,o||Object.keys(a).length!==Object.keys(s).length){let u=qn(e);try{await me.mkdir(Gn.dirname(u),{recursive:!0}),await pe(u,JSON.stringify({version:Wn,entries:s}))}catch{}}let d=[...new Set([...r.missingStreams,...r.unreadableStreams,...r.hashMismatches,...r.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...r,driftedItems: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]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var da=["metadata","resolution"],_t=["metadata","resolution","estimates","lifecycle"],ua="completed";function ht(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Jn(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Xn(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let r=Jn(n.close_reason)??ua;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:r,command:`pm update ${n.id} --resolution ${ht(r)}`,gate:"resolution"})}return t}function Zn(e){let t=[];for(let n of e){let r=Jn(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 ${ht(r)}`,gate:"metadata"})}return t}function Qn(e,t){return e.map(n=>{let r=on(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 er(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 tr(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 ${ht(n.path)}`})}return t}function nr(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: ${_t.join(", ")}.`,_.USAGE);return new Set(da)}let n=new Set;for(let r of t){let i=r.toLowerCase().replaceAll("-","_");if(_t.includes(i)){n.add(i);continue}throw new h(`Unknown --fix-scope value "${r}". Supported values: ${_t.join(", ")}.`,_.USAGE)}return n}function rr(e,t){let n=[],r=[];for(let i of e)i.gate!==void 0&&!t.has(i.gate)?r.push(i):n.push(i);return{applicable:n,gated:r}}function Se(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]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var ma=/^([A-Z][A-Z0-9]*-\d+)\b/;function fa(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=ma.exec(t);return n?n[1]:null}function ir(e){return typeof e=="string"&&e.trim().length>0}function ar(e){let t=new Map;for(let r of e){if(typeof r.title!="string"||ir(r.duplicate_of))continue;let i=fa(r.title);if(i===null)continue;let a=t.get(i);a||(a=[],t.set(i,a)),a.some(s=>s.id===r.id)||a.push({id:r.id,title:r.title,parent:ir(r.parent)?r.parent.trim():null})}let n=[];for(let[r,i]of t){if(i.length<2)continue;let a=new Set(i.map(c=>c.id.toLowerCase())),s=i.filter(c=>c.parent===null||!a.has(c.parent.toLowerCase()));if(s.length<2)continue;let o=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:r,count:o.length,ids:o.map(c=>c.id),titles:o.map(c=>c.title)})}return n.sort((r,i)=>r.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 sr(e){let t=new Map;for(let r of e){let i=t.get(r.item_type);i||(i=new Map,t.set(r.item_type,i)),i.set(r.field,(i.get(r.field)??0)+1)}let n={};for(let r of[...t.keys()].sort((i,a)=>i.localeCompare(a))){let i=t.get(r),a={};for(let s of[...i.keys()].sort((o,c)=>o.localeCompare(c)))a[s]=i.get(s);n[r]=a}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var or=3;function cr(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function lr(e,t,n=or){let r=Number.isFinite(n)&&n>=1?Math.floor(n):or,i=new Map;for(let a of t){let s=cr(a);if(s.length===0)continue;let o=i.get(s);o?o.push(a):i.set(s,[a])}return e.map(a=>{let s=(i.get(cr(a))??[]).filter(o=>o!==a).sort((o,c)=>o.localeCompare(c));return s.length===0?{path:a,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:a,classification:"moved",candidates:s.slice(0,r),candidates_truncated:s.length>r}})}function dr(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 pa=/^[a-z][a-z0-9+.-]+:\/\//i;function Re(e){return pa.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 _a(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function ur(e){return`${e.item_id} ${e.link_kind}`}function mr(e,t){let n=new Map;for(let r of e){let i=n.get(r.path);i?(i.classification=_a(i.classification,r.classification),i.owners.set(ur(r),r)):n.set(r.path,{classification:r.classification,owners:new Map([[ur(r),r]])})}return[...n.entries()].sort(([r],[i])=>r.localeCompare(i)).map(([r,i])=>({path:r,classification:i.classification,items:[...i.owners.values()].map(a=>{let s=t(a.item_id);return{id:a.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:a.link_kind}}).sort((a,s)=>{let o=a.id.localeCompare(s.id);return o!==0?o:a.field.localeCompare(s.field)})}))}function ha(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function fr(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="${ha(r.title)}"`);return t}import{execFile as ga}from"node:child_process";import{realpath as ya}from"node:fs/promises";import pr from"node:path";import{promisify as wa}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 ka=wa(ga),va=32*1024*1024,ba=1e4,Sa=["search/eval-queries.json"];function gt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Ra(e){return`'${e.replaceAll("'","'\\''")}'`}async function Aa(e,t=ya){return t(e).catch(()=>pr.resolve(e))}async function _r(e){let t=await ke(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 Aa(e),r=gt(pr.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 i=tt.map(a=>`${r}/${gt(a)}`);try{let{stdout:a}=await ka("git",["ls-files","-z","--",...i.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:va,windowsHide:!0,timeout:ba}),s=new Set(Sa.map(l=>`${r}/${l}`)),o=[...new Set(a.split("\0").filter(l=>l.length>0&&!s.has(gt(l))))].sort((l,d)=>l.localeCompare(d)),c=i.filter(l=>o.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:o,tracked_path_count:o.length,remediation_command:o.length===0?null:`git rm --cached -r -- ${c.map(l=>Ra(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:r,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Ea from"node:fs/promises";import U from"node:path";import xa 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]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var Ca=["path","scope","note"],Ia=["pattern","glob","path","scope","note"],Ta=["path"],Oa=["from","to"],Fa=new Set(["note","scope"]);function gr(e){let t=e??"project";if(!He.includes(t))throw new h(`Invalid scope "${e}". Valid scopes: ${He.join(", ")} (default: project).`,_.USAGE);return t}function yr(e){return e.startsWith("```")||e.includes(`
13
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:fn(e)}function Pa(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||yr(n)||!n.includes(",")?[t]:_n(n)})}function Da(e,t){return e?Pa(e).map(n=>{let r=n.trim(),i=yr(r)?he(n,"--add"):{path:r};if(ge(i,"--add",Ca),!i.path)throw new h(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:i.path,scope:gr(i.scope),note:i.note?.trim()||void 0}}):[]}function Na(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--add-glob requires a glob pattern value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let r=he(n,"--add-glob");ge(r,"--add-glob",Ia);let i=r.pattern?.trim()||r.glob?.trim()||r.path?.trim();if(!i)throw new h("--add-glob key/value form requires pattern=<glob>",_.USAGE);return{pattern:i,scope:gr(r.scope),note:r.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Ma(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new h("--remove requires a path value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let r=he(n,"--remove"),i=Object.keys(r).filter(a=>Fa.has(a.toLowerCase()));if(i.length>0)throw new h(`--remove identifies a linked artifact by path only and does not accept ${i.map(a=>`"${a}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,_.USAGE);if(ge(r,"--remove",Ta),!r.path)throw new h("--remove key/value form requires path=<value>",_.USAGE);return r.path}return n}):[]}function La(e){return e?e.map(t=>{let n=he(t,"--migrate");ge(n,"--migrate",Oa);let r=n.from?.trim(),i=n.to?.trim();if(!r||!i)throw new h("--migrate requires from=<value> and to=<value>",_.USAGE);return{from:r,to:i}}):[]}function yt(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 Q(e){return e.split(U.sep).join("/")}function wt(e,t,n=process.cwd()){let r=e.trim();if(Re(r))return r;if(U.isAbsolute(r)||/^[A-Za-z]:[\\/]/.test(r))return Q(r.replaceAll("\\",U.sep));let i=U.relative(t,n);return i.startsWith(`..${U.sep}`)||i===".."||U.isAbsolute(i)?Q(U.normalize(r)):Q(U.relative(t,U.resolve(n,r)))}async function $a(e,t=process.cwd(),n=process.cwd()){let r=[];for(let i of e){let a=U.isAbsolute(i.pattern),s=await xa(i.pattern,{cwd:n,absolute:a,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),o=[...new Set(s.map(c=>wt(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of o)r.push({path:c,scope:i.scope,note:i.note})}return r}function ja(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)",_.USAGE);let r=t.trim();return r.length===0?e:e.map(i=>i.note===void 0?{...i,note:r}:i)}function Ba(e){return`${e.path}::${e.scope}`}function kt(e){return[...e].sort((t,n)=>{let r=t.path.localeCompare(n.path);return r!==0?r:t.scope.localeCompare(n.scope)})}function vt(e){return[...new Map(e.map(t=>[Ba(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Ua(e,t=process.cwd()){let n=[...new Set(e)].sort((o,c)=>o.localeCompare(c)),r=[],i=[],a=[],s=[];for(let o of n){if(Re(o)){s.push(o.trim());continue}let c=U.isAbsolute(o)?o:U.resolve(t,o);try{(await Ea.stat(c)).isFile()?r.push(o):a.push(o)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){i.push(o);continue}a.push(o)}}return{checked:n.length,existing_files:r,missing_paths:i,non_file_paths:a,remote_references:s}}function za(e,t,n,r){let i=0;for(let s=0;s<e.length;s+=1){let o=yt(e[s].path,r);o!==e[s].path&&(e[s]={...e[s],path:o},i+=1)}return{adds:t.map(s=>{let o=yt(s.path,r);return o!==s.path&&(i+=1),{...s,path:o}}),removes:n.map(s=>yt(s,r)),count:i}}function Ga(e,t,n,r){for(let a of t)e.some(s=>s.path===a.path&&s.scope===a.scope)||e.push(a);if(n.length>0)for(let a=e.length-1;a>=0;a-=1)n.includes(e[a].path)&&e.splice(a,1);let i=vt(e);return r?i:kt(i)}async function hr(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?await Ua(t,e.workspaceRoot):void 0}}async function Le(e,t,n,r){let{metadataKey:i}=r,a=pn(),s=j(process.cwd(),n.path),o=_e(s),c=process.cwd();if(!await N(B(s)))throw new h(`Tracker is not initialized at ${s}. Run pm init first.`,_.NOT_FOUND);let l=await L(s),d=H(l,Y()),u=await a.resolveList(t.add,"--add"),m=await a.resolveList(t.addGlob,"--add-glob"),f=await a.resolveList(t.remove,"--remove"),k=await a.resolveList(t.migrate,"--migrate"),p=Da(u,r.bareNoun).map(D=>({...D,path:wt(D.path,o,c)})),g=Na(m),y=await $a(g,o,c),S=ja([...p,...y],t.note,p.length>0||g.length>0),A=Ma(f).map(D=>wt(D,o,c)),E=La(k);if(!(S.length>0||A.length>0||E.length>0)){let D=await Ce(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!D)throw new h(`Item ${e} not found`,_.NOT_FOUND);let I=(await Ie(D,{schema:l.schema})).document.metadata[i]??[];return hr({id:D.id,artifacts:I,changed:!1,options:t,workspaceRoot:o})}let K=le(t.author,l.author_default),W=await Te({pmRoot:s,settings:l,id:e,op:r.op,author:K,message:t.message,force:t.force,skipNoop:!0,mutate(D){let v=D.metadata,I=v[i]??[],ce=[...I],ae=za(ce,S,A,E),qe=Ga(ce,ae.adds,ae.removes,r.supportsAppendStable&&t.appendStable===!0);qe.length>0?v[i]=qe:delete v[i];let Dt=!Wt(I,qe);return{changedFields:Dt?[i]:[],warnings:Dt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),R=W.item[i]??[],P=W.warnings.find(D=>D.startsWith("path_migrations_applied:")),q=P?Number(P.slice(24)):0;return hr({id:W.item.id,artifacts:R,changed:W.changedFields.includes(i),migrationsApplied:q,options:t,workspaceRoot:o})}function $e(e,t){let n={};for(let[r,i]of Object.entries(e))n[r==="artifacts"?t: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]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function wr(e,t,n){let r=await Le(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return $e(r,"docs")}import kr from"node:fs/promises";import z 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]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var Wa=32768;function bt(e){return Q(z.normalize(e))}async function je(e){try{return await kr.realpath(e)}catch{return z.resolve(e)}}function fe(e,t){let n=z.isAbsolute(e.path)?z.resolve(e.path):z.resolve(t,e.path);return`${bt(n)}::${e.scope}`}function Be(e,t,n){if(typeof e=="string"){let r=e.trim();r.length>0&&n.push({field:t,value:r});return}if(Array.isArray(e)){e.forEach((r,i)=>Be(r,`${t}[${i}]`,n));return}if(typeof e=="object"&&e!==null)for(let[r,i]of Object.entries(e))Be(i,t?`${t}.${r}`:r,n)}function qa(e){let t=[];return Be(e.metadata,"metadata",t),Be(e.body,"body",t),t}function Ha(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Va(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,r=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let i of e){let a=new Set,s=i.value.slice(0,Wa);for(let[o,c]of[[n,i.value],[r,s]]){o.lastIndex=0;for(let l of c.matchAll(o)){let d=Ha(l[0]);!d||a.has(d)||(a.add(d),t.push({field:i.field,value:d}))}}}return t}async function Ka(e,t,n=t){let r=z.isAbsolute(e)?z.resolve(e):z.resolve(n,e),i;try{i=await kr.stat(r)}catch{return}if(!i.isFile())return;let[a,s]=await Promise.all([je(t),je(r)]);if(Ve(a,s)){let o=z.relative(a,s);return!o||o.startsWith("..")||z.isAbsolute(o)?void 0:{path:bt(o),scope:"project"}}return{path:bt(r),scope:"global"}}async function Ya(e,t,n=t){let r=new Set((e.metadata.files??[]).map(c=>fe(c,t))),i=new Map,a=Va(qa(e)),s=new Map;await Promise.all([...new Set(a.map(c=>c.value))].map(async c=>{s.set(c,await Ka(c,t,n))}));let o=a.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:l}of o){if(!l)continue;let d=fe(l,t),u=i.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,i.set(d,u)}return[...i.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:r.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function vr(e,t,n){let r=await Le(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return $e(r,"files")}async function Ja(e,t){let n=await je(t),r=await Promise.all(e.map(async a=>{let s=a.trim();if(!s)throw new h("Files lookup paths must not be empty.",_.USAGE);if(!z.isAbsolute(s))return Q(s);let o=await je(s);return Ve(n,o)?Q(z.relative(n,o)):Q(o)})),i=[...new Set(r)].sort((a,s)=>a.localeCompare(s));if(i.length===0)throw new h("Files lookup requires at least one path.",_.USAGE);return i}function Xa(e){for(let[r,i]of[["limit",e.limit],["offset",e.offset]])if(i!==void 0&&(!Number.isInteger(i)||i<0))throw new h(`Files lookup ${r} must be a non-negative integer.`,_.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function br(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function Za(e){if([e.strictRead,e.noTruncate,Yt()].includes(!0))return null;let t=await dn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?ln({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Qa(e){let t=[],r=(await un(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(s=>({item:s,files:(s.files??[]).filter(o=>e.paths.includes(Q(o.path))&&(e.scope===void 0||o.scope===e.scope)).sort((o,c)=>{let l=o.path.localeCompare(c.path);return l===0?o.scope.localeCompare(c.scope):l})})).filter(s=>s.files.length>0).sort((s,o)=>{let c=s.item.priority-o.item.priority;if(c!==0)return c;let l=o.item.updated_at.localeCompare(s.item.updated_at);return l===0?s.item.id.localeCompare(o.item.id):l}),i=t.filter(s=>/^item_list_(?:item|directory)_read_failed:/u.test(s));if(e.strictRead&&i.length>0)throw new h(`Files lookup could not read every item: ${i.join("; ")}`,_.GENERIC_FAILURE);let a=r.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:r.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<r.length,truncated:e.offset+a.length<r.length,completeness:{status:i.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(s=>({item:br(s.item),files:s.files}))}}async function dd(e,t){let n=j(process.cwd(),t.path),r=_e(n);if(!await N(B(n)))throw new h(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let i=await Ja(e.paths,r),a=await L(n),s=H(a,Y()),{offset:o,limit:c}=Xa(e),l=await Za({pmRoot:n,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0});return l?{paths:i,total:l.total,count:l.matches.length,offset:o,limit:c,has_more:o+l.matches.length<l.total,truncated:o+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:br(d.item),files:d.files}))}:Qa({pmRoot:n,settings:a,typeToFolder:s.type_to_folder,paths:i,scope:e.scope,limit:c,offset:o,strictRead:e.strictRead===!0})}async function ud(e,t,n){let r=j(process.cwd(),n.path),i=_e(r);if(!await N(B(r)))throw new h(`Tracker is not initialized at ${r}. Run pm init first.`,_.NOT_FOUND);let a=await L(r),s=H(a,Y()),o=await Ce(r,e,a.id_prefix,a.item_format,s.type_to_folder);if(!o)throw new h(`Item ${e} not found`,_.NOT_FOUND);let c=await Ie(o,{schema:a.schema}),l=await Ya(c.document,i,process.cwd()),d=l.filter(R=>R.status==="addable"),u=l.filter(R=>R.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let R=c.document.metadata.files??[];return{id:o.id,files:R,changed:!1,apply:m,count:R.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let k=le(t.author,a.author_default),p=d.map(R=>({path:R.path,scope:R.scope,note:f})),g=[],y=new Set,S=await Te({pmRoot:r,settings:a,id:e,op:"files_discover",author:k,message:t.message??"Discover referenced file links",force:t.force,mutate(R){let P=[...R.metadata.files??[]],q=new Set(P.map(I=>fe(I,i)));g=[],y.clear();for(let[I,ce]of p.entries()){let ae=fe(ce,i);q.has(ae)||(P.push(ce),q.add(ae),g.push(ce),y.add(I))}let D=vt(P),v=t.appendStable?D:kt(D);return v.length>0?R.metadata.files=v:delete R.metadata.files,{changedFields:g.length>0?["files"]:[],warnings:g.length!==p.length?[`files_discover_skipped_existing:${p.length-g.length}`]:[]}}}),A=S.item.files??[],E=new Set(g.map(R=>fe(R,i))),x=A.filter(R=>E.has(fe(R,i))),K=d.filter((R,P)=>!y.has(P)),W=[...u,...K];return{id:S.item.id,files:A,changed:x.length>0,apply:!0,count:A.length,candidate_count:l.length,addable_count:d.length,added_count:x.length,skipped_existing_count:W.length,candidates:l,added:x,skipped_existing:W}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var es=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),St=new Set(["--pm-path","--path","--author"]),ts={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"])},ns=new Set(["-p","--package"]),rs=new Set(["-c","--call"]),is=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),as=new Set(["-C","--prefix","--userconfig","--cache"]),fd=new Set(["--cwd"]),pd=new Set(["--cwd"]),ss=new Set(["exec","x"]),_d=new Set(["run","run-script"]),hd=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function os(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function cs(e){let t=ls(e.split(" ").filter(a=>a.length>0));if(t.length===0)return null;let[n,...r]=t;if(Sr(n)||Rr(n))return r;if(n==="node"&&r[0]&&Rr(r[0]))return r.slice(1);let i=n==="npx"||n==="bunx"?Rt(r):n==="pnpm"?ms(r):n==="npm"?fs(r):null;return i&&(Sr(i.command)||us(i.command))?i.args:null}var Ar=(e,t="pm")=>{let n=t.trim().toLowerCase(),r=n.length;for(;r>0&&n[r-1]==="-";)r-=1;let i=n.slice(0,r);if(i.length===0)return[];let a=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let o of os(a)){let c=cs(o),l=c?ps(c):null,d=l&&es.has(l.subcommand)?_s(l.remaining,ts[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${i}-`)===!0&&u.length>i.length+1&&s.add(d)}return[...s].sort((o,c)=>o.localeCompare(c))};function ls(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 gd(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(St.has(n)){t+=2;continue}t+=1;continue}return n}}function Sr(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function ds(e){let t=e.trim();if(!t.startsWith("@")){let i=t.indexOf("@");return i===-1?t:t.slice(0,i)}let n=t.indexOf("/");if(n===-1)return t;let r=t.indexOf("@",n+1);return r===-1?t:t.slice(0,r)}function us(e){let t=ds(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Rr(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function Rt(e){let t=0;for(;t<e.length;){let r=e[t];if(r==="--"){t+=1;break}if(!r.startsWith("-"))break;let i=/^(?:-c|--call)=(.*)$/.exec(r);if(i){let a=i[1];return a?{command:a,args:e.slice(t+1)}:null}if(rs.has(r)){t+=1;break}t+=ns.has(r)&&!r.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Er(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 ms(e){let t=Er(e,is);return t?.subcommand!=="dlx"?null:Rt(t.args)}function fs(e){let t=Er(e,as);return!t||!ss.has(t.subcommand)?null:Rt(t.args)}function ps(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(St.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function _s(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("=")&&(St.has(r)||t.has(r))&&(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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var ws=["src","tests","docs"],ks=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],vs=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),bs=["resolution","expected_result","actual_result"],Ss=["default","tracked-all","tracked-all-strict"],xr=["core","strict","custom"],ze=["off","warn","error"];var Et=["author","acceptance_criteria","estimated_minutes","close_reason"],Fr=[...Et,"reviewer","risk","confidence","sprint","release"],Tt=Array.from(new Set(Fr)),Rs={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"},As={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"},Es={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"},xs={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"},Cs={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"},Is=32*1024*1024,Ts=1e4,Pr=40,te=5,Os=4096,Fs=255,Ps=ys(gs);function Dr(e){let t={};for(let[n,r]of Object.entries(e))Array.isArray(r)||(t[n]=typeof r=="object"&&r!==null?Dr(r):r);return t}function Ds(e){return{...e,checks:e.checks.map(t=>({...t,details:Dr(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 oe(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Cr(e){return oe(e).replace(/\/+$/,"")}function G(e){let t=M(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function We(e,t){return en(e,t)??e}function Ae(e,t){return t.terminal_statuses.has(We(e,t))}function re(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ue(e,t){return e.length!==t.length?!1:e.every((n,r)=>n===t[r])}function Ns(e){let t=re(Mt),n={blocked_reason:re(Ee.blocked_reason),resolution:re(Ee.resolution),actual_result:re(Ee.actual_result)},r=re(e.validation.lifecycle_stale_blocker_reason_patterns),i={blocked_reason:re(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:re(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:re(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:r,stale_blocker_reason_pattern_source:Ue(r,t)?"default":"settings",closure_like_metadata_field_patterns:i,closure_like_metadata_field_pattern_sources:{blocked_reason:Ue(i.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Ue(i.resolution,n.resolution)?"default":"settings",actual_result:Ue(i.actual_result,n.actual_result)?"default":"settings"}}}function Nr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(xr.includes(t))return t;throw new h(`Unknown --metadata-profile value "${e}". Supported values: ${xr.join(", ")}.`,_.USAGE)}function Mr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ze.includes(t))return t;throw new h(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${ze.join(", ")}.`,_.USAGE)}function Lr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(ze.includes(t))return t;throw new h(`Unknown --parent-cycle-severity value "${e}". Supported values: ${ze.join(", ")}.`,_.USAGE)}function Ms(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Rs[n]).filter(n=>n!==void 0).sort((n,r)=>n.localeCompare(r))}function Ls(e,t,n){let r=Ms(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Et],configured_custom_fields:r,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Fr],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:[...Et],configured_custom_fields:r,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var $s=new Set(["acceptance_criteria","estimated_minutes"]);function $r(e,t,n,r){return!r&&$s.has(t)&&Ae(e.status,n)?!1:t==="author"?!M(e.author):t==="acceptance_criteria"?!M(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?We(e.status,n)===n.close_status&&!M(e.close_reason):t==="reviewer"?!M(e.reviewer):t==="risk"?!M(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!M(e.confidence):t==="sprint"?!M(e.sprint):!M(e.release)}function jr(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: ${Ss.join(", ")}.`,_.USAGE)}function Br(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $.resolve(t);let n=$.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $.dirname($.dirname(n));let i=$.resolve(process.cwd()),a=Ir(n),s=Ir(i),o=$.relative(a,s);return o.length===0||!o.startsWith("..")&&!$.isAbsolute(o)?n:i}function Ir(e){try{return hs.native(e)}catch{return $.resolve(e)}}function Ur(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function Ot(e,t,n){let r=t.length>0?$.join(e,t):e,i;try{i=await It.readdir(r,{withFileTypes:!0})}catch(a){if(Ur(a,["ENOENT"]))return;throw a}for(let a of i){if(a.name.startsWith("."))continue;let s=t.length>0?$.join(t,a.name):a.name;if(a.isDirectory()){if(vs.has(a.name))continue;await Ot(e,s,n);continue}a.isFile()&&n.push(oe(s))}}async function xt(e){let t=[];for(let n of ws)await Ot(e,n,t);for(let n of ks){let r=$.join(e,n);try{(await It.stat(r)).isFile()&&t.push(oe(n))}catch{}}return[...new Set(t)].sort((n,r)=>n.localeCompare(r))}async function zr(e){try{let{stdout:t}=await Ps("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Is,windowsHide:!0,timeout:Ts}),n=t.split("\0").map(r=>oe(r)).filter(r=>r.length>0);return[...new Set(n)].sort((r,i)=>r.localeCompare(i))}catch{return null}}function js(e,t){let n=new Set,r=Cr(Nt);r.length>0&&n.add(r);let i=Cr($.relative(t,e));return i.length>0&&!i.startsWith("..")&&n.add(i),[...n].sort((a,s)=>a.localeCompare(s))}function Tr(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Bs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let r=await zr(e);if(r)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length};let i=await xt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length}}let n=await xt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function F(e,t=te){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function ie(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=F(e,Pr);return{values:n.values,truncated:n.truncated,total:e.length}}var Us={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},zs={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function Gs(e){let t=e.missing_fields.map(n=>`${Us[n]} "${zs[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function Gr(e,t){let n=e.details?.missing_resolution_remediation_hints,r=Array.isArray(n)&&n.length>0,i=r?n.filter(s=>typeof s=="string"):Un(t);if(i.length===0)return;let a=r&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:i,...a?{fix_hints_truncated:!0}:{}}}function Wr(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 Ws="validate_metadata_duplicate_issue_codes";function qr(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:te,r=e.slice(0,n);return{rows:r.map(a=>({code:a.code,count:a.count,ids:a.ids,titles:a.titles,remediation_hint:`Items ${a.ids.join(", ")} share issue code "${a.code}"; rename or merge so each logical code maps to one item.`})),truncated:r.length<e.length,warnings:[`${Ws}:${e.length}`]}}function qs(){return Object.fromEntries(Tt.map(e=>[e,[]]))}function Hs(e,t,n){let r=qs();for(let i of e)for(let a of Tt)$r(i,a,t,n)&&r[a].push(i.id);return r}function Vs(e,t,n){let r=[...e.warnings];for(let i of e.required_fields){let a=t[i];a.length>0&&r.push(`${As[i]}:${a.length}`)}return r.push(...n),r}function Hr(e,t){let n={};for(let r of e.required_fields){let i=t[r],a=i?i.length:0,s=Es[r];a>0&&s&&(n[s]=a)}return n}function Vr(e,t,n){let r=[];for(let i of e.required_fields){let a=t[i];if(a)for(let s of a){let o=n.get(s)?.type,c=typeof o=="string"&&o.length>0?o:"Unknown";r.push({item_type:c,field:i})}}return r}function Ks(e,t,n,r){for(let i of t.required_fields){let a=n[i];if(!a||a.length===0)continue;let s=xs[i],o=Cs[i];if(!s||!o)continue;let c=F(a,r?a.length:te);e[s]=c.values,e[o]=c.truncated}}function Kr(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let r=t.close_reason;return r?r.map(i=>({id:i,resolution:M(n.get(i)?.resolution)})):[]}function Yr(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let r=t.estimated_minutes;return r?r.map(i=>({id:i,type:M(n.get(i)?.type)})):[]}function Ys(e,t,n,r){let i=new Map(e.map(g=>[g.id,g])),a=t.profile==="strict",s=Hs(e,n,a),o=ar(e),c=qr(o,r),l=Vs(t,s,c.warnings),d=Hr(t,s),u=Vr(t,s,i),m=sr(u),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:[...Tt],counts:d,missing_by_type:m,duplicate_issue_codes_count:o.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),Ks(f,t,s,r);let k=Kr(t,s,i),p=Yr(t,s,i);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:k,estimateBackfillRows:p}}function Js(e,t,n){let r=new Set(t.terminal_done_statuses);r.add(t.close_status);let i=e.filter(m=>r.has(We(m.status,t))),a=[],s=[];for(let m of i){let f=bs.filter(k=>!M(m[k]));f.length!==0&&(a.push({id:m.id,missing_fields:f}),s.push({id:m.id,missing_fields:f,close_reason:M(m.close_reason)}))}let o=a.length>0?[`validate_resolution_missing_fields:${a.length}`]:[],c=n?Number.POSITIVE_INFINITY:te,l=F(a.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=a.map(m=>Gs(m)),u=F(d,c);return{check:{name:"resolution",status:o.length===0?"ok":"warn",details:{checked_closed_items:i.length,missing_resolution_items:a.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:o,resolutionBackfillRows:s}}function Jr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Xr(e,t="pm",n=Ke()){let r=new Set(e.map(a=>a.id)),i=[...e].sort((a,s)=>a.id.localeCompare(s.id));return new Map(i.map(a=>{let s=new Set,o=G(a.blocked_by);o&&r.has(o)&&s.add(o),(a.dependencies??[]).filter(l=>{let d=G(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>G(l.id)).filter(l=>l!==void 0&&r.has(l)).forEach(l=>s.add(l));let c=G(a.definition_of_ready);return Qr(c??"",t).filter(l=>r.has(l)).forEach(l=>s.add(l)),[a.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function Zr(e,t,n){let r=hn(e,n?d=>Ae(d,n):void 0),i=r.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),a=r.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:te,o=F(i,s),c=F(a,s),l=F(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:i.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:i.length+a.length,active_dangling_reference_count:i.length,dangling_reference_rows:o.values,dangling_reference_rows_truncated:o.truncated,legacy_terminal_dangling_reference_count:a.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:i.length>0?[`validate_dangling_dependency_references:${i.length}`]:[]}}function Qr(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),r=new RegExp(`(?:^|[^a-z0-9-])(${Jr(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(r)].map(i=>i[1].toLowerCase()))].sort((i,a)=>i.localeCompare(a))}function Ft(e){let t=0,n=new Map,r=new Map,i=[],a=new Set,s=[],o=d=>{n.set(d,t),r.set(d,t),t+=1,i.push(d),a.add(d);for(let m of e.get(d)??[])n.has(m)?a.has(m)&&r.set(d,Math.min(r.get(d),n.get(m))):(o(m),r.set(d,Math.min(r.get(d),r.get(m))));if(r.get(d)!==n.get(d))return;let u=[];for(;i.length>0;){let m=i.pop();if(a.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||o(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 Pt(e,t){let n=e[0];if(e.length===1)return[n,n];let r=new Set(e),i=[n],a=new Set([n]),s=o=>{let c=(t.get(o)??[]).filter(l=>r.has(l));for(let l of c){if(l===n&&i.length>1)return i.push(n),!0;if(!a.has(l)){if(a.add(l),i.push(l),s(l))return!0;i.pop(),a.delete(l)}}return!1};return s(n)?[...i]:[...e,n]}function ei(e,t="pm"){let n=Xr(e,t),r=Ft(n),i=[...new Set(r.flat())].sort((s,o)=>s.localeCompare(o)),a=r.map(s=>Pt(s,n).join("->"));return{cycle_count:r.length,cycle_item_ids:i,cycle_sample_paths:a}}function ti(e,t=Ke()){let n=new Map(e.map(a=>[a.id.toLowerCase(),a.id])),r=new Map(e.map(a=>[a.id,[]]));return[...e].sort((a,s)=>a.id.localeCompare(s.id)).forEach(a=>{let s=r.get(a.id),o=G(a.parent),c=o?n.get(o.toLowerCase()):void 0;c&&s.push(c),(a.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?r.get(u).push(a.id):s.push(u))})}),r.forEach((a,s)=>{r.set(s,[...new Set(a)].sort((o,c)=>o.localeCompare(c)))}),r}function ni(e){let t=ti(e),n=Ft(t),r=[...new Set(n.flat())].sort((a,s)=>a.localeCompare(s)),i=n.map(a=>Pt(a,t).join("->"));return{cycle_count:n.length,cycle_item_ids:r,cycle_sample_paths:i}}function ri(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 Ge(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function ii(e,t){let n=Ge(e).split("/").filter(Boolean),r=Ge(t).split("/").filter(Boolean),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i+=1;return i}function Xs(e,t){let n=Ge(t),r=Ge(e),i=t.endsWith("/")?t:`${t}/`,a=e.startsWith(i),s=n.length>0&&n===r,o=ii(e,t);return!a&&!s&&o===0?null:a?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:o+500,confidence:"same_directory"}:{score:o,confidence:"shared_directory"}}function Zs(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function Qs(e,t,n){let r=t==="docs_unowned"?"docs":"files",i;return n.flatMap(a=>(r==="docs"?a.docs??[]:a.files??[]).map(s=>({item:a,link:s}))).forEach(({item:a,link:s})=>{if(s.scope!=="project")return;let o=oe(s.path);if(o.length===0||o===e)return;let c=Xs(e,o);c!==null&&Zs(i,a,c.score)&&(i={item:a,score:c.score,confidence:c.confidence})}),i?{id:i.item.id,type:i.item.type,title:i.item.title,status:i.item.status,confidence:i.confidence}:null}function ai(e,t){return e.map(n=>{let r=ri(n),i=r==="docs_unowned"?"docs":"files",a=Qs(n,r,t),s=a?.id??"<id>";return{path:n,classification:r,owner_candidate:a,remediation_hint:`pm ${i} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function si(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function eo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,r])=>{let i=G(e[n]);return i?r.some(a=>i.toLowerCase().includes(a)):!1}).map(([n])=>n).sort((n,r)=>n.localeCompare(r))}function to(e,t,n,r,i){let a=G(t.parent),s=a?n.get(r.get(a.toLowerCase())??a):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Ae(s.status,i)}}function no(e,t,n,r){let i=G(e.blocked_by),a=G(e.blocked_reason),s=a?.toLowerCase(),o=We(e.status,n),c=[];return t.has(o)?(!i&&!a&&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):(i&&c.push("non_blocked_status_has_blocked_by"),a&&c.push("non_blocked_status_has_blocked_reason"),c)}function ro(e,t,n,r){let i=new Map(e.map(c=>[c.id,c])),a=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),o={activeItems:e.filter(c=>!Ae(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of o.activeItems){let l=eo(c,r);l.length>0&&o.closureLikeRows.push({id:c.id,fields:l});let d=G(c.parent),u=d?i.get(a.get(d.toLowerCase())??d):void 0;if(u&&Ae(u.status,n)&&(o.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),o.terminalParentFixRows.push(to(c,u,i,a,n))),t){let m=no(c,s,n,r);m.length>0&&o.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,k)=>f.localeCompare(k))})}}return o}function io(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 Or(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ao(e,t,n,r,i,a){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let o=Or("validate_lifecycle_dependency_cycles",n,i),c=Or("validate_hierarchy_parent_cycle",r,a);return[...s,...o?[o]:[],...c?[c]:[]]}function oi(e){let t=oe(e);return t.length>Os||t.split(/[\\/]/).some(n=>n.length>Fs)}async function so(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(oi(n))return!1;try{let r=await It.stat(n);return!r.isFile()&&!r.isDirectory()}catch(r){return Ur(r,["ENOENT","ENOTDIR"])}}async function oo(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},r=e.flatMap(i=>[...(i.files??[]).map(a=>({item:i,artifact:a,link_kind:"files"})),...(i.docs??[]).map(a=>({item:i,artifact:a,link_kind:"docs"}))]);for(let{item:i,artifact:a,link_kind:s}of r){if(a.scope!=="project")continue;if(Re(a.path)){n.remoteLinkedPaths.add(a.path.trim());continue}let o=oe(a.path);o.length!==0&&(n.linkedProjectPaths.add(o),await so(t,a.path)&&(n.missingLinkedPaths.push(o),n.staleLinkRows.push({item_id:i.id,path:o,link_kind:s})))}return n}function co(e,t,n,r,i,a){let s=r==="tracked-all-strict",o=s&&!i,c=i||s,l=c?[]:js(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Tr(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Tr(f,l)),m={};if(d.length>0){let f=ie(d,a);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:o,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function ci(e,t,n,r,i,a,s,o="pm"){let c=ro(e,t,i,a);io(c);let l=ei(c.activeItems,o),d=ni(e),u=ao(c,t,n,r,l.cycle_count,d.cycle_count),m=s?Number.POSITIVE_INFINITY:te,f=F(c.closureLikeRows.map(x=>`${x.id}:${x.fields.join(",")}`),m),k=F(c.terminalParentRows.map(x=>`${x.id}:${x.parent_id}:${x.parent_status}`),m),p=F(c.staleBlockerRows.map(x=>`${x.id}:${x.status}:${x.reasons.join(",")}`),m),g=F(l.cycle_item_ids,m),y=F(l.cycle_sample_paths,m),S=F(d.cycle_item_ids,m),A=F(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&r==="error"?"error":u.length===0?"ok":"warn",details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:k.values,active_terminal_parent_rows_truncated:k.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:p.values,stale_blocker_rows_truncated:p.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:g.values,dependency_cycle_item_ids_truncated:g.truncated,dependency_cycle_sample_paths:y.values,dependency_cycle_sample_paths_truncated:y.truncated,parent_cycle_severity_policy:r,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:S.values,parent_cycle_item_ids_truncated:S.truncated,parent_cycle_sample_paths:A.values,parent_cycle_sample_paths_truncated:A.truncated,stale_blocker_reason_patterns:[...a.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:a.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...a.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:a.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...a.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:a.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...a.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:a.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function li(e,t,n,r,i,a){let s=await oo(e,t),o=new Map(e.map(v=>[v.id,v])),c=[...new Set(s.missingLinkedPaths)].sort((v,I)=>v.localeCompare(I)),l=await Bs(t,r),d=co(l,n,t,r,i,a),u=d.candidateFiles.filter(v=>!s.linkedProjectPaths.has(v)),m=ai(u,e),f=lr(c,d.candidateFiles),k=new Map(f.map(v=>[v.path,v.classification])),p=f.filter(v=>v.classification==="moved").length,g=s.staleLinkRows.map(v=>({...v,classification:k.get(v.path)??"deleted"})).sort((v,I)=>v.item_id.localeCompare(I.item_id)||v.path.localeCompare(I.path)||v.link_kind.localeCompare(I.link_kind)),y=[];d.strictModeForcesPmInternals&&y.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&y.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&y.push(`validate_files_orphaned_paths:${u.length}`);let S=[...s.remoteLinkedPaths].sort((v,I)=>v.localeCompare(I)),A=ie(S,a),E=ie(c,a),x=ie(u,a),K=ie(m.map(v=>`${v.path}:${v.classification}:owner_candidate=${v.owner_candidate?.id??"unowned"}`),a),W=a?m:ie(si(m),!1).values,R=ie(dr(f),a),P=g.map(v=>({item_id:v.item_id,path:v.path,link_kind:v.link_kind,classification:v.classification})),q=mr(P,v=>{let I=o.get(v);return I?{type:I.type,title:I.title,status:I.status}:void 0}),D=a?q:ie(fr(q),!1).values;return{check:{name:"files",status:y.length===0?"ok":"warn",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:a?"full":"summary",file_list_summary_limit:Pr,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:i,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:S.length,remote_linked_paths_total:A.total,remote_linked_paths:A.values,remote_linked_paths_truncated:A.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:E.total,missing_linked_paths:E.values,missing_linked_paths_truncated:E.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:R.values,missing_linked_path_classifications_truncated:R.truncated,missing_linked_path_rows_count:q.length,missing_linked_path_rows:D,orphaned_paths_count:u.length,orphaned_paths_total:x.total,orphaned_paths:x.values,orphaned_paths_truncated:x.truncated,orphaned_path_classifications:K.values,orphaned_path_classifications_truncated:K.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:W}},warnings:y,staleLinkPruneRows:g}}async function lo(e,t,n){let{missingStreams:r,unreadableStreams:i,hashMismatches:a,chainMismatches:s,driftedItems:o}=await Yn(e,t),c=[];r.length>0&&c.push(`validate_history_drift_missing_streams:${r.length}`),i.length>0&&c.push(`validate_history_drift_unreadable_streams:${i.length}`),a.length>0&&c.push(`validate_history_drift_hash_mismatches:${a.length}`),s.length>0&&c.push(`validate_history_drift_chain_mismatches:${s.length}`);let l=n?Number.POSITIVE_INFINITY:te,d=F(o,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",details:{checked_items:t.length,drifted_items_count:o.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:r.length,unreadable_streams:i.length,hash_mismatches:a.length,chain_mismatches:s.length}}},warnings:c}}function uo(e,t,n){let r=n.trim().replaceAll(/\s+/g," "),i=r.length>120?`${r.slice(0,117)}...`:r;return`${e}:${t}:${i}`}function di(e,t,n){let r=new Set(e.map(g=>g.id.toLowerCase())),i=0,a=0,s=new Set,o=[],c=e.flatMap(g=>(g.tests??[]).map(y=>({item:g,linkedTest:y})));for(let{item:g,linkedTest:y}of c){if(typeof y.command!="string"||y.command.trim().length===0)continue;i+=1;let S=Ar(y.command,t);if(S.length!==0){a+=S.length;for(let A of S)s.add(A),r.has(A.toLowerCase())||o.push(uo(g.id,A,y.command))}}let l=[...new Set(o)].sort((g,y)=>g.localeCompare(y)),d=[...new Set(l.map(g=>g.split(":")[1]??""))].filter(g=>g.length>0).sort((g,y)=>g.localeCompare(y)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:te,f=F(l,m),k=F(d,m),p=F([...s].sort((g,y)=>g.localeCompare(y)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:i,referenced_pm_ids_count:a,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:p.values,unique_referenced_pm_ids_truncated:p.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:k.values,stale_pm_ids_truncated:k.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function mo(e,t){let n=Qt(e.map(c=>({ref:c.id,version:Zt(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 i=t?Number.POSITIVE_INFINITY:te,a=F(n.outdated,i),s=F(n.ahead,i);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:Xt,outdated_items_count:n.outdated.length,outdated_items:a.values,outdated_items_truncated:a.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:r}}var Ct="pm validate auto-fix";async function ui(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let r={message:Ct};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.",_.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 At(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function mi(e,t,n){let r=[],i=[],a=new Map;for(let s of e.filter(o=>At(o)===null))try{await ui(s,t,n),r.push(s)}catch(o){i.push({fix:s,error:o})}for(let s of e.filter(o=>At(o)!==null)){let o=At(s),c=a.get(o);c?c.push(s):a.set(o,[s])}for(let s of a.values()){let o=s[0];if(!o)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{o.kind==="prune_file_link"?await vr(o.item_id,{remove:c,message:Ct},t):await wr(o.item_id,{remove:c,message:Ct},t),r.push(...s)}catch(l){i.push(...s.map(d=>({fix:d,error:l})))}}return{applied:r,failed:i}}var ru={applyValidateFix:ui,applyValidateFixes:mi,attachValidateFixHints:Gr,buildCommandReferencesCheck:di,buildDependencyReferencesCheck:Zr,buildCloseReasonBackfillRows:Kr,buildFilesCheck:li,buildLifecycleCheck:ci,buildLifecycleDependencyGraph:Xr,buildLifecycleParentGraph:ti,buildEstimateBackfillRows:Yr,buildMetadataCounts:Hr,buildMissingFieldOccurrences:Vr,buildOrphanedPathRows:ai,classifyOrphanedPath:ri,collectDefaultProjectFileCandidates:xt,collectTrackedGitFileCandidates:zr,detectLifecycleDependencyCycles:ei,detectLifecycleParentCycles:ni,escapeRegExp:Jr,extractItemIds:Qr,findLifecycleDependencyCycleComponents:Ft,isMetadataFieldMissing:$r,linkedArtifactPathExceedsFilesystemLimits:oi,listFilesRecursive:Ot,resolveDependencyCycleSeverity:Mr,resolveParentCycleSeverity:Lr,resolveFileScanMode:jr,resolveLifecycleDependencyCycleSamplePath:Pt,resolveRequestedChecks:Wr,resolveValidateMetadataProfile:Nr,resolveWorkspaceRoot:Br,sharedDirectoryPrefixLength:ii,summarizeOrphanedPathRows:si,summarizeDuplicateIssueCodes:qr,toMeaningfulString:G};async function fo(e,t,n,r){let i=await Bn(e,new Set(t.map(m=>m.id)),n,{schema:r.schema,extensionFieldNames:Lt(Y())}),a=[];i.unreadable_item_files.length>0&&a.push(`validate_storage_unreadable_items:${i.unreadable_item_files.length}`),i.duplicate_item_ids.length>0&&a.push(`validate_storage_duplicate_item_ids:${i.duplicate_item_ids.length}`),i.history_conflict_marker_streams.length>0&&a.push(`validate_storage_history_conflict_markers:${i.history_conflict_marker_streams.length}`),i.history_unparseable_streams.length>0&&a.push(`validate_storage_unparseable_history:${i.history_unparseable_streams.length}`),i.resurrected_items.length>0&&a.push(`validate_storage_resurrected_items:${i.resurrected_items.length}`),i.unparseable_config_files.length>0&&a.push(`validate_storage_unparseable_config:${i.unparseable_config_files.length}`);let s=a.length,o=await _r(e);o.tracked_path_count>0&&a.push(`validate_storage_tracked_runtime_cache_files:${o.tracked_path_count}`);let c=await Cn(e,Fe(r));c.status==="drift"&&a.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await ke(e),d=l===null?null:await In(l);d!==null&&d.status!=="ok"&&a.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await ft(l);return u.length>0&&a.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:s>0?"error":a.length>0?"warn":"ok",details:{...i,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),tracked_runtime_cache:{tracker_relative_root:o.tracker_relative_root,tracked_paths:o.tracked_paths,tracked_path_count:o.tracked_path_count,remediation_command:o.remediation_command}}},warnings:a}}function ee(e,t,n){n&&Gr(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function po(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 i=Ys(e.items,e.metadataPolicy,e.statusRegistry,r);t.closeReasonBackfillRows=i.closeReasonBackfillRows,t.estimateBackfillRows=i.estimateBackfillRows,ee(t,i,n)}if(e.requestedChecks.has("resolution")){let i=Js(e.items,e.statusRegistry,r);t.resolutionBackfillRows=i.resolutionBackfillRows,ee(t,i,n)}if(e.requestedChecks.has("lifecycle")){let i=ci(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,r,e.settings.id_prefix);t.terminalParentFixRows=i.terminalParentFixRows,ee(t,i,n),ee(t,Zr(e.items,r,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let i=await li(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=i.staleLinkPruneRows,ee(t,i,n)}return e.requestedChecks.has("command_references")&&ee(t,di(e.items,e.settings.id_prefix,r),n),e.requestedChecks.has("history_drift")&&ee(t,await lo(e.pmRoot,e.items,r),n),e.requestedChecks.has("format_version")&&ee(t,mo(e.items,r),n),e.requestedChecks.has("storage_integrity")&&ee(t,await fo(e.pmRoot,e.items,H(e.settings,Y()).type_to_folder,e.settings),n),t}function _o(e,t,n){let r=[];return e.autoFix===!0&&(r.push(...Zn(t.closeReasonBackfillRows)),r.push(...Xn(t.resolutionBackfillRows)),r.push(...Qn(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),r.push(...er(t.terminalParentFixRows))),e.pruneMissing===!0&&r.push(...tr(t.staleLinkPruneRows)),r}async function ho(e,t,n,r,i,a){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=_o(e,t,n),{applicable:o,gated:c}=rr(s,r),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await mi(o,i,a);d.push(...m.applied.map(Se)),u.push(...m.failed.map(({fix:f,error:k})=>({...Se(f),error:k instanceof Error?k.message:String(k)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...r].sort((m,f)=>m.localeCompare(f)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Se),applied_fixes:d,gated_fixes:c.map(m=>({...Se(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function iu(e,t,n={}){Kt(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).",_.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new h("--fix-scope requires --auto-fix.",_.USAGE);let i=nr(e.fixScope),a=j(process.cwd(),t.path);if(!await N(B(a)))throw new h(`Tracker is not initialized at ${a}. Run pm init first.`,_.NOT_FOUND);let s=await L(a),o=Vt(s.schema),c=H(s,Y()),l=[],d=await mn(a,s.item_format,c.type_to_folder,l,s.schema),u=Wr(e);if(u.has("history_drift")){let P=await ut(a);P.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${P.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=Nr(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),k=Ls(f,m,s.validation.metadata_required_fields),p=Ns(s),g=Mr(e.dependencyCycleSeverity),y=Lr(e.parentCycleSeverity),S=jr(e.scanMode),A=Br(a),E=await po({requestedChecks:u,options:e,global:t,pmRoot:a,workspaceRoot:A,settings:s,items:d,statusRegistry:o,metadataPolicy:k,lifecyclePatternPolicy:p,dependencyCycleSeverity:g,parentCycleSeverity:y,fileScanMode:S,initialWarnings:[...new Set(l)]}),x=r?await ho(e,E,s,i,t,n):void 0,K=[...new Set(E.warnings)].sort((P,q)=>P.localeCompare(q)),R={ok:!E.checks.some(P=>P.status==="error"),has_warnings:K.length>0,checks:E.checks,warnings:K,...x!==void 0?{fixes:x}:{},generated_at:ne(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?R:{...Ds(R),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{vo as a,gi as b,yi as c,se as d,we as e,Si as f,ke as g,st as h,Fe as i,Cn as j,In as k,Bo as l,Uo as m,Ai as n,Yn as o,na as p,b as q,O as r,Ii as s,fc as t,pc as u,_c as v,Pn as w,hc as x,gc as y,yc as z,wc as A,kc as B,dt as C,vc as D,bc as E,lt as F,Sc as G,Rc as H,Dn as I,Ac as J,Li as K,Mn as L,Dc as M,ut as N,Ui as O,zi as P,Nc as Q,Gi as R,_r as S,qc as T,Hc as U,ft as V,Vc as W,Kc as X,Bn as Y,wr as Z,vr as _,dd as $,ud as aa,is as ba,as as ca,fd as da,pd as ea,_d as fa,hd as ga,os as ha,cs as ia,ls as ja,gd as ka,Sr as la,us as ma,Rr as na,Rt as oa,Er as pa,ms as qa,fs as ra,ps as sa,Ds as ta,ru as ua,iu as va};
14
- //# sourceMappingURL=chunk-CMDS3KYT.js.map
@@ -1,5 +0,0 @@
1
- import{T,U as ye,V as ge,W as _e,o as pe,va as we}from"./chunk-CMDS3KYT.js";import{e as fe,f as me,g as he}from"./chunk-YSAHYUXX.js";import{g as M}from"./chunk-U646T7Z6.js";import{Aa as j,Ba as I,K as re,L as S,La as x,M as P,ba as D,bb as ue,da as ne,ea as ie,eb as le,fa as oe,ga as se,k as F,la as ae,n as te,ta as O,wa as ce,xa as de,za as B}from"./chunk-HGNKPSCB.js";import{D as L,J as C,M as k,h as Z,p as E,q as ee}from"./chunk-FPDYXZBK.js";import{Y as y,Z as g,aa as w}from"./chunk-54EU2UVO.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="582576df-8dbe-5f93-890b-5d872669dfe8")}catch{}})();function U(e,t){let n=D(e);if(n)throw new g(`History merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(i)try{let d=JSON.parse(i);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");r.push(d)}catch{throw new g(`History merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}}return r}function v(e){return w({ts:e.ts,author:e.author,op:e.op,patch:e.patch,message:e.message??null})}function Ne(e,t){let n=Math.min(e.length,t.length),r=0;for(;r<n&&v(e[r])===v(t[r]);)r+=1;return r}function Re(e,t,n){U(e,"base");let r=U(t,"ours"),o=U(n,"theirs"),a=Ne(r,o);if(a===r.length&&a===o.length)return{merged:I(r),strategy:"identical",common_entries:a,entries_from_ours:0,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===o.length)return{merged:I(r),strategy:"fast_forward_ours",common_entries:a,entries_from_ours:r.length-a,entries_from_theirs:0,entries_total:r.length,reanchored:!1};if(a===r.length)return{merged:I(o),strategy:"fast_forward_theirs",common_entries:a,entries_from_ours:0,entries_from_theirs:o.length-a,entries_total:o.length,reanchored:!1};let i=r.slice(a),d=new Set(i.map(v)),c=o.slice(a).filter(u=>!d.has(v(u))),m=[...i,...c].sort((u,f)=>{let l=P(u.ts,f.ts);if(l!==0)return l;let h=d.has(v(u)),p=d.has(v(f));return h!==p?Number(p)-Number(h):v(u).localeCompare(v(f))}),s=j([...r.slice(0,a),...m]);return{merged:I(s.entries),strategy:"union_reanchor",common_entries:a,entries_from_ours:i.length,entries_from_theirs:c.length,entries_total:s.entries.length,reanchored:!0}}function J(e,t){let n=D(e);if(n)throw new g(`Relationship merge input (${t}) contains unresolved conflict markers at line ${n.line}. Merge drivers must receive clean per-side versions.`,y.GENERIC_FAILURE);let r=[];for(let[o,a]of e.split(/\r?\n/).entries()){let i=a.trim();if(!i)continue;let d;try{d=JSON.parse(i)}catch{throw new g(`Relationship merge input (${t}) contains invalid JSON at line ${o+1}.`,y.GENERIC_FAILURE)}if(typeof d!="object"||d===null||Array.isArray(d)||typeof d.eventId!="string"||typeof d.sequence!="number")throw new g(`Relationship merge input (${t}) line ${o+1} is not a relationship event (eventId + sequence required).`,y.GENERIC_FAILURE);r.push(d)}return r}function H(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
2
- `)}
3
- `}function $e(e){return e.map((t,n)=>({...t,sequence:n+1}))}function ve(e,t,n){J(e,"base");let r=J(t,"ours"),o=J(n,"theirs"),a=Math.min(r.length,o.length),i=0;for(;i<a&&r[i].eventId===o[i].eventId;)i+=1;if(i===r.length&&i===o.length)return{merged:H(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:H(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:H(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 d=r.slice(i),c=new Set(d.map(f=>f.eventId)),m=o.slice(i).filter(f=>!c.has(f.eventId)),s=[...d,...m].sort((f,l)=>{if(f.timestamp!==void 0&&l.timestamp!==void 0){let _=P(f.timestamp,l.timestamp);if(_!==0)return _}else{if(f.timestamp===void 0&&l.timestamp!==void 0)return 1;if(f.timestamp!==void 0)return-1}let h=c.has(f.eventId),p=c.has(l.eventId);return h!==p?Number(p)-Number(h):0}),u=$e([...r.slice(0,i),...s]);return{merged:H(u),strategy:"union_reanchor",common_entries:i,entries_from_ours:d.length,entries_from_theirs:m.length,entries_total:u.length,reanchored:!0}}var Pe=["tags","dependencies","comments","notes","learnings","files","tests","test_runs","docs","reminders","events"],De=["updated_at"];function b(e,t){return w(e??null)===w(t??null)}function je(e,t,n){let r=s=>Array.isArray(s)?s:[],o=new Set(r(e).map(s=>w(s))),a=r(t),i=new Set(a.map(s=>w(s))),d=r(n),c=new Set(d.map(s=>w(s))),m=a.filter(s=>{let u=w(s);return!o.has(u)||c.has(u)});for(let s of d){let u=w(s);!i.has(u)&&!o.has(u)&&m.push(s)}return m}function Me(e,t){return P(String(e),String(t))>=0?e:t}function q(e,t,n,r){return b(t,n)?{value:t,from_theirs:!1,conflict:!1}:b(e,t)?{value:n,from_theirs:!0,conflict:!1}:b(e,n)?{value:t,from_theirs:!1,conflict:!1}:{value:r==="theirs"?n:t,from_theirs:r==="theirs",conflict:!0}}function G(e){return{...e.metadata}}function z(e,t,n){try{return oe(ne(e,n),n)}catch(r){throw new g(`Item merge input (${t}) is not a readable item document: ${String(r)}`,y.GENERIC_FAILURE)}}function He(e,t,n,r){let o=new Set(Pe),a=new Set(De),i=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((c,m)=>c.localeCompare(m)),d={merged:{},conflictFields:[],fieldsFromTheirs:[],unionFields:[],conflictDecisions:[]};for(let c of i){let m=e[c],s=t[c],u=n[c];if(o.has(c)){let l=je(m,s,u);d.merged[c]=l,b(l,s)||d.unionFields.push(c);continue}if(a.has(c)){d.merged[c]=Me(s,u);continue}let f=q(m,s,u,r);f.value!==void 0&&(d.merged[c]=f.value),f.conflict?(d.conflictFields.push(c),d.conflictDecisions.push({field:c,base:m,ours:s,theirs:u,retained:f.value,discarded:r==="theirs"?s:u})):f.from_theirs&&d.fieldsFromTheirs.push(c)}return d}function Ie(e,t,n,r={}){let o=r.preferred??"ours",a=e.trim().length>0,i=z(t,"ours",r),d=z(n,"theirs",r),c=a?z(e,"base",r):i,m=a?G(c):{},s=G(i),u=G(d),{merged:f,conflictFields:l,fieldsFromTheirs:h,unionFields:p,conflictDecisions:_}=He(m,s,u,o),R=q(a?c.body:"",i.body,d.body,o);return R.conflict?(l.push("body"),_.push({field:"body",base:a?c.body:"",ours:i.body,theirs:d.body,retained:R.value,discarded:o==="theirs"?i.body:d.body})):R.from_theirs&&h.push("body"),{merged:ie({metadata:f,body:R.value},r),conflict_fields:l,fields_from_theirs:h,union_fields:p,conflict_decisions:_,preferred:o}}function V(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function W(e,t){let n=D(e);if(n)throw new g(`JSON merge input (${t}) contains unresolved conflict markers at line ${n.line}.`,y.GENERIC_FAILURE);if(e.trim().length!==0)try{return JSON.parse(e)}catch{throw new g(`JSON merge input (${t}) is not valid JSON.`,y.GENERIC_FAILURE)}}function Le(e,t,n){if(!Array.isArray(e)||!Array.isArray(t)||!Array.isArray(n))return null;let r=m=>{let s=new Map;for(let u of m){let f=w(u);s.set(f,(s.get(f)??0)+1)}return s},o=r(e),a=r(t),i=r(n);for(let[m,s]of o)if((a.get(m)??0)<s||(i.get(m)??0)<s)return null;let d=new Map(a),c=[];for(let m of n){let s=w(m),u=d.get(s)??0;u>0?d.set(s,u-1):c.push(m)}return{merged:[...t,...c],acceptedTheirs:c.length>0}}function Be(e,t,n,r,o,a,i){if(!V(t)||!V(n))return null;let d=V(e)?e:{},c={},m=[...new Set([...Object.keys(t),...Object.keys(n)])].sort((s,u)=>s.localeCompare(u));for(let s of m){let u=o.length>0?`${o}.${s}`:s,f=Ue(d,t,n,s,r,u,a,i);f!==void 0&&(c[s]=f)}return c}function be(e,t,n,r,o,a,i){if(b(t,n))return t;let d=Le(e,t,n);if(d!==null)return d.acceptedTheirs&&i.push(o),d.merged;let c=Be(e,t,n,r,o,a,i);if(c!==null)return c;let m=q(e,t,n,r);return m.conflict?a.push(o):m.from_theirs&&i.push(o),m.value}function Ue(e,t,n,r,o,a,i,d){let c=Object.prototype.hasOwnProperty.call(t,r),m=Object.prototype.hasOwnProperty.call(n,r),s=Object.prototype.hasOwnProperty.call(e,r);if(c&&m)return be(e[r],t[r],n[r],o,a,i,d);if(c){if(s&&b(e[r],t[r])){d.push(a);return}return s?(i.push(a),o==="theirs"?void 0:t[r]):t[r]}if(!(s&&b(e[r],n[r])))return s?(i.push(a),o==="theirs"?n[r]:void 0):(d.push(a),n[r])}function Ee(e,t,n,r={}){let o=r.preferred??"ours",a=W(e,"base"),i=W(t,"ours"),d=W(n,"theirs"),c=[],m=[],s=be(a,i,d,o,"",c,m);return{merged:`${JSON.stringify(s??null,null,2)}
4
- `,conflict_paths:c,paths_from_theirs:m,preferred:o}}import{readFile as Je,writeFile as Ge}from"node:fs/promises";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]="182fee45-4de8-502d-8aec-84b5b8e4aecb")}catch{}})();var Se=["item","history","relationship","json"];function Ve(e){let t=e.trim().toLowerCase();if(Se.includes(t))return t;throw new g(`Unknown merge artifact "${e}". Supported values: ${Se.join(", ")}.`,y.USAGE)}function We(e){if(e===void 0)return"ours";let t=e.trim().toLowerCase();if(t==="ours"||t==="theirs")return t;throw new g(`Unknown --prefer value "${e}". Supported values: ours, theirs.`,y.USAGE)}async function X(e,t){try{return await Je(e,"utf8")}catch{throw new g(`Cannot read merge ${t} file at ${e}.`,y.NOT_FOUND)}}async function qe(e){let t=C(process.cwd(),e.path);return await E(k(t))?x(t):null}function Xe(e,t){return e.endsWith(".md")?"json_markdown":e.endsWith(".toon")?"toon":t?.item_format??"toon"}async function It(e,t){let n=Ve(e.artifact),r=We(e.prefer),o=ze.resolve(e.outputPath??e.oursPath),[a,i,d]=await Promise.all([X(e.basePath,"base"),X(e.oursPath,"ours"),X(e.theirsPath,"theirs")]),c,m,s=[],u={};if(n==="history"){let l=Re(a,i,d);c=l.merged,u.history={strategy:l.strategy,common_entries:l.common_entries,entries_from_ours:l.entries_from_ours,entries_from_theirs:l.entries_from_theirs,entries_total:l.entries_total,reanchored:l.reanchored}}else if(n==="relationship"){let l=ve(a,i,d);c=l.merged,u.relationship={strategy:l.strategy,common_entries:l.common_entries,entries_from_ours:l.entries_from_ours,entries_from_theirs:l.entries_from_theirs,entries_total:l.entries_total,reanchored:l.reanchored}}else if(n==="item"){let l=await qe(t),h=Ie(a,i,d,{format:Xe(e.itemPath??o,l),schema:l?.schema,extensionFieldNames:Z(F()),preferred:r});c=h.merged,s.push(...h.conflict_fields),u.item={fields_from_theirs:h.fields_from_theirs,union_fields:h.union_fields},e.itemPath!==void 0&&(m={cwd:process.cwd(),itemPath:e.itemPath,preferred:r,fieldsFromTheirs:h.fields_from_theirs,unionFields:h.union_fields,decisions:h.conflict_decisions})}else{let l=Ee(a,i,d,{preferred:r});c=l.merged,s.push(...l.conflict_paths),u.json={paths_from_theirs:l.paths_from_theirs}}if(await Ge(o,c,"utf8"),m!==void 0){let l=await ye(m);l!==null&&(u.receipt=T(l))}let f=[];if(s.length>0){let l=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 ${s.join(", ")}; the ${r} value was kept. ${l} Review the merged file, re-apply the losing change if needed, then "git add" it.`)}return n==="history"&&u.history?.reanchored&&f.push('The merged history chain was re-anchored. Run "pm validate --check-history-drift" and "pm history-repair --all" after the merge to reconcile item state with merged history.'),{ok:s.length===0,artifact:n,output_path:o,preferred:r,conflicts:s,...u,guidance:f,generated_at:S()}}import Ce 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]="dd5ab9c3-bc6f-59f1-be89-ad0ab2abe7b5")}catch{}})();function Oe(e,t){return t==="body"?e.body:e.metadata[t]}function K(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 a=t.findIndex((i,d)=>!r.has(d)&&K(o,i));return a<0?!1:(r.add(a),!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)&&K(o,n[r]))}function Ae(e,t){let n=new Set(t),r=[];for(let o=e.length-1;o>=0&&n.size>0;o-=1){let a=e[o],i=new Set;for(let c of de(a.patch))i.add(M(c.path)),c.from&&i.add(M(c.from));let d=[...n].filter(c=>i.has(c));if(d.length!==0){for(let c of d)n.delete(c);r.push({index:o+1,ts:a.ts,author:a.author,op:a.op,fields:d.sort((c,m)=>c.localeCompare(m))})}}return r.reverse()}function Ke(e,t,n){let r=Ce.compare(t,n);if(r.length===0)return;let o=new Set;for(let h of r)o.add(M(h.path));let a=new Set([...o].filter(h=>K(Oe(t,h),Oe(n,h)))),i=new Set([...o].filter(h=>!a.has(h))),d=Ae(e,i),c=Ae(e,a),m=[...o].sort((h,p)=>h.localeCompare(p)),s=[...i].sort((h,p)=>h.localeCompare(p)),u=[...a].sort((h,p)=>h.localeCompare(p)),f=[...new Set(d.map(h=>h.author))].sort((h,p)=>h.localeCompare(p)),l=[...new Set(c.map(h=>h.author))].sort((h,p)=>h.localeCompare(p));return{reconciled_field_count:o.size,reconciled_fields:m,reverted_field_count:i.size,reverted_fields:s,discarded_events:d,discarded_authors:f,preserved_field_count:a.size,preserved_fields:u,preserved_events:c,preserved_authors:l,recovery_hint:d.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 Qe(e,t,n){let r=e.located?.itemPath??null,o=e.located?await ue(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:r,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let a=ce(o.document),i=n[n.length-1]?.after_hash;return{currentItemReplay:a,currentItemPath:r,matchedChainBefore:O(a)===i,currentItemRawBeforeLock:o.raw,loadedItem:o}}function Ye(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 Ze(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:S(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Ce.compare(e.finalReplay,e.currentItemReplay):[],before_hash:O(e.finalReplay),after_hash:O(n),message:e.message,...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function et(e,t){let n=[];return e||n.push("history_repair_no_changes"),t>0&&n.push(`history_repair_skipped_unresolvable_ops:${t}`),n}async function tt(e){return me({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})=>fe({historyPath:e.historyPath,nextHistoryRaw:I(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>te({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function Q(e,t,n){let r=C(process.cwd(),n.path);if(!await E(k(r)))throw new g(`Tracker is not initialized at ${r}. Run pm init first.`,y.NOT_FOUND);let o=await x(r),a=L(o,F()),i=await he(r,e,o,a.type_to_folder);if(!await E(i.historyPath))throw new g(`No history stream exists for ${i.id}.`,y.NOT_FOUND);let d=await ee(i.historyPath),c=await se(i.historyPath,i.id);if(c.length===0)throw new g(`No history entries exist for ${i.id}; nothing to repair.`,y.USAGE);let m=B(c),s=j(c),u=await Qe(i,o,c),f=s.finalDocument,l=u.currentItemReplay!==null&&O(f)!==O(u.currentItemReplay),h=l&&u.currentItemReplay?Ke(s.entries,f,u.currentItemReplay):void 0,p=[s.entriesRehashed>0,s.entriesPatchRepaired>0,l,t.forceAuditEntry===!0].some(Boolean),_=re(t.author,o.author_default),R=!!t.dryRun,A=Ye({message:t.message,entriesRehashed:s.entriesRehashed,entriesPatchRepaired:s.entriesPatchRepaired,reconcileNeeded:l}),{rewrittenEntries:Y,auditEntryAdded:Fe}=Ze({reanchorEntries:s.entries,changed:p,reconcileNeeded:l,currentItemReplay:u.currentItemReplay,finalReplay:f,author:_,message:A,auditOperation:t.auditOperation??"history_repair",auditContext:t.auditContext}),N=B(Y);if(!N.ok)throw new g(`history-repair produced an invalid rewritten chain (${N.errors.join(", ")}).`,y.GENERIC_FAILURE);let $=et(p,s.skippedOps);return h&&h.discarded_events.length>0&&($.push(`history_repair_reconcile_discards_events:${h.discarded_events.length}`),$.push(`history_repair_discarded_authors:${h.discarded_authors.join(",")}`)),p&&!R&&$.push(...await tt({pmRoot:r,subject:i,settings:o,typeRegistry:a,historyRawBeforeLock:d,currentItemRawBeforeLock:u.currentItemRawBeforeLock,author:_,force:t.force,loadedItem:u.loadedItem,historyPath:i.historyPath,rewrittenEntries:Y})),{id:i.id,dry_run:R,changed:p,history:{path:i.historyPath,entries_scanned:c.length,chain_drift_before:!m.ok,entries_rehashed:s.entriesRehashed,entries_patch_repaired:s.entriesPatchRepaired,converted_replace_to_add:s.convertedReplaceToAdd,skipped_ops:s.skippedOps,reconciled_with_item:l,audit_entry_added:Fe,verify_ok:N.ok,verify_errors:N.errors},item:{exists:u.currentItemPath!==null,path:u.currentItemPath,matched_chain_before:u.matchedChainBefore},...h?{reconciliation:h}:{},warnings:[...new Set($)].sort((xe,Te)=>xe.localeCompare(Te)),generated_at:S()}}function Ut(e,t){if(t&&e!==void 0)throw new g("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",y.USAGE);if(!t&&e===void 0)throw new g("history-repair: provide an item <id> or pass --all to repair every drifted stream.",y.USAGE)}async function ke(e,t){let n=C(process.cwd(),t.path);if(!await E(k(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,y.NOT_FOUND);let r=await x(n),o=L(r,F()),a=[],i=await le(n,r.item_format,o.type_to_folder,a,r.schema,{forceSourceScan:!0}),d=await pe(n,i),c=[],m=[],s={repaired:0,skipped_clean:0,failed:0};for(let u of d.driftedItems)try{let f=await Q(u,{...e,auditContext:e.auditContextById?.[u],auditContextById:void 0},t),l=f.changed?"repaired":"skipped_clean";s[l]+=1,m.push(...f.warnings.map(h=>`${u}:${h}`)),c.push({id:u,outcome:l,entries_rehashed:f.history.entries_rehashed,entries_patch_repaired:f.history.entries_patch_repaired,reconciled_with_item:f.history.reconciled_with_item,...f.reconciliation?{reconciliation:f.reconciliation}:{},warnings:f.warnings})}catch(f){s.failed+=1,c.push({id:u,outcome:"failed",error:f instanceof Error?f.message:String(f)})}return e.dryRun||await ae(n),{all:!0,dry_run:!!e.dryRun,scanned_streams:i.length,drifted_streams:d.driftedItems.length,streams:c,totals:s,warnings:[...new Set([...a,...m])].sort((u,f)=>u.localeCompare(f)),generated_at:S()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2f34565-7664-5612-815d-949b8b1d4f90")}catch{}})();async function Wt(e,t){let n=e.dryRun===!0,r=await ge(process.cwd()),o=r.reduce((p,_)=>((p[_.item_id]??=[]).push(_),p),{}),a=Object.fromEntries(Object.entries(o).map(([p,_])=>[p,{merge:{receipts:_.map(T)}}])),i=await ke({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:a},t),d=new Set(i.streams.map(p=>p.id)),c=Object.keys(o).filter(p=>!d.has(p));(await Promise.allSettled(c.map(p=>Q(p,{dryRun:n,author:e.author??t.author,message:e.message??"record field-aware branch merge provenance",force:e.force,auditOperation:"merge_reconcile",auditContext:a[p],forceAuditEntry:!0},t)))).forEach((p,_)=>{let R=c[_];if(p.status==="fulfilled"){let A=p.value.changed?"repaired":"skipped_clean";i.streams.push({id:R,outcome:A,entries_rehashed:p.value.history.entries_rehashed,entries_patch_repaired:p.value.history.entries_patch_repaired,reconciled_with_item:p.value.history.reconciled_with_item,warnings:p.value.warnings}),i.totals[A]+=1}else i.streams.push({id:R,outcome:"failed",error:p.reason instanceof Error?p.reason.message:String(p.reason)}),i.totals.failed+=1});let s=0;!n&&i.totals.failed===0&&(await Promise.all(r.map(p=>_e(process.cwd(),p))),s=r.length);let u=await we({checkHistoryDrift:!0,checkStorageIntegrity:!0},t),f=u.checks.every(p=>p.status==="ok"),l=i.totals.failed===0&&f,h=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."]:l?["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:l,dry_run:n,repair:i,receipts:{pending_before:r.length,reconciled:s,summaries:r.map(T)},validation:u,guidance:h,generated_at:u.generated_at}}export{Re as a,ve as b,Pe as c,De as d,Ie as e,Ee as f,Se as g,It as h,Q as i,Ut as j,ke as k,Wt as l};
5
- //# sourceMappingURL=chunk-F5B3HBEZ.js.map