@unbrained/pm-cli 2026.11.23 → 2026.11.24

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 (170) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/main.js +5 -5
  3. package/dist/cli/register-annotations.js +1 -1
  4. package/dist/cli/runtime/invocation-options.js +1 -1
  5. package/dist/cli-bundle/bundle-manifest.json +1 -1
  6. package/dist/cli-bundle/chunks/{chunk-2UQU7HRR.js → chunk-23K6DQQY.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-O7JHS64G.js → chunk-37UDIJ2K.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-7IROAPWI.js +3 -0
  9. package/dist/cli-bundle/chunks/{chunk-KZHIBEJL.js → chunk-7VRFEURZ.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-7X253M6Z.js +3 -0
  11. package/dist/cli-bundle/chunks/chunk-AWB5KBJS.js +2 -0
  12. package/dist/cli-bundle/chunks/chunk-DQDRA3SW.js +2 -0
  13. package/dist/cli-bundle/chunks/chunk-FXJYZBWV.js +113 -0
  14. package/dist/cli-bundle/chunks/{chunk-BSRIVYTM.js → chunk-HNKK2UG6.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-HZZLSBIJ.js +2 -0
  16. package/dist/cli-bundle/chunks/chunk-I2OJ5B4A.js +2 -0
  17. package/dist/cli-bundle/chunks/chunk-I3BFCKZR.js +2 -0
  18. package/dist/cli-bundle/chunks/{chunk-ENKXRSFZ.js → chunk-MXUSC5RS.js} +31 -31
  19. package/dist/cli-bundle/chunks/chunk-PLIUU37C.js +3 -0
  20. package/dist/cli-bundle/chunks/chunk-PQUBVRV5.js +2 -0
  21. package/dist/cli-bundle/chunks/chunk-PW7U7WCE.js +3 -0
  22. package/dist/cli-bundle/chunks/chunk-SSALO4DB.js +2 -0
  23. package/dist/cli-bundle/chunks/chunk-STOOTHZZ.js +2 -0
  24. package/dist/cli-bundle/chunks/chunk-TKRY22SO.js +2 -0
  25. package/dist/cli-bundle/chunks/{chunk-AEOHUSUI.js → chunk-TVIJ2VCU.js} +68 -68
  26. package/dist/cli-bundle/chunks/{chunk-F2Z6XLZB.js → chunk-VJSGUXGU.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-H7JEXRIN.js → chunk-WWTPNIC2.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-J2PDAVBC.js → chunk-XFADNMGD.js} +2 -2
  29. package/dist/cli-bundle/chunks/{chunk-TZY5MVJF.js → chunk-YOPTAIBD.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-CFWLQFJM.js → chunk-YW2HBHRO.js} +50 -51
  31. package/dist/cli-bundle/chunks/chunk-Z7MFVRDV.js +2 -0
  32. package/dist/cli-bundle/chunks/chunk-ZOX4SWRL.js +8 -0
  33. package/dist/cli-bundle/chunks/chunk-ZYCOM4MS.js +9 -0
  34. package/dist/cli-bundle/chunks/field-option-collisions-W66HSWMK.js +2 -0
  35. package/dist/cli-bundle/{focused-chunks/item-revision-YDACCDVY.js → chunks/item-revision-D3LSBNIR.js} +2 -2
  36. package/dist/cli-bundle/chunks/item-transaction-M6NTBYH3.js +2 -0
  37. package/dist/cli-bundle/chunks/mutation-actor-OKL3CQVX.js +2 -0
  38. package/dist/cli-bundle/chunks/mutation-admission-EKPEOZMF.js +2 -0
  39. package/dist/cli-bundle/chunks/{register-list-query-L4IBU64P.js → register-list-query-3LBV6CS2.js} +2 -2
  40. package/dist/cli-bundle/chunks/register-mutation-72AGTMNE.js +21 -0
  41. package/dist/cli-bundle/chunks/register-operations-XERFG2SH.js +2 -0
  42. package/dist/cli-bundle/chunks/register-setup-W22L34Z4.js +2 -0
  43. package/dist/cli-bundle/chunks/runtime-schema-JP2KBHBY.js +2 -0
  44. package/dist/cli-bundle/chunks/stage-T2LKWN7C.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-24VRBNKE.js +26 -0
  46. package/dist/cli-bundle/focused-chunks/chunk-3ELVASVA.js +2 -0
  47. package/dist/cli-bundle/focused-chunks/{chunk-XRS3VNC6.js → chunk-3GT4A3ZN.js} +23 -23
  48. package/dist/cli-bundle/focused-chunks/{chunk-IROZDIDX.js → chunk-3OCDKITJ.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/chunk-3Z7MCUJM.js +3 -0
  50. package/dist/cli-bundle/focused-chunks/chunk-46MP7IZN.js +5 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-OTMMOKPM.js → chunk-5LDBS6MS.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-ZHWPCVQL.js → chunk-B6BNHKUW.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/chunk-C7WHWI7K.js +3 -0
  54. package/dist/cli-bundle/focused-chunks/chunk-EUQGZPGO.js +2 -0
  55. package/dist/cli-bundle/focused-chunks/{chunk-UFTUNBMY.js → chunk-FDZPRJXJ.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/chunk-GXP7Q4XM.js +2 -0
  57. package/dist/cli-bundle/focused-chunks/chunk-HL47UQZJ.js +8 -0
  58. package/dist/cli-bundle/focused-chunks/chunk-LMFIAQ2V.js +2 -0
  59. package/dist/cli-bundle/focused-chunks/chunk-LMU7DDOA.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/chunk-OZOCEB2Q.js +8 -0
  61. package/dist/cli-bundle/focused-chunks/{chunk-NQTEE66P.js → chunk-Q2HY44LV.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/chunk-REFMQY47.js +2 -0
  63. package/dist/cli-bundle/focused-chunks/chunk-RIQUIHYU.js +3 -0
  64. package/dist/cli-bundle/focused-chunks/{chunk-QQIIMMFU.js → chunk-RLO2HCZT.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/chunk-SMMOZ3H3.js +100 -0
  66. package/dist/cli-bundle/focused-chunks/chunk-UVTUX54T.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-Y2ESLKCF.js → chunk-XDBHD4CY.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/chunk-YD66IRSL.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-Z7W2RQIB.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/field-option-collisions-UODPSV6W.js +2 -0
  71. package/dist/cli-bundle/focused-chunks/item-revision-QH7RNBX4.js +2 -0
  72. package/dist/cli-bundle/focused-chunks/item-transaction-ZO72OINF.js +2 -0
  73. package/dist/cli-bundle/focused-chunks/mutation-actor-PHVLKG4I.js +2 -0
  74. package/dist/cli-bundle/focused-chunks/mutation-admission-ZSG5OECH.js +2 -0
  75. package/dist/cli-bundle/focused-chunks/runtime-schema-6RQMIDTN.js +2 -0
  76. package/dist/cli-bundle/focused-chunks/stage-AQMKRVX4.js +2 -0
  77. package/dist/cli-bundle/main.js +26 -26
  78. package/dist/cli-bundle/sdk-authoring.js +1 -1
  79. package/dist/cli-bundle/sdk-contracts.js +4 -4
  80. package/dist/cli-bundle/sdk-core.js +1 -1
  81. package/dist/cli-bundle/sdk-governance.js +1 -1
  82. package/dist/cli-bundle/sdk-graph.js +1 -1
  83. package/dist/cli-bundle/sdk-merge.js +63 -63
  84. package/dist/cli-bundle/sdk-query.js +1 -1
  85. package/dist/cli-bundle/sdk-runtime.js +1 -1
  86. package/dist/cli-bundle/sdk-testing.js +1 -1
  87. package/dist/cli-bundle/sdk.js +11 -11
  88. package/dist/core/profile/profile-lint.d.ts +1 -1
  89. package/dist/core/profile/profile-lint.js +1 -1
  90. package/dist/core/schema/fields-file.js +2 -2
  91. package/dist/core/schema/runtime-field-values.js +1 -1
  92. package/dist/core/schema/runtime-schema.d.ts +2 -0
  93. package/dist/core/schema/runtime-schema.js +1 -1
  94. package/dist/sdk/extension/command-options.d.ts +26 -1
  95. package/dist/sdk/extension/command-options.js +1 -1
  96. package/dist/sdk/extension-command-context.js +2 -2
  97. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  98. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  99. package/dist/sdk/index.d.ts +1 -1
  100. package/dist/sdk/public-surface.json +1 -1
  101. package/dist/sdk/read-output-contracts.d.ts +11 -0
  102. package/dist/sdk/read-output-contracts.js +1 -1
  103. package/dist/sdk/schema/field-flag-spelling.d.ts +22 -0
  104. package/dist/sdk/schema/field-flag-spelling.js +2 -0
  105. package/dist/sdk/schema/field-option-collisions.js +1 -1
  106. package/docs/COMMANDS.md +1 -1
  107. package/docs/EXTENSIONS.md +1 -1
  108. package/docs/READ_OUTPUT_CONTRACTS.md +2 -0
  109. package/docs/SDK.md +20 -1
  110. package/docs/SDK_AUDITED_MUTATIONS.md +11 -0
  111. package/marketplace.json +1 -1
  112. package/package.json +1 -1
  113. package/packages/pm-beads/package.json +1 -1
  114. package/packages/pm-calendar/package.json +1 -1
  115. package/packages/pm-command-kit/package.json +1 -1
  116. package/packages/pm-digital-twin/package.json +1 -1
  117. package/packages/pm-governance-audit/package.json +1 -1
  118. package/packages/pm-guide-shell/package.json +1 -1
  119. package/packages/pm-kanban/package.json +1 -1
  120. package/packages/pm-lifecycle-hooks/package.json +1 -1
  121. package/packages/pm-linked-test-adapters/package.json +1 -1
  122. package/packages/pm-search-advanced/package.json +1 -1
  123. package/packages/pm-templates/package.json +1 -1
  124. package/packages/pm-todos/package.json +1 -1
  125. package/packages/pm-vcs/package.json +1 -1
  126. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  127. package/plugins/pm-claude/package.json +1 -1
  128. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  129. package/plugins/pm-codex/package.json +1 -1
  130. package/plugins/pm-codex/plugin.json +1 -1
  131. package/runtime-dependencies.json +1 -1
  132. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +0 -3
  133. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +0 -2
  134. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +0 -2
  135. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +0 -2
  136. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +0 -2
  137. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +0 -115
  138. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +0 -2
  139. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +0 -2
  140. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +0 -2
  141. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +0 -9
  142. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +0 -2
  143. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +0 -2
  144. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +0 -8
  145. package/dist/cli-bundle/chunks/item-revision-FMD4KWBB.js +0 -2
  146. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +0 -2
  147. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +0 -2
  148. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +0 -2
  149. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +0 -21
  150. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +0 -2
  151. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +0 -2
  152. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +0 -2
  153. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +0 -6
  154. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +0 -8
  156. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +0 -2
  157. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +0 -2
  158. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +0 -2
  159. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +0 -26
  160. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +0 -2
  161. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +0 -2
  162. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +0 -8
  164. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +0 -2
  165. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +0 -2
  166. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +0 -102
  167. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +0 -2
@@ -1,3 +1,3 @@
1
- import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-H7JEXRIN.js";import{lb as w,mb as R,nb as k}from"./chunk-KZHIBEJL.js";import{Cc as p,Fc as g,Gc as a,Xc as v}from"./chunk-OPJF254V.js";import{ca as O,od as B}from"./chunk-TZY5MVJF.js";import{gh as H,lh as u,mh as y,uj as I}from"./chunk-NGJ5ERBF.js";import{A as c,C as f}from"./chunk-YYT3MIRF.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
1
+ import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-WWTPNIC2.js";import{lb as w,mb as R,nb as k}from"./chunk-7VRFEURZ.js";import{Ka as v,pa as p,sa as g,ta as a}from"./chunk-ZYCOM4MS.js";import{ca as O,od as B}from"./chunk-YOPTAIBD.js";import{Af as y,Ih as I,uf as H,zf as u}from"./chunk-FXJYZBWV.js";import{A as c,C as f}from"./chunk-YYT3MIRF.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
2
2
  `)):u(t,o),"ok"in t&&!t.ok&&(process.exitCode=c.GENERIC_FAILURE)}function ee(r,e){r.command(e?"attest":"history-attest",{hidden:!e}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(F),r.command("restore",{hidden:!e}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(N),r.command(e?"redact":"history-redact",{hidden:!e}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",g).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",g).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=Array.isArray(t.literal)?t.literal:void 0,d=Array.isArray(t.regex)?t.regex:void 0,n=await E(o,{literal:m,regex:d,replacement:a(t,"replacement"),dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force},i);n.changed&&!n.dry_run&&await v(i,n),u(n,i),i.profile&&y(`profile:command=history-redact took_ms=${Date.now()-l}`)}),r.command(e?"repair":"history-repair",{hidden:!e}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--append-only","Bridge breaks; never rewrite entries").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=t.all===!0;R(o,m);let d={dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force,normalizeProvenance:t.normalizeProvenance===!0,salvageTail:t.salvageTail===!0,appendOnly:t.appendOnly===!0};if(m){let n=await k(d,i);u(n,i),n.totals.failed>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let n=await w(o,d,i);u(n,i)}i.profile&&y(`profile:command=history-repair took_ms=${Date.now()-l}`)}),r.command(e?"compact":"history-compact",{hidden:!e}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(D)}export{ee as a};
3
- //# sourceMappingURL=chunk-F2Z6XLZB.js.map
3
+ //# sourceMappingURL=chunk-VJSGUXGU.js.map
@@ -1,6 +1,6 @@
1
- import{$ as Io,B as Eo,C as bo,Eb as Mo,F as So,Gb as Fo,Ib as To,Jb as Po,Ka as Ao,N as xo,O as Ro,R as ko,S as kt,T as It,U as ze,e as ho,i as ge,ib as Co,j as po,jb as Ve,k as go,l as We,m as yo,mc as Ho,n as _o,q as wo,qc as Oo,r as vo}from"./chunk-KZHIBEJL.js";import{a as co,b as lo}from"./chunk-S32NGRQM.js";import{fb as fo,g as St,h as xt,j as Rt,k as uo,l as mo}from"./chunk-OPJF254V.js";import{c as bt,j as so,r as ao}from"./chunk-6MYJLOSG.js";import{a as pe,b as K}from"./chunk-NQ54T7T2.js";import{Ba as Oe,Cb as Xn,Db as Jn,Eb as $e,Fb as Zn,Gb as Ue,Hb as Ge,Ib as Be,Jb as eo,Ma as Dn,Na as Nn,Nb as to,Ob as Et,Ra as $n,T as $,Va as H,Xa as Un,Xb as ro,Ya as re,Z as Fn,Za as vt,_ as Tn,_a as Gn,aa as Pn,ba as Hn,da as wt,dd as no,ea as On,eb as Bn,fa as Te,hd as oo,ka as qn,mb as Le,ob as je,od as io,pb as zn,qb as qe,rb as De,sb as Vn,tb as Kn,ub as Ne,wb as Qn,xa as He,xb as Yn}from"./chunk-TZY5MVJF.js";import{B as Wn,I as O,a as Pe,b as Ln,c as jn,v as P}from"./chunk-2UQU7HRR.js";import{$b as Ie,$c as de,$g as yn,Aj as te,Bd as en,Bg as hn,Bh as Sn,Dc as N,De as cn,Dj as Mn,Ej as he,Fc as Z,Fh as V,Gh as xn,Ib as ce,Jb as Re,Ka as D,Mg as pn,Nb as ke,Ob as Kr,Oh as Rn,Sa as k,Se as ee,Ta as Wr,Ua as zr,Uc as Ae,Wa as z,Wc as Xr,Wh as kn,Xh as In,Ya as xe,Yb as S,Ye as dn,Zc as Jr,Zh as An,_g as gn,a as F,ac as Qr,bc as Yr,be as Fe,cc as mt,ce as tn,cf as ln,ge as le,ib as ut,lb as J,le as rn,me as ht,nd as Zr,ne as ue,od as Ce,oe as me,oh as yt,pd as Me,pe as pt,pj as x,qe as T,qh as _n,re as nn,se as fe,tb as Vr,tc as I,te as on,uc as ft,ug as un,ve as sn,vg as mn,vh as wn,we as gt,wh as vn,wj as Cn,xj as _t,yh as En,ze as an,zg as fn,zh as bn}from"./chunk-NGJ5ERBF.js";import{A as h,C as p,E as Se,G as Br,K as L,u as Ur,z as Gr}from"./chunk-YYT3MIRF.js";import jo from"node:fs/promises";import qo from"node:path";function cs(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function ds(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function Lo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return cs(t.ids,r,t.minEntries)}return ds(e,t)}function ls(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new p("history-compact --before requires a non-empty value.",h.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=H(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new p(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,h.USAGE);let a=i-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new p(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,h.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new p(`History for this item contains invalid timestamp at entry ${i+1}.`,h.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function us(e,t){let r=ue(),n=ue();for(let o=0;o<e.length;o+=1){let i=e[o];r=re(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function ms(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:_n.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&pt(fe(e.document),n,I(r.hash_algorithm)).includes(r.after_hash))}}function fs(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function hs(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function ps(e,t){let r=e.slice(0,t).findIndex(o=>!no(o));if(r===-1)return;let n=Number.isFinite(Date.parse(e[r].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new p(`History for this item contains ${n} at entry ${r+1}.`,h.GENERIC_FAILURE)}function gs(e,t){let r=e[t.start].ts,n=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!n.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${r}".`,`Run pm history-compact <id> --before "${r}".`];let o=new Date(n.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${r}", or after "${o}".`,`Run pm history-compact <id> --before "${r}", or with a timestamp after "${o}".`]}function ys(e,t){let r=t-1,n=(sn(e).bridged_segments??[]).find(({start:d,end:l})=>d<=r&&r<l);if(n===void 0)return;let o=H(e,!0),[i,s,a]=o===null?gs(e,n):[`version ${o+t}`,`Choose --before ${o+n.start+1} or lower, or --before ${o+n.end+2} or higher.`,`Run pm history-compact <id> --before ${o+n.start+1} or --before ${o+n.end+2}.`];throw new p(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,h.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[a]})}function _s(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};ys(e.historyEntries,e.boundary.compactCount);let{checkpoint:t,finalReplay:r}=us(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=H(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:I(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:T(ue()),after:T(t),message:hs(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:oo(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:wn(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[vn({...s,before_hash:pt(ue(),i.item_hash_version??1,I(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:T(r),after:T(r),message:fs(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function ws(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>vs(s,t,a)})}function vs(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new p(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,h.CONFLICT);let s=ls(t.before,o);ps(o,s.compactCount);let a=s.compactCount>0,d=!!t.dryRun,l=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=ms(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:f,auditEntryAdded:_}=_s({historyEntries:o,boundary:s,changed:a,dryRun:d,author:l,options:t}),y=H(o,!0),g=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:d,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:n,entries_scanned:o.length,entries_after:m.length,baseline_entry_added:f,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...c,...v])].sort((b,E)=>b.localeCompare(E)),generated_at:S()})}}var Es=3;function bs(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new p(`history-compact ${r} must be a non-negative safe integer.`,h.USAGE)}let t=Hn(e.ids);if(e.ids!==void 0&&t==="")throw new p("history-compact ids requires at least one valid item ID.",h.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Pn(t)}}function Hd(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)===0)throw new p("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",h.USAGE);if(e!==void 0&&(r||n))throw new p("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",h.USAGE);if(r&&n)throw new p("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",h.USAGE)}function Ss(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function xs(e){let t=N(e.settings.schema),r=We(t),n=await Ne(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(l=>[l.id,r.classify(l.status)])),i=qo.join(e.pmRoot,"history"),s=[],a=[];if(!await Se(i))return{candidates:s,preselectionErrors:a};let d=(await jo.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,c)=>l.localeCompare(c));for(let l of d){let c=qo.join(i,l),u=l.slice(0,-6);try{let m=await jo.readFile(c,"utf8");await he({path:c,scope:"project"}),s.push({id:u,entries:Ss(m),bucket:o.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function Rs(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await ws(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await ao(t,e.pmRoot)}}}}async function Od(e,t){let r=bs(e),{pmRoot:n,settings:o,typeRegistry:i}=await pe(t.path),{candidates:s,preselectionErrors:a}=await xs({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),d=r.ids!==void 0&&r.ids.length>0?"ids":"scan",l=e.minEntries??Es,c=o.history.compact_policy,u=d==="scan"&&e.allOver===void 0&&c.enabled,m=e.allOver??(u?c.max_entries:void 0),f=Lo(s,{ids:r.ids,scope:e.scope,minEntries:l,allOver:m}),_=!!e.dryRun,y=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of f){let v=await Rs({pmRoot:n,row:w,options:r,dryRun:_,global:t});if(y.push(v.result),!v.selected){g.items_skipped+=1;continue}g.selected+=1,v.compacted&&(g.items_compacted+=1),v.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:_,mode:d,scope:e.scope??null,criteria:{min_entries:l,all_over:m??null,policy_threshold_applied:u},totals:g,results:y,generated_at:S()}}import Ct from"node:fs/promises";function Mt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function No(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function At(e,t){return new p(`Invalid --regex value at --regex #${e}: ${t}`,h.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function $o(e,t=1){let r=e.trim();if(r.length===0)throw At(t,"provide a non-empty pattern.");let n=r,o="g";if(r.startsWith("/")&&r.length>1){let i=r.lastIndexOf("/"),s=0;for(let a=i-1;a>=0&&r[a]==="\\";a--)s++;i>0&&s%2===0&&/^[dgimsuvy]*$/u.test(r.slice(i+1))&&(n=r.slice(1,i),o=No(r.slice(i+1)))}if(n.length===0)throw At(t,"an empty pattern is not allowed.");try{new RegExp(n,o)}catch{throw At(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:n,flags:o}}function Uo(e,t){let r=[...new Set(Mt(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),n=new Set,o=Mt(t).flatMap((s,a)=>{let d=s.trim();return n.has(d)?[]:(n.add(d),[$o(d,a+1)])}),i=[...r,...o];if(i.length===0)throw new p("history-redact requires at least one matcher via --literal or --regex.",h.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function Go(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function Bo(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function Ft(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?Go(n,i.value,r):Bo(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function ye(e,t,r){if(typeof e=="string")return Ft(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=ye(i,t,r);return n+=s.replacements,s.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=ye(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function Do(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=ye(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function ks(e){let t=structuredClone(ht),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];me(t,void 0,I(i.hash_algorithm))!==i.before_hash&&(r+=1),t=re(t,i.patch,o+1,i.op),me(t,void 0,I(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Is(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let l=Ft(e.message,t,r);s=l.value,n+=l.replacements,l.replacements>0&&(o=!0)}let a=Do(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let d=e.reanchor_evidence?.map(l=>{let c=l.patch?Do(l.patch,t,r):{patch:void 0,replacements:0},u=l.record?ye(l.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let m=c.replacements>0||u.replacements>0;if(o||=m,!m)return l;i=!0;let{patch:f,record:_,record_hash:y,record_hash_version:g,...w}=l;return c.replacements>0?w:{...w,patch:l.patch}});return{entry:{...e,message:s,patch:a.patch,...d?{reanchor_evidence:d}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function As(e,t,r){let n=structuredClone(ht),o=0,i=0,s=[],a=rn(e),d=[...a.unlocated,...a.undigested];if(d.length>0)throw new p(`history-redact refuses a stream whose bridge at record ${Math.min(...d)+1} does not prove its segment; repair the history first.`,h.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});let l=an(a.segments);for(let c=0;c<e.length;c+=1){let u=e[c],m=En(u);if(!m.ok)throw new p(`history-redact refuses invalid immutable record ${c+1} (${m.error}).`,h.GENERIC_FAILURE);let f=Is(u,t,r);i+=f.replacements,f.changed&&(o+=1);let _=me(n,void 0,I(u.hash_algorithm));n=re(n,f.entry.patch,c+1,f.entry.op);let y=me(n,void 0,I(u.hash_algorithm)),{bridge:g,...w}=f.entry;s.push(bn(u,{...w,...l.has(c)?{replay_inexact:!0}:{},before_hash:_,after_hash:y},{retainPriorRecord:f.changed||g!==void 0,retainPriorRecordHash:!f.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function Wo(e){return Object.keys(e.metadata).length>0}function Cs(e){if(!Wo(e.finalDocument))return{raw:null,path:null,document:null};let t=Me(T(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new p("history-redact would change the item id; narrow your patterns.",h.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Ce(t,{format:"toon",schema:e.settings.schema})}}function Ms(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function Fs(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??T(e.rewritten.finalDocument);return t.push(V({nowIso:S(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function Ts(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Le(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await L(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Ct.rm(e.currentItem.path,{force:!0}),await L(e.subject.historyPath,cn(e.rewrittenEntries))}catch(d){try{await Ps(e.subject.historyPath,r,o,i)}finally{await yt(e.subject.historyPath)}throw d}await yt(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await Hs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function Ps(e,t,r,n){t===null?await Ct.rm(e,{force:!0}):await L(e,t);for(let o of r){let i=n.get(o);i===void 0?await Ct.rm(o,{force:!0}):await L(o,i)}}async function Hs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await te({path:o,scope:"project",op:"history_redact"}));return r.push(...await te({path:e,scope:"project",op:"history_redact:history"})),r}async function el(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=t.replacement??"",a=s.length===0,d=a?"[redacted]":s,l=Uo(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>Os({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:l,replacement:d,replacementIsDefault:a},u)})}function Os(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:d,replacementIsDefault:l}=e,c=t.entries,u=ks(c),m=As(c,a,d),f=u.hashMismatchesBefore+u.hashMismatchesAfter,_=!!s.dryRun,y=m.replacements>0,g=[];f>0&&g.push(`history_redact_preexisting_hash_mismatches:${f}`),y||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=Cs({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:m.finalDocument}),b=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),E=t.author,X=Ms(s,m),{rewrittenEntries:R,auditEntryAdded:lt}=Fs({rewritten:m,dryRun:_,changed:y,nextItemDocument:v.document,author:E,message:X});return{changed:y,rewrittenEntries:R,...Ts({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:E,rewrittenEntries:R}),report:({verification:q,warnings:ae})=>({id:n.id,dry_run:_,changed:y,patterns:{literal_count:a.filter(B=>B.kind==="literal").length,regex_count:a.filter(B=>B.kind==="regex").length,total_count:a.length,replacement_is_default:l},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:f,audit_entry_added:lt,verify_ok:q.ok,verify_errors:q.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:b},warnings:[...new Set([...g,...ae])].sort((B,W)=>B.localeCompare(W)),generated_at:S()})}}var tl={applyLiteralRule:Go,applyRegexRule:Bo,buildRedactionRules:Uo,hasItemMetadata:Wo,normalizeRegexFlags:No,normalizeStringArrayInput:Mt,parseRegexRule:$o,redactStringValue:Ft,redactUnknownValue:ye};var Tt={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as Ls}from"node:crypto";import{isUtf8 as js}from"node:buffer";import _e from"node:fs/promises";import Pt from"node:path";async function zo(e){try{return(await _e.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Br(t))return[];throw t}}function qs(e,t,r,n){let o=t.at(-1),i;for(let d=t.length-1;d>=0;d-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[d].op)){i=t[d];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?I(o.hash_algorithm):null,rewrite_count:t.reduce((d,l)=>d+(l.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function Ds(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!js(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return gt(n).ok?qs(e,n,t.length,r):null}catch{return null}}async function Ht(e,t){if(!(await _e.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Pt.join(e,"history"),n=await zo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),d={id:a,digest:null,stream:null};i.push(d);let l=Pt.join(r,s);try{let c=await _e.lstat(l);if(o.set(s,F([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await _e.readFile(l);d.digest=Ls(t).update(u).digest("hex"),d.stream=Ds(a,u,d.digest)}catch{}}if(F(n)!==F(await zo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let d=await _e.lstat(Pt.join(r,s));if(a!==F([d.ino,d.size,d.mtimeMs,d.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}function Ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function ne(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function Ns(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:ne(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||ne(e.latest_record_hash,e.latest_hash_algorithm))}function $s(e){return e===null?!0:!Ot(e)||!Lt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Ie(e.ts)&&(e.record_hash===null||ne(e.record_hash,"sha256")||ne(e.record_hash,"sha512"))}function Us(e,t){return!Ot(e)||!Lt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&ne(e.stream_digest,t)&&Ns(e)&&(e.checkpoint_digest===null||ne(e.checkpoint_digest,"sha256"))&&$s(e.last_maintenance)}function Vo(e){if(!Ot(e)||!Lt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Tt.format||e.version!==1||typeof e.generated_at!="string"||!Ie(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let i of e.streams){if(!Us(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(ft(F(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Ko(e={}){let t=I(e.hashAlgorithm),r=e.generatedAt??S();if(!Ie(r))throw new TypeError("Invalid history attestation timestamp");let n=await Ht(k(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:Tt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return Vo({...i,workspace_digest:ft(F(i),t)})}async function Qo(e,t={}){let r=Vo(e),n=await Ht(k(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(c=>[c.id,c])),i=new Map(r.streams.map(c=>[c.id,c])),s=r.streams.filter(c=>!o.has(c.id)).map(c=>c.id),a=n.filter(c=>!i.has(c.id)).map(c=>c.id),d=n.filter(c=>c.stream===null).map(c=>c.id),l=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||F(u.stream)!==F(c))&&l.push({id:c.id,before_digest:c.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+d.length+l.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:l.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:d,transitions:l}}import Yo from"node:fs/promises";async function Il(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new p(`history attest ${n} requires a nonempty string.`,h.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new p("history attest --verify cannot be combined with --output or --hash-algorithm",h.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Yo.readFile(e.verify,"utf8")):e.verify}catch{throw new p("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",h.USAGE)}return Qo(n,{pmRoot:t.path})}let r=await Ko({pmRoot:t.path,hashAlgorithm:I(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Yo.writeFile(e.output,`${JSON.stringify(r,null,2)}
1
+ import{$ as Io,B as Eo,C as bo,Eb as Mo,F as So,Gb as Fo,Ib as To,Jb as Po,Ka as Ao,N as xo,O as Ro,R as ko,S as kt,T as It,U as ze,e as ho,i as ge,ib as Co,j as po,jb as Ve,k as go,l as We,m as yo,mc as Ho,n as _o,q as wo,qc as Oo,r as vo}from"./chunk-7VRFEURZ.js";import{a as co,b as lo}from"./chunk-STOOTHZZ.js";import{c as bt,j as so,r as ao}from"./chunk-Z7MFVRDV.js";import{a as pe,b as K}from"./chunk-PQUBVRV5.js";import{Ba as Oe,Cb as Xn,Db as Jn,Eb as $e,Fb as Zn,Gb as Ue,Hb as Ge,Ib as Be,Jb as eo,Ma as Dn,Na as Nn,Nb as to,Ob as Et,Ra as $n,T as $,Va as H,Xa as Un,Xb as ro,Ya as re,Z as Fn,Za as vt,_ as Tn,_a as Gn,aa as Pn,ba as Hn,da as wt,dd as no,ea as On,eb as Bn,fa as Te,hd as oo,ka as qn,mb as Le,ob as je,od as io,pb as zn,qb as qe,rb as De,sb as Vn,tb as Kn,ub as Ne,wb as Qn,xa as He,xb as Yn}from"./chunk-YOPTAIBD.js";import{B as Wn,I as O,a as Pe,b as Ln,c as jn,v as P}from"./chunk-23K6DQQY.js";import{Ab as Ce,Ac as me,Ba as ce,Bb as Me,Bc as pt,Ca as Re,Cc as T,Cf as yt,Dc as nn,Dh as x,Ec as fe,Ef as _n,Fc as on,Ga as ke,Ha as Kr,Hc as sn,Ic as gt,Ie as un,Je as mn,Jf as wn,Kf as vn,Kh as Cn,Lc as an,Lh as _t,Mf as En,Nb as en,Ne as fn,Nf as bn,Oh as te,Pc as cn,Pe as hn,Pf as Sn,Rh as Mn,Sh as he,Tf as V,Uf as xn,V as D,_e as pn,ab as I,ag as Rn,ba as k,bb as ft,ca as Wr,cd as ee,da as zr,eb as Ae,fa as z,gb as Xr,ha as xe,id as dn,ig as kn,jb as Jr,jg as In,lb as de,lg as An,mf as gn,nc as Fe,nf as yn,oc as tn,od as ln,sc as le,ta as ut,xc as rn,yc as ht,zb as Zr,zc as ue}from"./chunk-FXJYZBWV.js";import{gb as fo,h as St,i as xt,k as Rt,l as uo,m as mo}from"./chunk-I2OJ5B4A.js";import{A as Vr,K as S,N as Ie,O as Qr,P as Yr,Q as mt,a as F,s as J}from"./chunk-7IROAPWI.js";import{O as N,Q as Z}from"./chunk-7X253M6Z.js";import{A as h,C as p,E as Se,G as Br,K as L,u as Ur,z as Gr}from"./chunk-YYT3MIRF.js";import jo from"node:fs/promises";import qo from"node:path";function cs(e,t,r){let n=new Set,o=[];for(let i of e){let s=i.trim();if(s.length===0||n.has(s))continue;n.add(s);let a=t.get(s);if(a===void 0){o.push({id:s,entries:0,selected:!1,skip_reason:"no_stream"});continue}if(a.entries<=r){o.push({id:s,entries:a.entries,selected:!1,skip_reason:"already_compact"});continue}o.push({id:s,entries:a.entries,selected:!0,skip_reason:null})}return o}function ds(e,t){let r=[...e].sort((o,i)=>i.entries-o.entries||o.id.localeCompare(i.id)),n=[];for(let o of r){if(t.scope==="closed"&&o.bucket!=="closed"){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"scope_mismatch"});continue}if(o.entries<=t.minEntries){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"already_compact"});continue}if(t.allOver!==void 0&&o.entries<=t.allOver){n.push({id:o.id,entries:o.entries,selected:!1,skip_reason:"below_threshold"});continue}n.push({id:o.id,entries:o.entries,selected:!0,skip_reason:null})}return n}function Lo(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return cs(t.ids,r,t.minEntries)}return ds(e,t)}function ls(e,t){if(e===void 0)return{kind:"default",raw:null,compactCount:t.length,retainedCount:0};let r=e.trim();if(r.length===0)throw new p("history-compact --before requires a non-empty value.",h.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=H(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new p(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,h.USAGE);let a=i-s-1;return{kind:"version",raw:r,compactCount:a,retainedCount:t.length-a}}let n=Date.parse(r);if(!Number.isFinite(n))throw new p(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,h.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new p(`History for this item contains invalid timestamp at entry ${i+1}.`,h.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function us(e,t){let r=ue(),n=ue();for(let o=0;o<e.length;o+=1){let i=e[o];r=re(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function ms(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:_n.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&pt(fe(e.document),n,I(r.hash_algorithm)).includes(r.after_hash))}}function fs(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:t.raw===null?`history-compact compacted full stream (${t.compactCount} entr${t.compactCount===1?"y":"ies"}).`:`history-compact compacted ${t.compactCount} entr${t.compactCount===1?"y":"ies"} before ${t.raw}.`}function hs(e){return e.raw===null?`history-compact baseline snapshot after compacting ${e.compactCount} entr${e.compactCount===1?"y":"ies"}.`:`history-compact baseline snapshot before ${e.raw}.`}function ps(e,t){let r=e.slice(0,t).findIndex(o=>!no(o));if(r===-1)return;let n=Number.isFinite(Date.parse(e[r].ts))?"a malformed record or compaction receipt":"invalid timestamp";throw new p(`History for this item contains ${n} at entry ${r+1}.`,h.GENERIC_FAILURE)}function gs(e,t){let r=e[t.start].ts,n=e.slice(0,t.end+1).map(i=>Date.parse(i.ts));if(!n.every(Number.isFinite))return["that boundary",`Choose a --before timestamp at or before "${r}".`,`Run pm history-compact <id> --before "${r}".`];let o=new Date(n.reduce((i,s)=>Math.max(i,s),Number.NEGATIVE_INFINITY)).toISOString();return["that boundary",`Choose a --before timestamp at or before "${r}", or after "${o}".`,`Run pm history-compact <id> --before "${r}", or with a timestamp after "${o}".`]}function ys(e,t){let r=t-1,n=(sn(e).bridged_segments??[]).find(({start:d,end:l})=>d<=r&&r<l);if(n===void 0)return;let o=H(e,!0),[i,s,a]=o===null?gs(e,n):[`version ${o+t}`,`Choose --before ${o+n.start+1} or lower, or --before ${o+n.end+2} or higher.`,`Run pm history-compact <id> --before ${o+n.start+1} or --before ${o+n.end+2}.`];throw new p(`history-compact cannot checkpoint ${i}: it lies inside a bridged segment whose states cannot be reconstructed.`,h.USAGE,{code:"history_compact_boundary_bridged",required:s,nextSteps:[a]})}function _s(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};ys(e.historyEntries,e.boundary.compactCount);let{checkpoint:t,finalReplay:r}=us(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=H(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:I(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:T(ue()),after:T(t),message:hs(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",last_activity_at:oo(e.historyEntries.slice(0,e.boundary.compactCount)),pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:wn(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[vn({...s,before_hash:pt(ue(),i.item_hash_version??1,I(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version,...i.replay_inexact===!0?{replay_inexact:!0}:{}}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:T(r),after:T(r),message:fs(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function ws(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>vs(s,t,a)})}function vs(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new p(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,h.CONFLICT);let s=ls(t.before,o);ps(o,s.compactCount);let a=s.compactCount>0,d=!!t.dryRun,l=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=ms(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:m,baselineEntryAdded:f,auditEntryAdded:_}=_s({historyEntries:o,boundary:s,changed:a,dryRun:d,author:l,options:t}),y=H(o,!0),g=s.retainedCount>0&&y!==null?y+s.compactCount+1:null;return{changed:a,rewrittenEntries:m,report:({verification:w,warnings:v})=>({id:e.id,dry_run:d,changed:a,compact_boundary:{kind:s.kind,before:s.raw,entries_compacted:s.compactCount,entries_retained:s.retainedCount,first_retained_entry:g},history:{path:n,entries_scanned:o.length,entries_after:m.length,baseline_entry_added:f,audit_entry_added:_,verify_ok:w.ok,verify_errors:w.errors},item:{exists:e.located!==null,path:e.located?.itemPath??null,matched_chain_before:u.matchedChainBefore},warnings:[...new Set([...c,...v])].sort((b,E)=>b.localeCompare(E)),generated_at:S()})}}var Es=3;function bs(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new p(`history-compact ${r} must be a non-negative safe integer.`,h.USAGE)}let t=Hn(e.ids);if(e.ids!==void 0&&t==="")throw new p("history-compact ids requires at least one valid item ID.",h.USAGE,{code:"bulk_ids_input_empty",required:"Provide one or more string or finite numeric IDs; non-finite and unsupported selector values are rejected."});return{...e,ids:t===void 0?void 0:Pn(t)}}function Hd(e,t){let r=t.ids!==void 0&&t.ids.length>0,n=t.allOver!==void 0||t.scope!==void 0;if((e!==void 0?1:0)+(r?1:0)+(n?1:0)===0)throw new p("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",h.USAGE);if(e!==void 0&&(r||n))throw new p("history-compact: <id> and bulk selectors (--ids/--all-over/--closed/--all-streams) are mutually exclusive; pass one item id, or use bulk mode without a positional id.",h.USAGE);if(r&&n)throw new p("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",h.USAGE)}function Ss(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function xs(e){let t=N(e.settings.schema),r=We(t),n=await Ne(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(l=>[l.id,r.classify(l.status)])),i=qo.join(e.pmRoot,"history"),s=[],a=[];if(!await Se(i))return{candidates:s,preselectionErrors:a};let d=(await jo.readdir(i)).filter(l=>l.endsWith(".jsonl")).sort((l,c)=>l.localeCompare(c));for(let l of d){let c=qo.join(i,l),u=l.slice(0,-6);try{let m=await jo.readFile(c,"utf8");await he({path:c,scope:"project"}),s.push({id:u,entries:Ss(m),bucket:o.get(u)??null})}catch(m){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:m instanceof Error?m.message:String(m)})}}return{candidates:s,preselectionErrors:a}}async function Rs(e){if(!e.row.selected)return{selected:!1,compacted:!1,errored:!1,result:{id:e.row.id,outcome:"skipped",entries_before:e.row.entries,entries_after:null,skip_reason:e.row.skip_reason,changed:!1,error:null}};try{let t=await ws(e.row.id,{dryRun:e.dryRun,author:e.options.author,message:e.options.message,force:e.options.force},e.global);return{selected:!0,compacted:!0,errored:!1,result:{id:e.row.id,outcome:"compacted",entries_before:e.row.entries,entries_after:t.history.entries_after,skip_reason:null,changed:t.changed,error:null}}}catch(t){return{selected:!0,compacted:!1,errored:!0,result:{id:e.row.id,outcome:"errored",entries_before:e.row.entries,entries_after:null,skip_reason:null,changed:!1,error:t instanceof Error?t.message:String(t),...await ao(t,e.pmRoot)}}}}async function Od(e,t){let r=bs(e),{pmRoot:n,settings:o,typeRegistry:i}=await pe(t.path),{candidates:s,preselectionErrors:a}=await xs({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),d=r.ids!==void 0&&r.ids.length>0?"ids":"scan",l=e.minEntries??Es,c=o.history.compact_policy,u=d==="scan"&&e.allOver===void 0&&c.enabled,m=e.allOver??(u?c.max_entries:void 0),f=Lo(s,{ids:r.ids,scope:e.scope,minEntries:l,allOver:m}),_=!!e.dryRun,y=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of f){let v=await Rs({pmRoot:n,row:w,options:r,dryRun:_,global:t});if(y.push(v.result),!v.selected){g.items_skipped+=1;continue}g.selected+=1,v.compacted&&(g.items_compacted+=1),v.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:_,mode:d,scope:e.scope??null,criteria:{min_entries:l,all_over:m??null,policy_threshold_applied:u},totals:g,results:y,generated_at:S()}}import Ct from"node:fs/promises";function Mt(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function No(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function At(e,t){return new p(`Invalid --regex value at --regex #${e}: ${t}`,h.USAGE,{code:"invalid_argument_value",field:"regex",reason:"invalid_regex",changed:!1,required:`Correct --regex #${e}: use a non-empty raw source or /pattern/flags with valid JavaScript flags.`})}function $o(e,t=1){let r=e.trim();if(r.length===0)throw At(t,"provide a non-empty pattern.");let n=r,o="g";if(r.startsWith("/")&&r.length>1){let i=r.lastIndexOf("/"),s=0;for(let a=i-1;a>=0&&r[a]==="\\";a--)s++;i>0&&s%2===0&&/^[dgimsuvy]*$/u.test(r.slice(i+1))&&(n=r.slice(1,i),o=No(r.slice(i+1)))}if(n.length===0)throw At(t,"an empty pattern is not allowed.");try{new RegExp(n,o)}catch{throw At(t,"provide a valid JavaScript regular expression.")}return{kind:"regex",source:n,flags:o}}function Uo(e,t){let r=[...new Set(Mt(e).map(s=>s.trim()))].filter(s=>s.length>0).map(s=>({kind:"literal",value:s})),n=new Set,o=Mt(t).flatMap((s,a)=>{let d=s.trim();return n.has(d)?[]:(n.add(d),[$o(d,a+1)])}),i=[...r,...o];if(i.length===0)throw new p("history-redact requires at least one matcher via --literal or --regex.",h.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return i}function Go(e,t,r){if(t.length===0)return{value:e,replacements:0};let n=0,o=0;for(;n<=e.length;){let i=e.indexOf(t,n);if(i===-1)break;o+=1,n=i+Math.max(1,t.length)}return o===0?{value:e,replacements:0}:{value:e.split(t).join(r),replacements:o}}function Bo(e,t,r){let n=new RegExp(t.source,t.flags),o=[...e.matchAll(n)];return o.length===0?{value:e,replacements:0}:{value:e.replace(n,r),replacements:o.length}}function Ft(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?Go(n,i.value,r):Bo(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function ye(e,t,r){if(typeof e=="string")return Ft(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=ye(i,t,r);return n+=s.replacements,s.value}),replacements:n}}if(typeof e=="object"&&e!==null){let n=0,o={};for(let[i,s]of Object.entries(e)){let a=ye(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function Do(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=ye(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function ks(e){let t=structuredClone(ht),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];me(t,void 0,I(i.hash_algorithm))!==i.before_hash&&(r+=1),t=re(t,i.patch,o+1,i.op),me(t,void 0,I(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Is(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let l=Ft(e.message,t,r);s=l.value,n+=l.replacements,l.replacements>0&&(o=!0)}let a=Do(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let d=e.reanchor_evidence?.map(l=>{let c=l.patch?Do(l.patch,t,r):{patch:void 0,replacements:0},u=l.record?ye(l.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let m=c.replacements>0||u.replacements>0;if(o||=m,!m)return l;i=!0;let{patch:f,record:_,record_hash:y,record_hash_version:g,...w}=l;return c.replacements>0?w:{...w,patch:l.patch}});return{entry:{...e,message:s,patch:a.patch,...d?{reanchor_evidence:d}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function As(e,t,r){let n=structuredClone(ht),o=0,i=0,s=[],a=rn(e),d=[...a.unlocated,...a.undigested];if(d.length>0)throw new p(`history-redact refuses a stream whose bridge at record ${Math.min(...d)+1} does not prove its segment; repair the history first.`,h.GENERIC_FAILURE,{code:"history_redact_bridge_unlocated",required:"Every bridge's segment digest must match the records it covers, so redaction can keep that segment's versions refused.",nextSteps:["Run pm history-repair <id> --dry-run to see how the stream would be repaired."]});let l=an(a.segments);for(let c=0;c<e.length;c+=1){let u=e[c],m=En(u);if(!m.ok)throw new p(`history-redact refuses invalid immutable record ${c+1} (${m.error}).`,h.GENERIC_FAILURE);let f=Is(u,t,r);i+=f.replacements,f.changed&&(o+=1);let _=me(n,void 0,I(u.hash_algorithm));n=re(n,f.entry.patch,c+1,f.entry.op);let y=me(n,void 0,I(u.hash_algorithm)),{bridge:g,...w}=f.entry;s.push(bn(u,{...w,...l.has(c)?{replay_inexact:!0}:{},before_hash:_,after_hash:y},{retainPriorRecord:f.changed||g!==void 0,retainPriorRecordHash:!f.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function Wo(e){return Object.keys(e.metadata).length>0}function Cs(e){if(!Wo(e.finalDocument))return{raw:null,path:null,document:null};let t=Me(T(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new p("history-redact would change the item id; narrow your patterns.",h.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:Ce(t,{format:"toon",schema:e.settings.schema})}}function Ms(e,t){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-redact replaced ${t.replacements} match(es) across ${t.entriesChanged} entr${t.entriesChanged===1?"y":"ies"}.`}function Fs(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??T(e.rewritten.finalDocument);return t.push(V({nowIso:S(),author:e.author,op:"history_redact",before:r,after:r,message:e.message})),{rewrittenEntries:t,auditEntryAdded:!0}}function Ts(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Le(e.pmRoot,e.author),o=new Set;e.currentItem.path&&o.add(e.currentItem.path),e.nextItem.path&&o.add(e.nextItem.path);let i=new Map;e.currentItem.path&&e.currentItem.raw!==null&&i.set(e.currentItem.path,e.currentItem.raw);let s=()=>{};try{try{e.nextItem.path&&e.nextItem.raw!==null&&e.nextItem.raw!==e.currentItem.raw&&await L(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await Ct.rm(e.currentItem.path,{force:!0}),await L(e.subject.historyPath,cn(e.rewrittenEntries))}catch(d){try{await Ps(e.subject.historyPath,r,o,i)}finally{await yt(e.subject.historyPath)}throw d}await yt(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await je({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:e.typeRegistry.type_to_folder,schema:e.settings.schema,itemPath:a,...e.currentItem.path?{previousItemPath:e.currentItem.path}:{},document:e.nextItem.document}))}finally{await n().catch(a=>{s=()=>{throw a}})}s()},afterWrite:async()=>[...t,...await Hs(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function Ps(e,t,r,n){t===null?await Ct.rm(e,{force:!0}):await L(e,t);for(let o of r){let i=n.get(o);i===void 0?await Ct.rm(o,{force:!0}):await L(o,i)}}async function Hs(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await te({path:o,scope:"project",op:"history_redact"}));return r.push(...await te({path:e,scope:"project",op:"history_redact:history"})),r}async function el(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await pe(r.path),s=t.replacement??"",a=s.length===0,d=a?"[redacted]":s,l=Uo(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return Ve({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>Os({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:l,replacement:d,replacementIsDefault:a},u)})}function Os(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:d,replacementIsDefault:l}=e,c=t.entries,u=ks(c),m=As(c,a,d),f=u.hashMismatchesBefore+u.hashMismatchesAfter,_=!!s.dryRun,y=m.replacements>0,g=[];f>0&&g.push(`history_redact_preexisting_hash_mismatches:${f}`),y||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},v=Cs({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:m.finalDocument}),b=(w.path??null)!==(v.path??null)||(w.raw??null)!==(v.raw??null),E=t.author,X=Ms(s,m),{rewrittenEntries:R,auditEntryAdded:lt}=Fs({rewritten:m,dryRun:_,changed:y,nextItemDocument:v.document,author:E,message:X});return{changed:y,rewrittenEntries:R,...Ts({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:v,author:E,rewrittenEntries:R}),report:({verification:q,warnings:ae})=>({id:n.id,dry_run:_,changed:y,patterns:{literal_count:a.filter(B=>B.kind==="literal").length,regex_count:a.filter(B=>B.kind==="regex").length,total_count:a.length,replacement_is_default:l},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:m.entriesChanged,replacements:m.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:f,audit_entry_added:lt,verify_ok:q.ok,verify_errors:q.errors},item:{existed_before:w.path!==null,exists_after:v.path!==null,path_before:w.path,path_after:v.path,changed:b},warnings:[...new Set([...g,...ae])].sort((B,W)=>B.localeCompare(W)),generated_at:S()})}}var tl={applyLiteralRule:Go,applyRegexRule:Bo,buildRedactionRules:Uo,hasItemMetadata:Wo,normalizeRegexFlags:No,normalizeStringArrayInput:Mt,parseRegexRule:$o,redactStringValue:Ft,redactUnknownValue:ye};var Tt={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};import{createHash as Ls}from"node:crypto";import{isUtf8 as js}from"node:buffer";import _e from"node:fs/promises";import Pt from"node:path";async function zo(e){try{return(await _e.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Br(t))return[];throw t}}function qs(e,t,r,n){let o=t.at(-1),i;for(let d=t.length-1;d>=0;d-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[d].op)){i=t[d];break}let s=t[0]?.context?.history_compaction,a=typeof s=="object"&&s!==null&&"pruned_stream_digest"in s&&typeof s.pruned_stream_digest=="string"?s.pruned_stream_digest:null;return{id:e,entries:t.length,bytes:r,stream_digest:n,latest_after_hash:o?.after_hash??null,latest_record_hash:o?.record_hash??null,latest_hash_algorithm:o?I(o.hash_algorithm):null,rewrite_count:t.reduce((d,l)=>d+(l.reanchor_evidence?.length??0),0),checkpoint_digest:a,last_maintenance:i?{op:i.op,ts:i.ts,record_hash:i.record_hash??null}:null}}function Ds(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!js(t))return null;let n=[];for(let o of t.toString("utf8").split(/\r?\n/u)){if(!o.trim())continue;let i=JSON.parse(o);if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=i;if(![s.op,s.author,s.ts,s.before_hash,s.after_hash].every(a=>typeof a=="string")||!Array.isArray(s.patch))return null;n.push(s)}return gt(n).ok?qs(e,n,t.length,r):null}catch{return null}}async function Ht(e,t){if(!(await _e.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Pt.join(e,"history"),n=await zo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),d={id:a,digest:null,stream:null};i.push(d);let l=Pt.join(r,s);try{let c=await _e.lstat(l);if(o.set(s,F([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await _e.readFile(l);d.digest=Ls(t).update(u).digest("hex"),d.stream=Ds(a,u,d.digest)}catch{}}if(F(n)!==F(await zo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let d=await _e.lstat(Pt.join(r,s));if(a!==F([d.ino,d.size,d.mtimeMs,d.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}function Ot(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function ne(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function Ns(e){return e.entries===0?[e.latest_hash_algorithm,e.latest_after_hash,e.latest_record_hash,e.checkpoint_digest,e.last_maintenance].every(t=>t===null)&&e.rewrite_count===0:e.latest_hash_algorithm!=="sha256"&&e.latest_hash_algorithm!=="sha512"?!1:ne(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||ne(e.latest_record_hash,e.latest_hash_algorithm))}function $s(e){return e===null?!0:!Ot(e)||!Lt(e,["op","ts","record_hash"])?!1:typeof e.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(e.op)&&typeof e.ts=="string"&&Ie(e.ts)&&(e.record_hash===null||ne(e.record_hash,"sha256")||ne(e.record_hash,"sha512"))}function Us(e,t){return!Ot(e)||!Lt(e,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof e.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(e.id)&&[e.entries,e.bytes,e.rewrite_count].every(r=>typeof r=="number"&&Number.isSafeInteger(r)&&r>=0)&&ne(e.stream_digest,t)&&Ns(e)&&(e.checkpoint_digest===null||ne(e.checkpoint_digest,"sha256"))&&$s(e.last_maintenance)}function Vo(e){if(!Ot(e)||!Lt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==Tt.format||e.version!==1||typeof e.generated_at!="string"||!Ie(e.generated_at)||!Array.isArray(e.streams)||e.hash_algorithm!=="sha256"&&e.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");let t=e.hash_algorithm,r;for(let i of e.streams){if(!Us(i,t))throw new TypeError("Invalid history attestation stream");let s=i.id;if(r!==void 0&&s<=r)throw new TypeError("Invalid history attestation stream order");r=s}let{workspace_digest:n,...o}=e;if(ft(F(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function Ko(e={}){let t=I(e.hashAlgorithm),r=e.generatedAt??S();if(!Ie(r))throw new TypeError("Invalid history attestation timestamp");let n=await Ht(k(e.cwd??process.cwd(),e.pmRoot),t),o=n.filter(s=>s.stream===null);if(o.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${o.map(s=>s.id).join(", ")}`);let i={format:Tt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return Vo({...i,workspace_digest:ft(F(i),t)})}async function Qo(e,t={}){let r=Vo(e),n=await Ht(k(t.cwd??process.cwd(),t.pmRoot),r.hash_algorithm),o=new Map(n.map(c=>[c.id,c])),i=new Map(r.streams.map(c=>[c.id,c])),s=r.streams.filter(c=>!o.has(c.id)).map(c=>c.id),a=n.filter(c=>!i.has(c.id)).map(c=>c.id),d=n.filter(c=>c.stream===null).map(c=>c.id),l=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||F(u.stream)!==F(c))&&l.push({id:c.id,before_digest:c.stream_digest,after_digest:u.digest,last_maintenance:u.stream?.last_maintenance??null})}return{ok:s.length+a.length+d.length+l.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:l.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:d,transitions:l}}import Yo from"node:fs/promises";async function Il(e,t){for(let n of["verify","output","hashAlgorithm"]){let o=e[n];if(!(n==="verify"&&typeof o=="object"&&o!==null)&&o!==void 0&&(typeof o!="string"||o.trim().length===0))throw new p(`history attest ${n} requires a nonempty string.`,h.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new p("history attest --verify cannot be combined with --output or --hash-algorithm",h.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await Yo.readFile(e.verify,"utf8")):e.verify}catch{throw new p("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",h.USAGE)}return Qo(n,{pmRoot:t.path})}let r=await Ko({pmRoot:t.path,hashAlgorithm:I(e.hashAlgorithm)});if(e.output===void 0)return r;try{await Yo.writeFile(e.output,`${JSON.stringify(r,null,2)}
2
2
  `,{flag:"wx",mode:384})}catch{throw new p("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",h.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import Gs from"fast-json-patch";import jt from"node:fs/promises";function qt(e){return{schema:e.schema,extensionFieldNames:$(x())}}async function Xo(e,t,r){let n=await Vn(e,qt(t));return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:Jo(r),recovered:!0}}function Bs(e,t){return Un(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function Jo(e){let t=vt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Me(T(t))}async function Ws(e,t,r,n){let o=await K(e,t,r,n),i=o.located?await Te({pmRoot:e,settings:r,itemId:o.id,commandLabel:"restore"}):{warnings:[]};return{...o,historyPolicyWarnings:i.warnings}}function zs(e,t){let r=fe(e),n=fe(t),o=Gs.compare(r,n),i=new Set;for(let s of o){if(s.path==="/body"||s.path.startsWith("/body/")){i.add("body");continue}let a=s.path.replace(/^\/(?:metadata|front_matter)\/?/,"").split("/")[0];i.add(a.replaceAll("~1","/").replaceAll("~0","~"))}return Array.from(i).sort((s,a)=>s.localeCompare(a))}async function Vs(e){let t=await Co({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>Xo(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function Ks(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:Jo(t),originalRaw:null}}function Qs(e){let t=e.document.metadata.assignee?.trim(),r=t&&t!==e.author&&!e.force,n=Vr(t);if(!r)return[];if(e.enforcement==="strict")throw new p(`Item ${e.resolvedId} is assigned to ${n}. Use --force to override.`,h.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${n}`]:[]}function Ys(e){return Object.keys(e).length===0?void 0:e}async function Xs(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await L(e.existingItemPath,e.resolvedOriginalRaw),await jt.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await L(e.existingItemPath,e.resolvedOriginalRaw);return}await jt.rm(e.restoredItemPath,{force:!0})}async function Js(e){return[...await te({path:e.restoredItemPath,scope:"project",op:"restore",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]}),...await te({path:e.historyPath,scope:"project",op:"restore:history",item_id:e.after.metadata.id,item_type:e.after.metadata.type,before:e.before,after:e.after,changed_fields:["restored"]})]}async function Kl(e,t,r,n){let o=k(process.cwd(),n.path);await O(o);let i=await P(o),s=D(i,x()),a=await Ws(o,e,i,s.type_to_folder),d=a.id,{raw:l,entries:c}=await tn(a.historyPath,d);if(c.length===0)throw new p(`No history exists for ${d}; restore is unavailable.`,h.NOT_FOUND);let u=Bs(t,c),m=Gn(vt(c,u.historyIndex),u),f=nn(m,qt(i));if(f.metadata.id!==d)throw new p(`Restore target resolved to item ${f.metadata.id}, expected ${d}.`,h.GENERIC_FAILURE);let y=(a.located?await Xo(a.located,i,c):null)?.raw??null,g=Fe(r.author,i.author_default),w=await en(o,d,i.locks.ttl_seconds,g,!!r.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms,{waitPolicy:"progress"}),v=w.release;try{let{loadedItemUnderLock:b,existingItemPath:E}=await Vs({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:l,currentItemRawBeforeLock:y,history:c}),X="toon",R=Ks(b,c);b?.recovered===!0&&Rn(o,d,b.raw),kn(o,b?.document??Gr,d),f.metadata.pm_format_version=Xr(Math.max(Ae(f.metadata),Ae(R.document.metadata))),Wn(Wr(o),Ae(f.metadata));let lt=Qs({document:R.document,author:g,force:r.force,enforcement:i.governance.ownership_enforcement,resolvedId:d}),q=zs(R.document,f),ae=await Bn({pmRoot:o,settings:i,operation:"restore",author:g,before:R.document,after:f});await Mn({pm_root:o,operation:"restore",before:R.document,after:f,changed_fields:q,author:g,sdk:Qn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let B=Ce(f,{format:X,...qt(i)}),W=z(o,f.metadata.type,d,X,s.type_to_folder),ns=await w.fence(async()=>{let is=await Le(o,g),$r;try{await L(W,B),E&&W!==E&&await jt.rm(E);let ss=V({nowIso:S(),author:g,op:"restore",before:R.document,after:f,message:r.message,context:Ys({...ae.decisions.length===0?{}:{workflow_policies:ae.decisions},...An(o,[d,R.document.metadata.id,f.metadata.id],"restore")})});try{await xn(a.historyPath,ss)}catch(as){throw await Xs({existingItemPath:E,resolvedOriginalRaw:R.originalRaw,restoredItemPath:W}),as}$r=await je({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:W,previousItemPath:E??void 0,document:f})}finally{await is()}return $r});In(o,f,d);let os=await Js({restoredItemPath:W,historyPath:a.historyPath,before:R.document,after:f});Cn({id:f.metadata.id,op:"restore",item_type:f.metadata.type,previous_status:R.document.metadata.status,status:f.metadata.status,previous:_t(R.document.metadata,q),current:_t(f.metadata,q),changed_fields:q});let Dr=c[u.historyIndex],Nr=H(c,!0);return{item:f.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Nr===null?null:Nr+u.historyIndex+1,entry_ts:Dr.ts,entry_op:Dr.op},changed_fields:q,warnings:[...ae.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...lt,...ns,...os]}}finally{await v()}}var Zs=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],ea=["filterAcMissing","filterEstimatesMissing","filterResolutionMissing","filterMetadataMissing","filterReviewerMissing","filterRiskMissing","filterConfidenceMissing","filterSprintMissing","filterReleaseMissing","hasNotes","hasLearnings","hasFiles","hasDocs","hasTests","hasComments","hasDeps","hasBody","hasLinkedCommand","noNotes","noLearnings","noFiles","noDocs","noTests","noComments","noDeps","emptyBody","noLinkedCommand"];function ta(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function Yl(e,t,r={}){let n=r.includePagination!==!1;return[t,...Zs.map(i=>e?.[i]),...n?[e?.limit,e?.offset]:[]].some(ta)||ea.some(i=>e?.[i]===!0)}function Zo(e){return{type:e.type,tag:e.tag,priority:e.priority,deadlineBefore:e.deadlineBefore,deadlineAfter:e.deadlineAfter,assignee:e.assignee,assigneeFilter:e.assigneeFilter,parent:e.parent,sprint:e.sprint,release:e.release}}var ei=["parent","type","priority","status","assignee","tags","sprint","release"];function ri(e,t){let r=He(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function ni(e,t=["estimate","estimated_minutes","priority"]){let r=e.sum?.trim(),n=e.avg?.trim(),o=r&&r.length>0?r:void 0,i=n&&n.length>0?n:void 0;if(!o&&!i)return null;if(o&&i&&o!==i)throw new p("Aggregate --sum and --avg must target the same numeric field",h.USAGE);let s=o??i;if(!t.includes(s))throw new p(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,h.USAGE);return{field:s,sum:o!==void 0,avg:i!==void 0}}function oi(e){let t=e?.trim()??"status";if(t.length===0)throw new p("--group-by requires at least one field name",h.USAGE);let r=io(t);if(r.length===0)throw new p("--group-by requires a comma-separated list of fields",h.USAGE);for(let n of r)if(!ei.includes(n))throw new p(`Aggregate group fields must be one of ${ei.join("|")}; received "${n}"`,h.USAGE);return r}function ii(e){let t=[...new Set(e.map(r=>r.trim().toLowerCase()).filter(r=>r.length>0))].sort((r,n)=>r.localeCompare(n));return t.length===0?null:t.join(",")}function si(e,t){switch(e){case"parent":return t.parent??null;case"type":return t.type;case"priority":return t.priority;case"status":return t.status;case"assignee":return t.assignee??null;case"tags":return ii(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function ai(e,t){let r=e??null,n=t??null;return r===n?0:r===null?1:n===null?-1:typeof r=="number"&&typeof n=="number"?r-n:String(r).localeCompare(String(n))}function Ke(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var ra={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function ti(e,t){return t==null||t===""?ra[e]:String(t)}function na(e,t){return e.length===1?ti(e[0],t[e[0]]):e.map(r=>`${r}=${ti(r,t[r])}`).join(" | ")}function ci(e,t,r){for(let n of r){let o=ai(e.group[n],t.group[n]);if(o!==0)return o}return 0}function di(e,t){let n=e[t];if(typeof n=="number"&&Number.isFinite(n))return n;if(typeof n=="string"){let o=n.trim();if(o.length===0)return null;let i=Number(o);if(Number.isFinite(i))return i}return null}function li(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Dt(e,t,r){let n=Jr(String(t),r)??t;if(n===r.open_status){e.open_count+=1;return}if(n==="in_progress"||r.active_statuses.has(n)&&n!==r.open_status){e.in_progress_count+=1;return}if(r.terminal_done_statuses.has(n)||n===r.close_status){e.closed_count+=1;return}e.other_count+=1}function oa(e,t){return{row:{group:e,count:1},numeric_count:t===null?0:1,numeric_sum:t??0,null_count:t===null?1:0,open_count:0,in_progress_count:0,closed_count:0,other_count:0}}function ia(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function sa(e){e.accumulator.row.count+=1,e.includeCompletion&&Dt(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&ia(e.accumulator,e.numericValue)}function aa(e,t,r,n){for(let o of t){let i=Ke(r,o),s=e.get(i);if(s){sa({...n,accumulator:s});continue}let a=oa(o,n.numericValue);n.includeCompletion&&Dt(a,n.item.status,n.statusRegistry),e.set(i,a)}}function ca(e,t){let r={};for(let n of e)r[n]=si(n,t);return r}function da(e,t,r){let n=[ca(e,t)];if(r==="tuple")return n;for(let o of e){let i=t[o];if(!Array.isArray(i))continue;let s=[...new Set(i.map(a=>a.trim().toLowerCase()).filter(Boolean))].sort();s.length!==0&&(n=n.flatMap(a=>s.map(d=>({...a,[o]:d}))))}return n}function la(e,t,r,n){let o={...e.row,group_label:na(t,e.row.group)};return r&&(o.open=e.open_count,o.in_progress=e.in_progress_count,o.closed=e.closed_count,o.other=e.other_count,o.completion_pct=li(e.closed_count,e.row.count)),n!==null&&(o.null_count=e.null_count,n.sum&&(o.sum=e.numeric_sum),n.avg&&(o.avg=e.numeric_count===0?null:e.numeric_sum/e.numeric_count)),o}function ua(e){return{group_by:e.groupBy,set_mode:e.setMode,count:!0,completion:e.includeCompletion,include_unparented:e.includeUnparented,status:e.status?.[0]??null,status_values:e.status,type:e.options.type??null,tag:e.options.tag??null,priority:e.options.priority??null,deadline_before:e.options.deadlineBefore??null,deadline_after:e.options.deadlineAfter??null,assignee:e.options.assignee??null,assignee_filter:e.options.assigneeFilter??null,parent:e.options.parent??null,sprint:e.options.sprint??null,release:e.options.release??null,...e.numericAggregation!==null?{sum:e.options.sum??null,avg:e.options.avg??null,numeric_field:e.numericAggregation.field}:{}}}async function ru(e,t){if(e.count===!1)throw new p("Aggregate grouped counts are always enabled; omit count=false.",h.USAGE);let r=k(process.cwd(),t.path),n=await P(r),o=N(n.schema),i=["estimate","estimated_minutes","priority",...Z(n.schema).definitions.filter(b=>b.type==="number").map(b=>b.metadata_key)],s=oi(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new p("Aggregate --set-mode must be element or tuple",h.USAGE);let d=ri(e.status,o),l=ni(e,[...new Set(i)].sort((b,E)=>b.localeCompare(E))),c=e.completion===!0,u=e.includeUnparented===!0,m=await ze(void 0,{...Zo(e),status:e.status,noTruncate:!0,strictRead:!0},t),f=new Map,_=0,y=0,g=0;for(let b of m.items){let E=b;if(s.includes("parent")&&E.parent===void 0&&!u){_+=1;continue}let X=l===null?null:di(E,l.field),R=da(s,E,a);aa(f,R,s,{item:E,statusRegistry:o,includeCompletion:c,numericAggregation:l,numericValue:X}),g+=R.length,y+=1}let w=[...f.values()].map(b=>la(b,s,c,l)).sort((b,E)=>ci(b,E,s)),v=m.warnings&&m.warnings.length>0?m.warnings:void 0;return{...ma(w,s,e),count:w.length,totals:{items_considered:m.items.length,items_grouped:y,items_skipped_unparented:_,group_memberships:g},filters:ua({groupBy:s,setMode:a,includeCompletion:c,includeUnparented:u,status:d,options:e,numericAggregation:l}),now:S(),...v?{warnings:v}:{}}}function ma(e,t,r){let n=Io(r.limit,"limit")??50,o=r.after===void 0?-1:e.findIndex(a=>Ke(t,a.group)===r.after);if(r.after!==void 0&&o<0)throw new p("Aggregate --after cursor is absent from the current grouping; restart without --after.",h.USAGE);let i=e.slice(o+1,o+1+n),s=o+1+i.length<e.length;return{groups:i,returned_count:i.length,truncated:s,next_after:s?Ke(t,i.at(-1).group):null}}var nu={buildGroupKey:Ke,compareAggregateRows:ci,compareNullableGroupValue:ai,completionPct:li,normalizeTagGroupValue:ii,parseGroupBy:oi,parseNumericAggregation:ni,parseStatus:ri,readNumericAggregateValue:di,resolveGroupValue:si,updateCompletionCounts:Dt};var ui=1e6,mi=20;function fi(e,t,r,n=mi){if(!Number.isSafeInteger(n)||n<0)throw new p("Child projection sample limit must be a non-negative integer.",h.USAGE);let o=e.trim().toLowerCase(),i={},s=[],a=0;for(let g of t){if(a+=1,a>ui)throw new p(`Child projection exceeded the ${ui.toLocaleString("en-US")} item safety bound.`,h.GENERIC_FAILURE,{code:"child_projection_item_bound_exceeded",required:"Use an indexed or parent-filtered metadata source.",why:"Unbounded graph scans can exhaust memory in universal project stores.",nextSteps:["Build the derived item index, then retry the parent read."]});s.push(g)}let d=new Map(s.map(g=>[g.id.trim().toLowerCase(),g])),l=So(bo(s,Eo())),c=new Set(l.children_by_parent.get(o)??[]);for(let g of s)g.parent?.trim().toLowerCase()===o&&c.add(g.id.trim().toLowerCase());let u=[...c].map(g=>d.get(g)),m=0;for(let g of u){let w=g.status.trim().toLowerCase();i[w]=(i[w]??0)+1,de(w,r)||(m+=1)}u.sort((g,w)=>g.id.localeCompare(w.id));let f=u.slice(0,n).map(g=>({id:g.id,title:g.title,type:g.type,status:g.status,priority:g.priority})),_=u.length>f.length,y=n===0?mi:n;return{count:u.length,active:m,by_status:Object.fromEntries(Object.entries(i).sort(([g],[w])=>g.localeCompare(w))),sample:f,sample_limit:n,truncated:_,next_offset:_?f.length:null,continuation:_?`pm list --status all --parent ${e} --offset ${f.length} --limit ${y}`:null,scanned:a}}var fa=new Set(["event","meeting","reminder"]);function ha(e){return fa.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Qe(e){if(!ha(e))return;let t=[...e.events??[]].sort((n,o)=>n.start_at.localeCompare(o.start_at)),r=t[0];return{deadline:e.deadline??null,start_at:r?.start_at??null,end_at:r?.end_at??null,location:r?.location??null,reminders:[...e.reminders??[]],events:t}}var ga=new Set(["epic","feature","milestone","plan"]),ya=new Set(Object.keys(Ur).map(e=>e.toLowerCase()));function Ut(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(r=>[r,e[r]?.length??0]))}function _a(e,t,r,n,o){let i=Ut(e);return[...t.length>0?["body"]:[],...Object.entries(i).flatMap(([s,a])=>a>0?[s]:[]),...i.files+i.tests+i.docs>0?["linked"]:[],...r===void 0?["children"]:r.count>0?["children"]:[],...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Qe(e)?["schedule"]:[],...n&&bt(e).length>0?["blockers"]:[],...!o.full&&e.dependencies?.some(({id:s,kind:a,...d})=>Object.values(d).some(l=>l!==void 0))?["dependency_provenance"]:[]]}function pi(e){let t=e.trim().toLowerCase();return t.length>0&&(ga.has(t)||!ya.has(t))}function hi(e){return{ts:e.ts,author:e.author,message:e.message??null}}function wa(e,t){let r=e?.trim(),n=r&&r.length>0?r:null,o=[...t].reverse().find(s=>s.op==="claim"),i=[...t].reverse().find(s=>s.op==="release");return{claimed:n!==null,assignee:n,last_claim:o?hi(o):null,last_release:i?hi(i):null}}function va(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(St.includes(t))return t;throw new p("Get --depth must be one of brief|standard|deep|full",h.USAGE,{field:"depth",value:e,recovery:{allowed_values:[...xt]}})}function Ea(e,t,r){let n=Ut(e),o={...e};if(!r&&e.dependencies!==void 0&&(o.dependencies=e.dependencies.map(({id:_,kind:y})=>({id:_,kind:y}))),t==="deep")return{...o,comments:e.comments??[],notes:e.notes??[],learnings:e.learnings??[],files:e.files??[],tests:e.tests??[],docs:e.docs??[],reminders:e.reminders??[],events:e.events??[],notes_count:n.notes,tests_count:n.tests,collection_counts:n};let{comments:i,notes:s,learnings:a,files:d,tests:l,docs:c,reminders:u,events:m,...f}=o;return{...f,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:n}}function ba(e){if(e===void 0)return null;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new p("Get --fields requires a comma-separated list of field names",h.USAGE);return t}function ie(e){return e.startsWith("item.")?e.slice(5):e}function Sa(e,t,r){if(e===null)return;let n=Rt(t),o=new Set(n),i=e.filter(s=>{let a=ie(s);return!o.has(s)&&!o.has(a)});if(i.length>0){let s=["get",r,"--fields",e.filter(a=>!i.includes(a)).join(",")||"id,title,status"];throw new p(`Unknown get --fields value(s): ${i.join(", ")}`,h.USAGE,{code:"unknown_field_projection",examples:["pm get <id> --fields id,title,status,type,updated_at","pm get <id> --fields id,title,claim_state","pm get <id> --fields id,title,body,linked.files"],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}var xa=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function Ra(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:xa.has(r)?[]:void 0}function ka(e,t){if(e==="item.item_hash")return!1;let r=t.indexOf(".");return r===-1?gn.has(t):yn.has(t.slice(0,r))}function Ia(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:Ut(e)},o={id:e.id};for(let i of t){let s=ie(i);ka(i,s)||(o[s]=Ra(r,n,s))}return o}function Ye(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function oe(e,t){return e.some(r=>{let n=ie(r);return n===t||n.startsWith(`${t}.`)})}function Aa(e,t){if(e.full&&(e.fields!==void 0||e.depth!==void 0))throw new p("Get projection options are mutually exclusive; remove the extra projection flag and retry.",h.USAGE,{code:"projection_options_mutually_exclusive",flag:"--full",recovery:{suggested_retry:J(["get",t,"--full"]),suggested_retry_args:["get",t,"--full"]}});if(e.tree!==!0&&e.treeDepth!==void 0)throw new p("Get --tree-depth requires --tree",h.USAGE);if(e.at!==void 0&&e.tree===!0)throw new p("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",h.USAGE);return{depth:e.full?"deep":va(e.depth),full:e.full===!0||e.depth?.trim().toLowerCase()==="full",treeDepth:e.tree===!0?ho(e.treeDepth,"--tree-depth"):void 0,fields:ba(e.fields),fieldProjection:e.fields!==void 0}}async function Ca(e,t,r){let n=k(process.cwd(),t.path);await O(n);let o=await P(n),i=D(o,x());if(r!==void 0){let d=await lo(e,r,{pmRoot:t.path});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:d.document.metadata.id,metadata:d.document.metadata,body:d.document.body,historical:d}}let s=await qe(n,e,o.id_prefix,o.item_format,i.type_to_folder);if(!s)throw await Yn(n,e,o.id_prefix,i.type_to_folder);let a=await De(s,{schema:o.schema});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:s.id,metadata:a.document.metadata,body:a.document.body}}function Ma(e,t,r,n){let o=[...Z(t.schema).definitions.map(i=>i.metadata_key),...$(x())];if(Sa(e,o,n),r&&oe(e??[],"children"))throw new p("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",h.USAGE);if(r&&oe(e??[],"blockers"))throw new p("Get --at cannot project current blocker statuses; read the current item with --fields blockers instead.",h.USAGE)}function Nt(e){let{fieldProjection:t,depth:r,fields:n,field:o}=e;return t?o==="body"||o==="linked"?Ye(n,o):oe(n,o):r!=="brief"}async function Fa(e,t){if(!t)return;let r=xe(e.pmRoot,e.locatedId),n=await le(r,e.locatedId);return wa(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function Ta(e,t,r){t.historical===void 0&&(r.fieldProjection&&!r.fields.includes("item_hash")||(e.item_hash=Sn({metadata:t.metadata,body:t.body})))}var gi=["files","tests","docs"],Pa=["claimed","assignee","last_claim","last_release"];function Ha(e,t,r,n){let o=gi.filter(i=>n||Ye(r,`linked.${i}`));o.length!==0&&(e.linked=Object.fromEntries(o.map(i=>[i,t.metadata[i]??[]])))}function Oa(e,t){return t===null||Ye(t,"claim_state")?e:Object.fromEntries(Pa.filter(r=>t.some(n=>ie(n)===`claim_state.${r}`)).map(r=>[r,e[r]]))}var La={linked:new Set(gi),schedule:new Set(["deadline","reminders","events"]),claim_state:new Set(["assignee"])};function $t(e,t,r){let n=e.map(ie);if(n.includes(t))return[];let o=`${t}.`;if(!n.some(s=>s.startsWith(o)))return[];let i=La[t];return Object.entries(r).flatMap(([s,a])=>!n.includes(`${o}${s}`)&&!(i.has(s)&&n.includes(s))&&ja(a)?[`${o}${s}`]:[])}function ja(e){return e!=null&&e!==!1&&!(Array.isArray(e)&&e.length===0)}function qa(e,t,r){return[...$t(t,"linked",{files:e.metadata.files,tests:e.metadata.tests,docs:e.metadata.docs}),...r?$t(t,"claim_state",r):[],...$t(t,"schedule",Qe(e.metadata)??{})]}async function Da(e,t){if(!t)return;let r=N(e.settings.schema),n=await Ne(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return fi(e.locatedId,n,r)}async function Na(e,t,r){if(t.historical!==void 0||!(r.fieldProjection?oe(r.fields,"blockers"):r.depth!=="brief")||bt(t.metadata).length===0)return;let n=await so({pmRoot:t.pmRoot,settings:t.settings,typeToFolder:t.typeToFolder,metadata:t.metadata});e.blockers={scope:"declared",open:n.filter(o=>!o.resolved).map(({resolved:o,...i})=>i),closed_count:n.filter(o=>o.resolved).length},!r.fieldProjection&&!r.full&&delete e.item.blocked_by}function $a(e,t,r,n){if(!n)return;let o=Qe(t.metadata);if(o){if(r===null||Ye(r,"schedule")){e.schedule=o;return}e.schedule=Object.fromEntries(Object.entries(o).filter(([i])=>r.some(s=>ie(s)===`schedule.${i}`)))}}async function Ua(e,t,r,n){if(t.tree!==!0)return;let o=await ze(void 0,{parent:e.locatedId,tree:!0,treeDepth:r===void 0?void 0:String(r),full:!0},n);return{root_id:e.locatedId,root_title:e.metadata.title,depth_limit:r??null,count:o.count,items:o.items.map(i=>i)}}async function Cu(e,t,r={}){let n=Aa(r,e),o=await Ca(e,t,r.at);Ma(n.fields,o.settings,o.historical!==void 0,o.locatedId);let i=Nt({...n,field:"body"}),s=Nt({...n,field:"linked"}),a=Nt({...n,field:"claim_state"}),d=o.historical===void 0&&(n.fieldProjection?oe(n.fields,"children"):n.depth==="deep"&&(n.full||pi(o.metadata.type))),l=n.fieldProjection?oe(n.fields,"schedule"):n.depth!=="brief",c=await Fa(o,a),u={item:n.fieldProjection?Ia(o.metadata,n.fields):Ea(o.metadata,n.depth,n.full)};i&&(u.item.body=o.body),Ta(u,o,n),Ha(u,o,n.fields,s),c&&(u.claim_state=Oa(c,n.fields)),$a(u,o,n.fields,l),await Na(u,o,n);let m=await Da(o,d);m!==void 0&&(u.children=m);let f=await Ua(o,r,n.treeDepth,t);if(f!==void 0&&(u.tree=f),o.historical&&(u.reconstructed=!0,u.as_of_version=o.historical.as_of_version,u.as_of_timestamp=o.historical.as_of_timestamp),o.historical===void 0)try{await pn({pmRoot:o.pmRoot,author:Fe(void 0,o.settings.author_default),itemIds:[o.locatedId],intent:"get"})}catch{}return dn(u,n.fieldProjection?qa(o,n.fields,c):_a(o.metadata,o.body,m,o.historical===void 0,n)),u}var Mu={shouldAutoIncludeGetChildren:pi};function Ga(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function Ba(e,t){return e.map(({entry:r,version:n})=>{let o=new Set,i=on(r.patch);for(let s of i)o.add(wt(s.path)),s.from&&o.add(wt(s.from));return{index:n,...t?{version:t.offset===null?null:t.offset+n}:{},ts:r.ts,op:r.op,author:r.author,patch_ops:i.length,changed_fields:[...o].sort((s,a)=>s.localeCompare(a))}})}function Wa(e){if(e[0]?.op!=="history_compact_baseline")return;let t=H(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function za(e,t){let r=k(process.cwd(),t.path);await O(r);let n=await P(r),o=D(n,x()),i=e.trim()===Pe,s=i?Pe:qn(e,n.id_prefix),a=await qe(r,s,n.id_prefix,n.item_format,o.type_to_folder),d=a?.id??s,l=i?Ln(r):xe(r,d);if(!a&&!await Se(l))throw new p(`Item ${e} not found`,h.NOT_FOUND);return a&&await Te({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:l,located:a,resolvedId:d,settings:n}}function Va(e){let{resolvedId:t,selectedHistory:r,options:n,limit:o,addressing:i,vocabulary:s,total:a}=e,d=n.compact===!0,l=(n.order??(d||n.provenance===!0?"newest_first":"oldest_first"))==="newest_first",c=l?[...r].reverse():r,u=c.map(({entry:w})=>w),m=d?Ba(c,i):void 0,f=n.provenance===!0?c.map(({entry:w,durableVersion:v})=>Fo(w,s,{itemId:t,version:v})):void 0,_=n.provenance===!0?"provenance":d?"compact":"full",y={compact:{compact_history:m},provenance:{provenance_history:f},full:{history:u}}[_];return{id:t,...y,compact:d,projection:{mode:_,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[_]},omission_receipt:ln("history",_),count:u.length,total:a,order:l?"newest_first":"oldest_first",limit:o??null,version_addressing:i}}async function Nu(e,t,r){if(t.order!==void 0&&t.order!=="oldest_first"&&t.order!=="newest_first")throw new p("--order must be oldest_first or newest_first",h.USAGE);let n=Oe(t.limit),{historyPath:o,located:i,resolvedId:s,settings:a}=await za(e,r),d=await le(o,s),l=Wa(d),c=a.agent_identity.identity_vocabulary,u=Mo(a.agent_identity.harness_signals),m=To({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},c,u),f=Ka(d).filter(({entry:g})=>m(g)),_=Ga(f,n),y=Va({resolvedId:s,selectedHistory:_,options:t,limit:n,addressing:l,vocabulary:c,total:f.length});if(t.provenanceSummary===!0&&(y.provenance_summary=Po(f.map(({entry:g})=>g),c,u)),t.diff||t.field!==void 0){let g=new Set(_.map(({version:w})=>w));y.diff=On(d,{windowStartIndex:(_[0]?.version??d.length+1)-1,field:t.field}).filter(w=>g.has(w.index)),y.order==="newest_first"&&y.diff.reverse()}if(t.verify){let g=i?(await De(i,{schema:a.schema})).document:void 0;if(y.verification=co(d,g),s===Pe&&y.verification.ok){let w=await jn(k(process.cwd(),r.path));y.verification={...y.verification,ok:w.ok,errors:w.ok?y.verification.errors:[...y.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:w.ok,workspace_state_mismatches:w.mismatched_documents,workspace_state_missing:w.missing_documents,workspace_state_unreadable:w.unreadable_documents}}}return y}function Ka(e){let t=H(e,!0);return e.map((r,n)=>({entry:r,version:n+1,durableVersion:t===null?void 0:t+n+1}))}function Qa(e){if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(t!=="keyword"&&t!=="semantic"&&t!=="hybrid")throw new p("Search mode must be one of keyword|semantic|hybrid",h.USAGE);return t}function Xe(e){return e===!0}function yi(e){return Kr(e,0,1)??void 0}function _i(e){if(e===void 0)return"or";let t=e.trim().toLowerCase();if(t!=="and"&&t!=="or"&&t!=="exact")throw new p("Search --match-mode must be one of and|or|exact",h.USAGE);return t}function wi(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(t)||t<0)throw new p("Search --min-score must be a finite number >= 0",h.USAGE);return t}function Q(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return mt(r,new Date,t)}function A(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Gt(e,t){if(e!==void 0)return mt(e,new Date,t)}function Ya(e){if(e===void 0)return;let t=e.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)throw new p("Search --fields requires a comma-separated list of field names",h.USAGE);return[...new Set(t)]}function Je(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,o=Ya(e.fields);if(Number(r)+Number(n)+ +(o!==void 0)>1)throw new p("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",h.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:J(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...uo]}:n?{mode:"full",fields:[]}:o?{mode:"fields",fields:o}:{mode:"full",fields:[]}}function Bt(e,t,r="<query>"){if(e.mode!=="fields")return;let n=mo([...t.definitions.flatMap(s=>[s.key,s.metadata_key]),...$(x())]),o=new Set(n),i=e.fields.filter(s=>{let a=s.trim();return!o.has(a)});if(i.length>0){let s=["search",r,"--fields",e.fields.filter(a=>!i.includes(a)).join(",")||"id,title,status,score"];throw new p(`Unknown search --fields value(s): ${i.join(", ")}`,h.USAGE,{code:"unknown_field_projection",examples:["pm search <query> --fields id,title,status,score","pm search <query> --fields id,title,item.description,matched_fields"],nextSteps:["Use item.<field> for explicit item metadata fields, or run pm search --help for projection examples."],recovery:{allowed_values:n,suggested_retry:J(s),suggested_retry_args:s}})}}function Ze(e){let t=A(e);if(!t)throw new p("Search query must not be empty",h.USAGE);return t.split(/\s+/u).filter(Boolean)}function Wt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var Xa=["auto","keyword","semantic","hybrid"];function Ja(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return Xa.includes(r)?r:"auto"}function zt(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:Qa(e.requested),source:"explicit"};let t=Ja(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Vt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function Kt(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function Qt(e){let t={title_exact_bonus:10,title_weight:48,description_weight:5,tags_weight:6,status_weight:2,body_weight:1,comments_weight:1,notes_weight:1,learnings_weight:1,reminders_weight:2,events_weight:2,dependencies_weight:3,linked_content_weight:1},r=e.search?.tuning;if(!r)return t;let n=(o,i)=>typeof o=="number"&&Number.isFinite(o)&&o>=0?o:i;return{title_exact_bonus:n(r.title_exact_bonus,t.title_exact_bonus),title_weight:n(r.title_weight,t.title_weight),description_weight:n(r.description_weight,t.description_weight),tags_weight:n(r.tags_weight,t.tags_weight),status_weight:n(r.status_weight,t.status_weight),body_weight:n(r.body_weight,t.body_weight),comments_weight:n(r.comments_weight,t.comments_weight),notes_weight:n(r.notes_weight,t.notes_weight),learnings_weight:n(r.learnings_weight,t.learnings_weight),reminders_weight:n(r.reminders_weight,t.reminders_weight),events_weight:n(r.events_weight,t.events_weight),dependencies_weight:n(r.dependencies_weight,t.dependencies_weight),linked_content_weight:n(r.linked_content_weight,t.linked_content_weight)}}import Za from"node:path";function Yt(e){return mn("search",{pmRoot:e.pmRoot===void 0?void 0:Za.resolve(e.pmRoot),query:e.query.trim(),mode:e.mode,options:un(e.searchOptions,fo)})}function vi(e){let t=hn(e.sorted,{cursor:e.searchOptions.after,fingerprint:Yt(e),limit:e.limit,readId:r=>r.item.id});return{limited:t.rows,pageExtras:{applied_limit:e.limit,...t.has_more?{has_more:!0,truncated:!0}:{},...t.next_cursor?{next_cursor:t.next_cursor}:{}}}}function Ei(e){if(typeof e!="string")return!1;let t=e.split(",").map(r=>r.trim().toLowerCase()).filter(Boolean);return t.length===1&&t[0]==="all"}var ec=[{optionKey:"status",summaryKey:"status",normalize:e=>Ei(e)?"all":e},{optionKey:"type",summaryKey:"type"},{optionKey:"tag",summaryKey:"tag"},{optionKey:"priority",summaryKey:"priority"},{optionKey:"deadlineBefore",summaryKey:"deadline_before"},{optionKey:"deadlineAfter",summaryKey:"deadline_after"},{optionKey:"updatedAfter",summaryKey:"updated_after"},{optionKey:"updatedBefore",summaryKey:"updated_before"},{optionKey:"createdAfter",summaryKey:"created_after"},{optionKey:"createdBefore",summaryKey:"created_before"},{optionKey:"assignee",summaryKey:"assignee"},{optionKey:"sprint",summaryKey:"sprint"},{optionKey:"release",summaryKey:"release"},{optionKey:"parent",summaryKey:"parent"}];function Y(e){let{mode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:d,runtimeFieldFilters:l}=e,c={};return ko(c,n,ec),Object.assign(c,It(n)),Object.assign(c,kt(n)),r!==void 0&&r!=="or"&&(c.match_mode=r),o&&(c.include_linked=!0),i&&(c.title_exact=!0),s&&(c.phrase_exact=!0),a>0&&(c.score_threshold=a),t==="hybrid"&&n.semanticWeight!==void 0&&(c.hybrid_semantic_weight=d),n.limit!==void 0&&(c.limit=n.limit),l&&Object.keys(l).length>0&&(c.runtime_filters=l),c}function et(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:d,queryExpansion:l,rerank:c,runtimeFieldFilters:u}=e,m=f=>f??null;return{mode:t,match_mode:r,status:n.status===void 0||Ei(n.status)?"all":n.status,type:m(n.type),tag:m(n.tag),priority:m(n.priority),deadline_before:m(n.deadlineBefore),deadline_after:m(n.deadlineAfter),updated_after:m(n.updatedAfter),updated_before:m(n.updatedBefore),created_after:m(n.createdAfter),created_before:m(n.createdBefore),assignee:m(n.assignee),sprint:m(n.sprint),release:m(n.release),parent:m(n.parent),...It(n),...kt(n),include_linked:o,title_exact:i,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?d:null,query_expansion_enabled:l.enabled,query_expansion_provider:l.provider,rerank_enabled:c.enabled,rerank_model:c.model,rerank_top_k:c.top_k,limit:m(n.limit),runtime_filters:u}}var tc=1.2,rc=.75;function Xt(e){return ee(e)}function nc(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function Si(e){let t=[],r=new Map,n=0;for(let i of e){let s=Xt(i.text),a=nc(s);n+=s.length;for(let d of a.keys())r.set(d,(r.get(d)??0)+1);t.push({id:i.id,termFrequencies:a,length:s.length})}let o=t.length;return{documents:t,documentFrequency:r,documentCount:o,averageDocumentLength:o>0?n/o:0}}function oc(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function xi(e,t,r){let n=new Map;if(e.documentCount===0||e.averageDocumentLength===0)return n;let o=[...new Set(t.filter(s=>s.length>0))];if(o.length===0)return n;let i=new Map;for(let s of o){let a=e.documentFrequency.get(s);a!==void 0&&i.set(s,oc(e.documentCount,a))}if(i.size===0)return n;for(let s of e.documents){let a=0;for(let[d,l]of i){let c=s.termFrequencies.get(d);if(c===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,m=c+r.k1*u;a+=l*(c*(r.k1+1)/m)}a>0&&n.set(s.id,a)}return n}function bi(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function Ri(e){let t=r=>typeof r=="string"?[r]:typeof r=="number"?[String(r)]:Array.isArray(r)?r.flatMap(t):typeof r=="object"&&r!==null?Object.values(r).flatMap(t):[];return t(Object.values(e)).join(" ")}function ki(e){let t=e?.search?.bm25;return{k1:bi(t?.k1,tc,0,1e3),b:bi(t?.b,rc,0,1)}}var Jt=4,ic=20,sc=200,ac=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function Zt(e,t){let r=[],n=new Set;for(let o of e){let i=o.trim().replaceAll(/\s+/g," ");if(i.length===0)continue;let s=i.toLowerCase();if(!n.has(s)&&(n.add(s),r.push(i),r.length>=t))break}return r}function cc(e){let t=e.toLowerCase();return t.length>4&&t.endsWith("ies")?`${t.slice(0,-3)}y`:t.length>4&&(t.endsWith("ches")||t.endsWith("shes")||t.endsWith("xes")||t.endsWith("zes")||t.endsWith("sses"))?t.slice(0,-2):t.length>3&&t.endsWith("s")&&!t.endsWith("ss")&&!t.endsWith("us")&&!t.endsWith("is")&&!t.endsWith("as")?t.slice(0,-1):t}function dc(e){let t=e.toLowerCase();return t.length>2&&(!t.endsWith("s")||t.endsWith("ss"))?t.endsWith("y")&&!/[aeiou]y$/u.test(t)?`${t.slice(0,-1)}ies`:t.endsWith("ch")||t.endsWith("sh")||t.endsWith("x")||t.endsWith("z")||t.endsWith("ss")?`${t}es`:`${t}s`:t}function Ii(e,t=Jt){let r=e.trim().replaceAll(/\s+/g," ");if(r.length===0)return[];let n=ee(r);if(n.length===0)return[r];let o=n.filter(a=>!ac.has(a.toLowerCase())),i=n.map(a=>cc(a)),s=o.map(a=>dc(a));return Zt([r,n.join(" "),o.join(" "),i.join(" "),s.join(" ")],Math.max(1,t))}function Ai(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?Zt(t.filter(r=>typeof r=="string"),Jt):[]}function Ci(e,t,r){return Zt([...e,...t],Math.max(1,r))}function Mi(e,t){let n=e.search?.query_expansion,o=ce(n?.provider);return{enabled:n?.enabled===!0,provider:o??t,max_queries:Jt}}function Fi(e,t){let n=e.search?.rerank,o=ce(n?.model),s=ke(n?.top_k)??ic;return{enabled:n?.enabled===!0,model:o??t,top_k:Math.min(sc,s)}}function Ti(e){let t=Array.isArray(e)?e:e?.hits;if(!Array.isArray(t))return[];let r=new Map;for(let o of t){if(typeof o!="object"||o===null)continue;let i=ce(o.id),s=o.score;if(!i||typeof s!="number"||!Number.isFinite(s))continue;let a=r.get(i);(a===void 0||s>a)&&r.set(i,s)}let n=[...r.entries()].map(([o,i])=>({id:o,score:i}));return n.sort((o,i)=>o.score!==i.score?i.score-o.score:o.id.localeCompare(i.id)),n}function lc(e,t){let r=e.length,n=0;for(let o=0;o<r;o+=1)n+=e[o]*t[o];return n}function Pi(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function uc(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=lc(e,t),o=Pi(t),i=r*o;return!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(i)||i===0?0:Math.max(-1,Math.min(1,n/i))}async function Hi(e,t,r,n,o){if(n.length===0)return new Map;let i=ce(t)??e.model,s=i===e.model?e:{...e,model:i},a=[r.trim(),...n.map(m=>m.text)],d=await $e(s,a,o?{timeout_ms:o}:{}),l=d[0];if(!l)return new Map;let c=Pi(l),u=new Map;for(let m=0;m<n.length;m+=1){let f=n[m],_=d[m+1];if(!_)continue;let y=uc(l,_,c);u.set(f.id,Math.max(0,Math.min(1,(y+1)/2)))}return u}function se(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function j(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function we(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function er(e){let t=e.metadata;return[t.title,t.description,t.status,se(t.tags).join(" "),e.body,j(t.comments).map(r=>r.text).join(" "),j(t.notes).map(r=>r.text).join(" "),j(t.learnings).map(r=>r.text).join(" "),Ue(t).join(" "),Ge(t).join(" "),we(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Be(t)]}function tr(e,t){return er(e).some(r=>A(r).includes(t))}function rr(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&A(n.metadata.title)!==t||r.phraseExact&&!tr(n,t)))}function mc(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new p('--assignee no longer accepts "none" or "null".',h.USAGE)}function fc(e,t,r){let n=ge(e.assignee,{label:"--assignee"});mc(n);let o=xo(e),i=Ro(e);return{typeFilter:po(e.type,t),tagFilter:ge(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:go(e.priority),deadlineBefore:Gt(e.deadlineBefore,"deadline-before"),deadlineAfter:Gt(e.deadlineAfter,"deadline-after"),updatedAfter:Q(e.updatedAfter,"updated-after"),updatedBefore:Q(e.updatedBefore,"updated-before"),createdAfter:Q(e.createdAfter,"created-after"),createdBefore:Q(e.createdBefore,"created-before"),assigneeFilter:n,sprintFilter:ge(e.sprint,{label:"--sprint"}),releaseFilter:ge(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:o,missingMetadataActive:yo(o),contentFieldFilters:i,contentFiltersActive:wo(i)}}function hc(e,t){return pc(e,t)&&Yr(e,t)&&gc(e,t)}function pc(e,t){if(t.statusSet&&!t.statusSet.has(e.status)||t.typeFilter&&!t.typeFilter.has(e.type))return!1;let r=t.tagFilter;return!(r&&!se(e.tags).some(n=>r.has(n))||t.priorityFilter!==void 0&&!t.priorityFilter.has(e.priority))}function gc(e,t){return!(t.assigneeFilter!==void 0&&(e.assignee===void 0||!t.assigneeFilter.has(e.assignee))||t.sprintFilter!==void 0&&(e.sprint===void 0||!t.sprintFilter.has(e.sprint))||t.releaseFilter!==void 0&&(e.release===void 0||!t.releaseFilter.has(e.release))||t.parentFilter!==void 0&&e.parent!==t.parentFilter)}function yc(e,t,r,n){let o=e.metadata;return!(!hc(o,t)||!Nn(o,r)||t.missingMetadataActive&&!_o(o,t.missingMetadataFilters,n)||t.contentFiltersActive&&!vo(o,t.contentFieldFilters))}function nr(e,t,r,n,o,i){let s=fc(t,r,o);return e.filter(a=>yc(a,s,n,i))}var _c=2,wc=120,vc=6,Ec=40,bc=1e3,Sc=900,xc="\xAB",Rc="\xBB",Oi=60;function tt(e,t){let r=0,n=0;for(;;){let o=e.indexOf(t,n);if(o<0)return r;r+=1,n=o+t.length}}var Li=[{name:"title",weightKey:"title_weight",value:e=>e.metadata.title},{name:"description",weightKey:"description_weight",value:e=>e.metadata.description},{name:"tags",weightKey:"tags_weight",value:e=>se(e.metadata.tags).join(" ")},{name:"status",weightKey:"status_weight",value:e=>typeof e.metadata.status=="string"?e.metadata.status:""},{name:"body",weightKey:"body_weight",value:e=>e.body},{name:"comments",weightKey:"comments_weight",value:e=>j(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>j(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>j(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>Ue(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>Ge(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>we(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Be(e.metadata)}],kc=new Map(Li.map(e=>[e.name,e]));function or(e,t){let r=t.filter(o=>o.length>0).sort((o,i)=>i.length-o.length).map(o=>o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"));if(r.length===0)return e;let n=new RegExp(r.join("|"),"gi");return e.replace(n,o=>`${xc}${o}${Rc}`)}function ir(e,t){if(e.length===0)return null;let r=e.toLowerCase(),n=-1,o=0;for(let c of t){if(c.length===0)continue;let u=r.indexOf(c);u>=0&&(n<0||u<n)&&(n=u,o=c.length)}if(n<0)return null;let i=Math.max(0,n-Oi),s=Math.min(e.length,n+o+Oi),a=or(e.slice(i,s),t),d=i>0?"\u2026":"",l=s<e.length?"\u2026":"";return`${d}${a}${l}`}function rt(e,t,r){let n=[];for(let o of t){let i=kc.get(o);if(i===void 0)continue;let s=ir(i.value(e),r);s!==null&&n.push({field:o,snippet:s})}return n}function Ic(e,t,r){return[...Li.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function Ac(e,t,r){let n=A(e.id),o=typeof r=="string"?r.trim().toLowerCase():"",i=A(o),s=i.length>0&&n.startsWith(i)?n.slice(i.length).trim():n;return t!==n&&t!==s?null:{item:e,score:t===n?bc:Sc,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function Cc(e,t,r,n,o){for(let i of e){let s=t.get(i)??0;s>0&&(o.score+=s*n.title_exact_bonus,o.matched.add("title"),o.matchedTokens.add(i));for(let a of r){let d=tt(a.value.toLowerCase(),i);d>0&&(o.score+=d*a.weight,o.matched.add(a.name),o.matchedTokens.add(i))}}}function Mc(e,t,r,n){A(e.title)===t&&(n.score+=wc,n.matched.add("title"));for(let i of r){let s=tt(A(i.value),t);s>0&&(n.score+=s*i.weight*vc,n.matched.add(i.name))}}function sr(e,t,r,n,o,i,s=!1){let a=e.metadata,d=Ac(a,r,i);if(d)return d;let l=new Map;for(let y of ee(a.title))l.set(y,(l.get(y)??0)+1);let c=Ic(e,n,o),u={score:0,matched:new Set,matchedTokens:new Set};Cc(t,l,c,o,u);let m=new Set(t),f=m.size>0&&u.matchedTokens.size===m.size;return s&&m.size>1&&f&&(u.score+=Ec),t.length>=_c&&r.includes(" ")&&Mc(a,r,c,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((y,g)=>y.localeCompare(g)),matched_all_terms:f}}function ar(e,t){return[...e].sort((r,n)=>{let o=n.score-r.score;if(o!==0)return o;let i=de(r.item.status,t),s=de(n.item.status,t);if(i!==s)return i?1:-1;let a=r.item.priority-n.item.priority;if(a!==0)return a;let d=Qr(n.item.updated_at,r.item.updated_at);return d!==0?d:r.item.id.localeCompare(n.item.id)})}function cr(e,t,r,n,o,i,s,a=!1){return sr(e,t,r,n?o.get(e.metadata.id)??"":"",i,s,a)}function ve(e){if(e.size===0)return new Map;let t=Number.POSITIVE_INFINITY,r=Number.NEGATIVE_INFINITY;for(let o of e.values())t=Math.min(t,o),r=Math.max(r,o);if(r===t)return new Map([...e.keys()].map(o=>[o,1]));let n=new Map;for(let[o,i]of e)n.set(o,(i-t)/(r-t));return n}function ot(e){let t=[],r=e;for(let n=0;n<5&&r&&typeof r=="object";n+=1){let o=r.code;typeof o=="string"&&t.push(o.toLowerCase()),r=r.cause}return t.join(" ")}function it(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=ot(e),n=`${t} ${r}`;return n.includes("timed out")||n.includes("timeout")||n.includes("etimedout")?"timeout":n.includes("econnrefused")||n.includes("connection refused")||n.includes("connect ")||n.includes("enotfound")||n.includes("eai_again")||n.includes("econnreset")||n.includes("fetch failed")?"connection":"error"}function dr(e,t){let r=it(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function ji(e){return e?.commands?.some(r=>r.command.trim()==="reindex")===!0?{command:"pm reindex --mode hybrid",args:["reindex","--mode","hybrid"]}:{command:"pm install search-advanced --project",args:["install","search-advanced","--project"],follow_up_command:"pm reindex --mode hybrid",follow_up_args:["reindex","--mode","hybrid"]}}async function lr(e,t,r){try{let n=await ro(e);n.warnings.length>0&&r.push(...n.warnings);let o=Ao(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(o.length===0)return;let i=ji(x());r.push(...qi(o.length,i)),process.stderr.write(`[pm] warning: ${o.length} item${o.length===1?" is":"s are"} new or modified since the last reindex and ${o.length===1?"is":"are"} NOT in the semantic index yet \u2014 run '${i.command}'${i.follow_up_command?`, then '${i.follow_up_command}'`:""}. (Write-time embedding is governed by search.mutation_refresh_policy; staleness means the embed was skipped, failed, or the backend was unreachable.)
3
3
  `)}catch{}}function qi(e,t){return[`vector_index_stale:${e}`,`vector_index_recovery:${t.args.join(" ")}`,...t.follow_up_args?[`vector_index_recovery_follow_up:${t.follow_up_args.join(" ")}`]:[]]}function st(e,t,r,n){if(!t.active)throw new p(`Search mode '${e}' requires a configured embedding provider in settings.providers.openai or settings.providers.ollama`,h.USAGE);if(!r.active&&!n)throw new p(`Search mode '${e}' requires a configured vector store in settings.vector_store.qdrant/settings.vector_store.lancedb or an extension adapter selected by settings.vector_store.adapter`,h.USAGE);return{provider:t.active,vectorStore:r.active??null}}var C=Re;function Ee(e){let t=x(),r=Fn(t,e);if(!r)return null;let n=r.runtime_definition??r.definition,o=n.query,i=n.queryExpansion??n.query_expansion,s=n.rerank,a=C(n.name)??C(r.definition.name)??e;if(!a)return null;let d={providerName:a,...typeof o=="function"?{query:o}:{},...typeof i=="function"?{queryExpansion:i}:{},...typeof s=="function"?{rerank:s}:{}};return!d.query&&!d.queryExpansion&&!d.rerank?null:d}function ur(e){let t=C(e.search?.provider),r=Ee(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function mr(e){let t=x(),r=C(e.vector_store?.adapter),n=Tn(t,r);if(!n)return null;let o=n.runtime_definition??n.definition,i=o.query;if(typeof i!="function")return null;let s=o.upsert;return{adapterName:C(o.name)??C(n.definition.name)??r??"extension",query:i,...typeof s=="function"?{upsert:s}:{}}}function fr(e,t,r){let n=Array.isArray(t)?t:t?.hits;if(!Array.isArray(n))throw new p(`Extension search provider "${e}" must return an array of hits or { hits: [...] }`,h.GENERIC_FAILURE);let o=new Set,i=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=C(s.id),d=s.score;if(!a||typeof d!="number"||!Number.isFinite(d)||o.has(a))continue;let l=r.get(a);if(!l)continue;let c=s.matched_fields,u=Array.isArray(c)&&c.every(m=>typeof m=="string")?[...new Set(c.map(m=>m.trim()).filter(m=>m.length>0))].sort((m,f)=>m.localeCompare(f)):[`provider:${e}`];o.add(a),i.push({item:l.metadata,score:d,matched_fields:u})}return i}function hr(e,t){let r=[],n=new Map;for(let o of e){if(n.has(o.id))continue;let i=t.get(o.id);i&&(n.set(o.id,o.score),r.push({item:i.metadata,score:o.score,matched_fields:["semantic"]}))}return{semanticHits:r,semanticScores:n}}function nt(e,t){let r=t.filter(l=>l.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(l=>l.item.id)),o=e.filter(l=>!n.has(l.item.id)),i=o.reduce((l,c)=>Math.max(l,c.score),0),s=r.sort((l,c)=>c.score-l.score),a=i+s.length+1;return[...s.map((l,c)=>({...l,score:a-c,matched_fields:["id"]})),...o]}function at(e,t,r,n,o="semantic"){let i=new Map(r.map(u=>[u.item.id,u.score])),s=new Map(r.map(u=>[u.item.id,u.matched_fields])),a=ve(t),d=ve(i),l=new Set([...t.keys(),...i.keys()]),c=1-n;return[...l].map(u=>{let m=e.get(u),f=a.get(u)??0,_=d.get(u)??0,y=f*n+_*c;if(y<=0)return null;let g=new Set;t.has(u)&&g.add(o);for(let w of s.get(u)??[])g.add(w);return{item:m.metadata,score:y,matched_fields:[...g].sort((w,v)=>w.localeCompare(v))}}).filter(u=>u!==null)}function pr(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function gr(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:Ri(eo(s,{fields:e.corpusFields}))})),r=Si(t),n=xi(r,Xt(e.query),e.bm25Params),o=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,d])=>({item:o.get(a).metadata,score:d,matched_fields:["bm25"]}));return nt(s,e.keywordHits)}let i=at(o,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return nt(i,e.keywordHits)}function yr(e){let t=new Map;for(let n of e)for(let o of n){let i=t.get(o.id);(!i||o.score>i.score)&&t.set(o.id,o)}let r=[...t.values()];return r.sort((n,o)=>n.score!==o.score?o.score-n.score:n.id.localeCompare(o.id)),r}function _r(e){let t=e.metadata,r=Array.isArray(t?.tags)?t.tags.join(" "):"";return[t?.title,t?.description,t?.type,t?.status,r,e.body].map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0).join(`
4
4
  `)}async function Fc(e,t){let r=e.queryExpansion.enabled?Ii(t,e.queryExpansion.max_queries):[t],n=r.length>0?r:[t];if(!e.queryExpansion.enabled)return n;if(e.queryExpansionExtension?.expand)try{let o=await Promise.resolve(e.queryExpansionExtension.expand({query:t,mode:e.requestedMode,settings:e.settings}));return Ci(n,Ai(o),e.queryExpansion.max_queries)}catch{return e.warnings.push(`search_query_expansion_provider_failed:${e.queryExpansionExtension.providerName}:using_builtin`),n}return e.queryExpansion.provider&&e.queryExpansion.provider!=="openai"&&e.queryExpansion.provider!=="ollama"&&e.warnings.push(`search_query_expansion_provider_unavailable:${e.queryExpansion.provider}:using_builtin`),n}async function Tc(e,t,r,n){if(e.extensionVectorAdapter?.query)try{return await Promise.resolve(e.extensionVectorAdapter.query({vector:t,limit:r,settings:e.settings}))}catch(o){if(!e.vectorStore)throw new p(`Extension vector adapter query failed and no built-in fallback store is configured (${o instanceof Error?o.message:String(o)})`,h.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await Et(e.vectorStore,t,r,n)}if(e.vectorStore)return await Et(e.vectorStore,t,r,n);throw new p("Semantic search requires either a configured vector store or an extension vector adapter query handler",h.USAGE)}function Pc(e,t,r){return[...e].sort((o,i)=>o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)).slice(0,r).map(o=>{let i=t.get(o.item.id);return i?{hit:o,text:_r(i)}:null}).filter(o=>o!==null)}async function Hc(e,t,r){if(!e.rerankExtension?.rerank)return null;try{let n=await Promise.resolve(e.rerankExtension.rerank({query:t,mode:"hybrid",model:e.rerank.model,top_k:e.rerank.top_k,settings:e.settings,candidates:r.map(i=>({id:i.hit.item.id,text:i.text,score:i.hit.score}))})),o=Ti(n);return o.length>0?new Map(o.map(i=>[i.id,i.score])):(e.warnings.push(`search_rerank_provider_invalid_response:${e.rerankExtension.providerName}:using_builtin`),null)}catch{return e.warnings.push(`search_rerank_provider_failed:${e.rerankExtension.providerName}:using_builtin`),null}}async function Oc(e,t,r){let n=await Hc(e,t,r);if(n)return n;let o=r.map(i=>({id:i.hit.item.id,text:i.text}));try{return await Hi(e.provider,e.rerank.model,t,o,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function Lc(e,t){let r=new Set(t.keys()),n=e.map(o=>{let i=t.get(o.item.id);if(i===void 0)return o;let s=new Set(o.matched_fields);return s.add("rerank"),{...o,score:i,matched_fields:[...s].sort((a,d)=>a.localeCompare(d))}});return n.sort((o,i)=>{let s=r.has(o.item.id),a=r.has(i.item.id);return s!==a?s?-1:1:o.score!==i.score?i.score-o.score:o.item.id.localeCompare(i.item.id)}),n}async function jc(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let o=Pc(r,n,e.rerank.top_k),i=await Oc(e,t,o);return i&&i.size>0?Lc(r,i):r}async function wr(e){let t=Math.max(e.limit??e.maxResults,e.maxResults),r=e.embeddingTimeoutMs!==void 0?{timeout_ms:e.embeddingTimeoutMs}:{},n=e.vectorQueryTimeoutMs!==void 0?{timeout_ms:e.vectorQueryTimeoutMs}:{},o=e.query.trim(),i=await Fc(e,o),s=await $e(e.provider,i,r),a=await Promise.all(s.map(async _=>await Tc(e,_,t,n))),d=yr(a),l=new Map(e.filteredDocuments.map(_=>[_.metadata.id,_])),{semanticHits:c,semanticScores:u}=hr(d,l),m=u.size;if(e.requestedMode==="semantic")return{hits:nt(c,e.keywordHits),vectorMatchCount:m};let f=await jc(e,o,at(l,u,e.keywordHits,e.hybridSemanticWeight),l);return{hits:nt(f,e.keywordHits),vectorMatchCount:m}}function Di(e){let t=Ee(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function Ni(e){let t=Ee(C(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import ct from"node:fs/promises";import vr from"node:path";function Er(e){let t=(e.files??[]).map(s=>({scope:s.scope,path:s.path.trim()})),r=(e.docs??[]).map(s=>({scope:s.scope,path:s.path.trim()})),n=(e.tests??[]).filter(s=>typeof s.path=="string"&&s.path.trim().length>0).map(s=>({scope:s.scope,path:s.path.trim()})),o=[...t,...r,...n].filter(s=>s.path.length>0).sort((s,a)=>s.scope.localeCompare(a.scope)||s.path.localeCompare(a.path)),i=new Map;for(let s of o)i.set(`${s.scope}:${s.path}`,s);return[...i.values()]}async function $i(e){let t=vr.resolve(e);try{let r=await ct.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function br(e,t){let[r,n]=await Promise.all([$i(e),$i(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function Sr(e,t){let r=Er(e.metadata),n=[];for(let o of r){let i=o.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!i)continue;let s=vr.resolve(i.resolved,o.path);if(!ut(i.resolved,s))continue;let a;try{a=await ct.realpath(s)}catch{continue}if(ut(i.realpath,a))try{await he({path:s,scope:o.scope}),n.push(await ct.readFile(s,"utf8"))}catch{}}return n.join(`
5
5
  `)}async function xr(e,t,r,n){let o=$(x()),i=async(l,c,u)=>{let m=async(f,_)=>{await he({path:f,scope:"project"});let y=await ct.readFile(f,"utf8");return Zr(y,{format:_,schema:n,extensionFieldNames:o,onWarning:w=>s.push(w)}).body};try{return await m(c,u)}catch{let f=u==="toon"?"json_markdown":"toon",_=z(e,l.type,l.id,f,r);try{return await m(_,f)}catch{return s.push(`item_list_item_read_failed:${vr.relative(e,_)}`),""}}},s=[],a=await zn(e,t,r,s,n),d=[];if(a.length===0){let l=await Kn(e,t,r,s,n);for(let c of l){let u=z(e,c.type,c.id,t,r),m=await i(c,u,t);d.push({metadata:c,body:m})}return{documents:d,warnings:[...new Set(s)].sort((c,u)=>c.localeCompare(u))}}for(let l of a){if(typeof l.body=="string"){d.push({metadata:l.metadata,body:l.body});continue}let c=await i(l.metadata,l.item_path,l.item_format);d.push({metadata:l.metadata,body:c})}return{documents:d,warnings:[...new Set(s)].sort((l,c)=>l.localeCompare(c))}}async function Ui(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let o=process.cwd(),i=await br(o,zr(o)),s=await Promise.all(r.map(async a=>[a.metadata.id,await Sr(a,i)]));for(let[a,d]of s)n.set(a,d);return n}var Gi=["tag","status","type","priority"];function Rr(e){let t={},r=[];for(let n of e.split(/\s+/).filter(o=>o.length>0)){let o=n.indexOf(":"),i=o>0?n.slice(0,o).toLowerCase():"",s=o>0?n.slice(o+1):"",a=Gi.includes(i)?i:void 0;if(a&&s.length>0&&t[a]===void 0){t[a]=s;continue}r.push(n)}return{residualQuery:r.join(" "),inlineFilters:t}}function kr(e,t,r){let n={...e};for(let o of Gi){let i=t[o];if(i!==void 0){if(Re(n[o])!==void 0){r.push(`search_inline_filter_ignored:${o}:flag_takes_precedence`);continue}n[o]=i}}return n}function Bi(e,t){let r=[],n=Rr(e),o=Object.keys(n.inlineFilters).length>0;if(o&&n.residualQuery.trim().length===0)throw new p("Inline field:value tokens consumed the entire query, leaving no search terms.",h.USAGE,{examples:["pm search auth tag:area:search","pm list --tag area:search --status open"],nextSteps:["Add keyword terms alongside the inline filters, or use pm list for pure tag/status/type/priority filtering."]});let i=o?n.residualQuery:e,s=kr(t,n.inlineFilters,r);return{query:i,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Xe(s.includeLinked),titleExact:Xe(s.titleExact),phraseExact:Xe(s.phraseExact),matchMode:_i(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:wi(s.minScore),countOnly:s.count===!0,tokens:Ze(i),normalizedQuery:A(i),limit:Oe(s.limit),projection:Je(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function Wi(e){if(e.after!==void 0&&e.count===!0)throw new p("Search --after cannot be combined with --count.",h.USAGE)}function Ar(e,t,r,n,o,i,s,a,d,l,c,u,m,f){let _=m?{total:0,count_only:!0}:{};if(l.mode==="compact"&&n.compact===!0){let w=Y({mode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,runtimeFieldFilters:u});return{query:e.trim(),mode:t,...Pr(f),items:[],count:0,..._,filters:w,...c.length>0?{warnings:c}:{}}}let g=l.mode==="full"?null:[...l.fields];return{query:e.trim(),mode:t,mode_source:f,items:[],count:0,..._,filters:Tr({effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,queryExpansion:a,rerank:d,runtimeFieldFilters:u??{}},l),projection:{mode:l.mode,fields:g},now:S(),...c.length>0?{warnings:c}:{}}}function Cr(e,t){let r=t.trim();if(r.length===0)return null;if(r==="score")return e.score;if(r==="matched_fields")return e.matched_fields;if(r.startsWith("item.")){let i=r.slice(5);return i.length===0?null:e.item[i]??null}let n=e,o=e.item;return Object.prototype.hasOwnProperty.call(o,r)?o[r]??null:Object.prototype.hasOwnProperty.call(n,r)?n[r]??null:null}function Mr(e,t){return t.mode==="full"?e.map(({matched_all_terms:r,exact_id_match:n,...o})=>o):e.map(r=>{let n={};for(let o of t.fields)n[o]=Cr(r,o);return n})}function Fr(e,t){return Ar(e.query,e.effectiveMode,e.matchMode,e.options,e.includeLinked,e.scoreThreshold,e.hybridSemanticWeight,e.queryExpansion,e.rerank,e.projection,e.warnings,e.runtimeFieldFilters,t,e.modeSource)}function zi(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Pr(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:Y({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let r=e.projection.mode==="full"?null:[...e.projection.fields];return Ir({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:Tr(e,e.projection),projection:{mode:e.projection.mode,fields:r},now:S()},e.warnings)}function Tr(e,t){let r={matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters};return t.mode==="fields"?Y({...r,mode:e.effectiveMode}):et({...r,effectiveMode:e.effectiveMode,queryExpansion:e.queryExpansion,rerank:e.rerank})}function Pr(e){return e==="settings"?{mode_source:e}:{}}function Ir(e,t){return t.length===0?e:{...e,warnings:t}}function be(e,t){return t?{...e,workspace_memory:t}:e}function Vi(e,t,r){if(!e.highlight)return{hits:r,projection:e.projection};let n=new Map(t.map(i=>[i.metadata.id,i])),o=r.map(i=>({...i,highlights:rt(n.get(i.item.id),i.matched_fields,e.tokens)}));return e.projection.mode==="full"||e.projection.fields.includes("highlights")?{hits:o,projection:e.projection}:{hits:o,projection:{mode:e.projection.mode,fields:[...e.projection.fields,"highlights"]}}}function Ki(e,t,r,n,o,i){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return Ir({query:e.query.trim(),mode:e.effectiveMode,...Pr(e.modeSource),items:t,count:t.length,...s,...i,filters:Y({mode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,runtimeFieldFilters:e.runtimeFieldFilters})},e.warnings);let a=o.mode==="full"?null:[...o.fields];return{query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:t,count:t.length,...s,...i,filters:Tr(e,o),projection:{mode:o.mode,fields:a},now:S(),...e.warnings.length>0?{warnings:e.warnings}:{}}}var qf={applyFilters:nr,applyExactQueryFilters:rr,applyInlineQueryFilters:kr,buildHitHighlights:rt,buildVerboseSearchFilters:et,buildExplicitSemanticFallbackWarning:dr,buildCompactSearchFilterSummary:Y,buildHybridLexicalScore:cr,buildRerankCorpus:_r,buildSemanticHits:hr,classifyImplicitSemanticFallbackReason:it,collectErrorCauseCodes:ot,collectExactPhraseFields:er,collectLinkedPaths:Er,combineHybridHits:at,computeBuiltInBm25Hits:gr,computeSemanticOrHybridHits:wr,resolveBuiltInBm25Mode:pr,countOccurrences:tt,dependencyEntries:we,documentContainsExactPhrase:tr,emptySearchResult:Ar,highlightFieldSnippet:ir,loadDocuments:xr,markTokenRuns:or,parseInlineQueryFilters:Rr,maybeEmitVectorIndexStaleWarning:lr,loadLinkedCorpus:Sr,mergeVectorHitsById:yr,normalizeExtensionProviderHits:fr,normalizeScoreMap:ve,parseProjectionConfig:Je,parseTimestampWindow:Q,parseTokens:Ze,projectSearchHits:Mr,readSearchFieldValue:Cr,requireSemanticDependencies:st,resolveExtensionSearchProvider:ur,resolveExtensionSearchProviderByName:Ee,resolveExtensionVectorAdapter:mr,resolveLinkedCorpusRoots:br,scoreDocument:sr,sortHits:ar,stringArray:se,textEntries:j,validateSearchProjectionFields:Bt};async function qc(e,t){let r=k(process.cwd(),t.path);await O(r);let n=await P(r),o=$n(n).settings,i=N(o.schema),s=Z(o.schema);Bt(e.projection,s,e.query);let a=Dn(e.options,s,"search"),d=D(o,x()),l=Jn(o),c=to(o,r),u=ur(o),m=mr(o),f=yi(e.options.semanticWeight),_=Mi(o,l.active?.name??null),y=Fi(o,l.active?.model??C(o.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:o,statusRegistry:i,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:d,maxResults:Wt(o),scoreThreshold:e.minScoreOverride??Vt(o),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:f,hybridSemanticWeight:f??Kt(o),tuning:Qt(o),providerResolution:l,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:m,bm25Mode:pr({configuredProvider:C(o.search?.provider),hasEmbeddingProvider:l.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:_,queryExpansionExtension:Di(_),rerank:y,rerankExtension:Ni(o),...Dc({requested:e.options.mode,settings:o,configuredProvider:n.search?.provider??null,providerResolution:l,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:m})}}function Dc(e){let r=Xn(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),n=e.extensionSearchProvider!==null||r,o=zt({requested:e.requested,settings:e.settings,semanticRunnable:n});return{effectiveMode:o.mode,modeSource:o.source}}async function Nc(e,t){let r=await xr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=He(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),o=We(t.statusRegistry),i=nr(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,o);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:rr(i,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function $c(e,t,r){let n=await Ui(e.includeLinked,t.effectiveMode,r),o=e.matchMode==="or";return r.map(i=>cr(i,e.tokens,e.normalizedQuery,e.includeLinked,n,t.tuning,t.settings.id_prefix,o)).filter(i=>i!==null).filter(i=>e.matchMode!=="and"||i.matched_all_terms===!0)}async function Uc(e,t,r,n,o){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let i=gr({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:Zn(t.settings),bm25Params:ki(t.settings),hybridSemanticWeight:t.hybridSemanticWeight});return t.bm25Mode==="auto-fallback"&&o.push(`search_${t.effectiveMode}_offline_bm25:no_embedding_provider:using_lexical_bm25`),i}async function Gc(e,t,r,n){if(!t.extensionSearchProvider)return null;let o=t.providerResolution.active!==null&&(t.vectorResolution.active!==null||t.extensionVectorAdapter!==null);try{let i=await Promise.resolve(t.extensionSearchProvider.query({query:e.query,mode:t.effectiveMode,tokens:e.tokens,options:e.options,settings:t.settings,documents:r}));return fr(t.extensionSearchProvider.providerName,i,n)}catch(i){if(!o)throw new p(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${i instanceof Error?i.message:String(i)}`,h.GENERIC_FAILURE);return null}}function Bc(e,t,r,n){return t.vectorMatchCount>0?t.hits:(n.push(`search_${e}_degraded:no_vector_matches:results_are_lexical`),e==="semantic"?r:t.hits)}async function Wc(e,t,r,n,o){let i=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);o&&i&&await lr(e.pmRoot,r,n),e.extensionSearchProvider||st(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function zc(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:o,warnings:i,modeWasExplicit:s}=e,a=o,d=await Uc(t,r,n,o,i),l=r.effectiveMode;if(d!==null||l==="keyword")return{effectiveMode:r.effectiveMode,hits:d??a};try{if(await Wc(r,l,n,i,s),n.length===0||t.limit===0)return{effectiveMode:r.effectiveMode,hits:[]};let c=new Map(n.map(u=>[u.metadata.id,u]));if(a=await Gc(t,r,n,c)??a,a===o){let{provider:u,vectorStore:m}=st(l,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),f=await wr({requestedMode:l,query:t.query,filteredDocuments:n,keywordHits:o,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:m,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:i,settings:r.settings});a=Bc(l,f,o,i)}return{effectiveMode:r.effectiveMode,hits:a}}catch(c){return i.push(dr(r.effectiveMode,c)),{effectiveMode:"keyword",hits:o}}}function Qi(e){e.searchOptions.after!==void 0&&fn(e.searchOptions.after,Yt(e))}async function Yi(e,t,r){Wi(t);let n=Bi(e,t),o=await qc(n,r),i=await Nc(n,o),s=i.warnings;s.push(...n.inlineWarnings);let a=await Ho(i.allDocuments.map(E=>E.metadata),{pmRoot:o.pmRoot,statusRegistry:o.statusRegistry,now:S()});s.push(...a.warnings);let d=Oo(a,n.query);o.effectiveMode==="hybrid"&&o.semanticWeightProvided&&o.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let l={query:n.query,modeSource:o.modeSource,matchMode:n.matchMode,options:n.options,includeLinked:n.includeLinked,titleExact:n.titleExact,phraseExact:n.phraseExact,scoreThreshold:o.scoreThreshold,hybridSemanticWeight:o.hybridSemanticWeight,queryExpansion:o.queryExpansion,rerank:o.rerank,projection:n.projection,warnings:s,runtimeFieldFilters:o.runtimeFieldFilters};if(o.effectiveMode==="keyword"&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Qi({query:n.query,mode:o.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),be(Fr({...l,effectiveMode:o.effectiveMode},n.countOnly),d);let c=await $c(n,o,i.filteredDocuments),u=await zc({prepared:n,runtime:o,filteredDocuments:i.filteredDocuments,keywordHits:c,warnings:s,modeWasExplicit:n.modeWasExplicit});if(u.effectiveMode!=="keyword"&&u.hits.length===0&&(i.filteredDocuments.length===0||n.limit===0&&!n.countOnly))return Qi({query:n.query,mode:u.effectiveMode,searchOptions:n.options,pmRoot:o.pmRoot}),be(Fr({...l,effectiveMode:u.effectiveMode},n.countOnly),d);let m=u.hits.filter(E=>E.exact_id_match===!0||E.score>=o.scoreThreshold),f=ar(m,o.statusRegistry),_=f.length,y=vi({pmRoot:o.pmRoot,sorted:f,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??o.maxResults}),g={...l,effectiveMode:u.effectiveMode};if(n.countOnly)return be(zi(g,_),d);let{hits:w,projection:v}=Vi(n,i.filteredDocuments,y.limited),b=Mr(w,v);return be(Ki(g,b,_,y.limited.length,v,y.pageExtras),d)}var Xi=["ndcg","mrr","precision","recall"];function Hr(e){if(typeof e!="object"||e===null||Array.isArray(e))throw new TypeError("Eval minimum must be an object of metric floors");let t={};for(let[r,n]of Object.entries(e)){if(!Xi.some(o=>o===r))throw new TypeError(`Unknown eval minimum metric: ${r}`);if(typeof n!="number"||!Number.isFinite(n)||n<0||n>1)throw new TypeError(`Eval minimum.${r} must be a finite number in [0, 1]`);t[r]=n}return t}function Ji(e,t){let r=Hr(t),n=[];for(let o of Xi){let i=r[o];if(i===void 0)continue;let s=e[o];!Number.isFinite(s)||s<0||s>1?n.push(`${o}:invalid`):s<i&&n.push(`${o}:${s}<${i}`)}return n}var es=10,U="https://schema.unbrained.dev/pm/eval-query-set/v1",Vc={schema:U,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description","minimum"],modes:["keyword","semantic","hybrid"]},dt={schema:U,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},M=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},Kc=new Set(["keyword","semantic","hybrid"]);function Zi(e,t){let r=0,n=Math.min(t,e.length);for(let o=0;o<n;o+=1)r+=e[o]/Math.log2(o+2);return r}function Qc(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),o=Zi(n,r),i=Array.from({length:t.size},()=>1),s=Zi(i,r);return s===0?0:o/s}function Yc(e,t,r){let n=Math.min(r,e.length);for(let o=0;o<n;o+=1)if(t.has(e[o]))return 1/(o+1);return 0}function Or(e,t,r){let n=Math.min(r,e.length),o=0;for(let i=0;i<n;i+=1)t.has(e[i])&&(o+=1);return o}function Xc(e,t,r){return r<=0?0:Or(e,t,r)/r}function Jc(e,t,r){return t.size===0?0:Or(e,t,r)/t.size}function ts(e,t,r){return{ndcg:Qc(e,t,r),mrr:Yc(e,t,r),precision:Xc(e,t,r),recall:Jc(e,t,r),relevant_total:t.size,retrieved_relevant:Or(e,t,r)}}function rs(e){let t=e.length;if(t===0)return{ndcg:0,mrr:0,precision:0,recall:0,query_count:0};let r=e.reduce((n,o)=>({ndcg:n.ndcg+o.ndcg,mrr:n.mrr+o.mrr,precision:n.precision+o.precision,recall:n.recall+o.recall}),{ndcg:0,mrr:0,precision:0,recall:0});return{ndcg:r.ndcg/t,mrr:r.mrr/t,precision:r.precision/t,recall:r.recall/t,query_count:t}}function Zc(e,t){if(typeof e!="object"||e===null)throw new M(`Eval query at index ${t} must be an object`);let r=e,n=typeof r.query=="string"?r.query.trim():"";if(n.length===0)throw new M(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new M(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(i=>typeof i!="string"))throw new M(`Eval query at index ${t} must have a "relevant_ids" array of strings`);let o=[...new Set(r.relevant_ids.map(i=>i.trim()).filter(i=>i.length>0))];if(o.length===0)throw new M(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!Kc.has(r.mode)))throw new M(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:o,...r.minimum===void 0?{}:{minimum:Hr(r.minimum)},...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function Lr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==U)throw new M(`Unsupported eval query set schema; expected "${U}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new M('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new M("Eval query set must contain at least one query");return{schema:U,queries:r.map((n,o)=>Zc(n,o))}}import ed from"node:fs/promises";import jr from"node:path";var td=jr.join("search","eval-queries.json"),qr={schema:U,examples:[JSON.stringify(dt)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},rd=new Set(["keyword","semantic","hybrid"]),nd=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!rd.has(t))throw new p("Eval --mode must be one of keyword|semantic|hybrid",h.USAGE);return t},od=e=>{if(e===void 0||e==="")return es;let t=ke(e);if(t===null)throw new p("Eval --k must be a positive integer",h.USAGE);return t},id=e=>{if(e===void 0||e==="")return;let t=String(e).trim(),r=Number(t);if([t.length===0,!Number.isFinite(r),r<0,r>1].includes(!0))throw new p("Eval --fail-under must be a number in the range [0, 1]",h.USAGE);return r},G=e=>Math.round(e*1e4)/1e4,sd=async e=>{try{return await ed.readFile(e,"utf8")}catch{throw new p(`Eval query set not found at ${e}`,h.NOT_FOUND,{...qr,examples:[`echo '${JSON.stringify(dt)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},ad=(e,t)=>{try{return JSON.parse(e)}catch(r){throw new p(`Eval query set at ${t} is not valid JSON: ${r instanceof Error?r.message:String(r)}`,h.USAGE,qr)}},cd=e=>{try{return Lr(e)}catch(t){throw new p(t instanceof Error?t.message:String(t),h.USAGE,qr)}},dd=async e=>cd(ad(await sd(e),e)),ld=async(e,t,r,n)=>{let o=e.mode??t,s=(await Yi(e.query,{mode:o,limit:String(r),fields:"id"},n)).items.map(d=>d.id).filter(d=>typeof d=="string"),a=ts(s,new Set(e.relevant_ids),r);return{metrics:a,report:{query:e.query,...e.minimum===void 0?{}:{violations:Ji(a,e.minimum)},mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:G(a.ndcg),mrr:G(a.mrr),precision:G(a.precision),recall:G(a.recall)}}},ud=(e,t,r,n)=>{let o=rs(r);return{k:e,query_count:t.length,aggregate:{ndcg:G(o.ndcg),mrr:G(o.mrr),precision:G(o.precision),recall:G(o.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:(n===void 0||o.ndcg>=n)&&t.every(i=>(i.violations?.length??0)===0)}},th=async(e,t)=>{let r=k(process.cwd(),t.path);await O(r);let n=od(e.k),o=nd(e.mode),i=id(e.failUnder),s=e.queries?jr.resolve(process.cwd(),e.queries):jr.join(r,td),a=await dd(s),d=[],l=[];for(let c of a.queries){let{report:u,metrics:m}=await ld(c,o,n,t);l.push(m),d.push(u)}return ud(n,d,l,i)};export{ws as a,Es as b,Hd as c,Od as d,el as e,tl as f,Tt as g,Vo as h,Ko as i,Qo as j,Il as k,Yl as l,Kl as m,ru as n,nu as o,ui as p,mi as q,fi as r,ha as s,Qe as t,Cu as u,Mu as v,Nu as w,Wt as x,zt as y,Vt as z,Kt as A,Qt as B,Yt as C,vi as D,Y as E,et as F,ot as G,it as H,ji as I,qi as J,qf as K,Yi as L,Xi as M,Hr as N,Ji as O,U as P,Vc as Q,dt as R,Lr as S,td as T,th as U};
6
- //# sourceMappingURL=chunk-H7JEXRIN.js.map
6
+ //# sourceMappingURL=chunk-WWTPNIC2.js.map
@@ -1,2 +1,2 @@
1
- import{la as g,ma as i,na as v,oa as _}from"./chunk-CFWLQFJM.js";import{Ua as w}from"./chunk-NGJ5ERBF.js";import u from"node:fs/promises";import c from"node:path";function f(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function b(e){return e!=="invalid"&&e!=="unreadable"}function j(e){let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new SyntaxError("Invalid settings object");let t=r.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");let n=t;if(n.enabled!==void 0&&(!Array.isArray(n.enabled)||!n.enabled.every(a=>typeof a=="string"))||n.disabled!==void 0&&(!Array.isArray(n.disabled)||!n.disabled.every(a=>typeof a=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:n.enabled??[],disabled:n.disabled??[]}}async function S(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}try{return{status:"ok",...j(r)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function A(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){if(f(t))try{if((await u.stat(c.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(n){if(f(n))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}try{let t=JSON.parse(r),n=_(t);if(!n||typeof t!="object"||t===null||!Array.isArray(t.entries)||n.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:n.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function M(e){try{return{directories:(await u.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}}catch(r){return f(r)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function N(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}try{let t=v(JSON.parse(r));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function z(e){let r=e.manifest?.name??e.directory,t=new Set(g(e.settings.enabled)),n=new Set(g(e.settings.disabled)),a=!b(e.settings.status)||!e.manifest?null:!n.has(r)&&(t.size===0||t.has(r)),o=b(e.managed.status)?e.managed.entries.some(d=>i(d.name)===i(r)||i(d.directory)===i(e.directory)):null;return{name:r,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?a===!1?"inactive":"installed":"malformed_manifest",configured_enabled:a,managed:o,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}async function J(e){let r=e.scope??"project",t=r==="global"?w(e.cwd??process.cwd()):e.pmRoot,n=c.join(t,"extensions"),a=await S(c.join(t,"settings.json")),o=await A(c.join(n,".managed-extensions.json")),d=await M(n),l=[];for(let s of[a,o,d])s.error&&l.push(s.error);let m=e.name?.trim(),y=[];for(let s of d.directories){let x=c.join(n,s,"manifest.json"),p=await N(x);p.error&&l.push(p.error);let h=z({directory:s,scope:r,manifest:p.manifest,settings:a,managed:o});m&&![h.name,s].some(E=>i(E)===i(m))||y.push(h)}return m&&y.length===0&&l.every(s=>s.code!=="extensions_unreadable")&&y.push({name:m,directory:null,scope:r,installed:!1,status:"absent",configured_enabled:b(a.status)?!1:null,managed:b(o.status)?!1:null,runtime_active:null}),{scope:r,complete:l.length===0,settings_status:a.status,managed_state_status:o.status,extensions:y,errors:l}}export{J as a};
2
- //# sourceMappingURL=chunk-J2PDAVBC.js.map
1
+ import{da as g,ea as i,fa as v,ga as _}from"./chunk-YW2HBHRO.js";import{da as w}from"./chunk-FXJYZBWV.js";import u from"node:fs/promises";import c from"node:path";function f(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function b(e){return e!=="invalid"&&e!=="unreadable"}function j(e){let r=JSON.parse(e);if(typeof r!="object"||r===null||Array.isArray(r))throw new SyntaxError("Invalid settings object");let t=r.extensions;if(t===void 0)return{enabled:[],disabled:[]};if(typeof t!="object"||t===null||Array.isArray(t))throw new SyntaxError("Invalid extensions settings");let n=t;if(n.enabled!==void 0&&(!Array.isArray(n.enabled)||!n.enabled.every(a=>typeof a=="string"))||n.disabled!==void 0&&(!Array.isArray(n.disabled)||!n.disabled.every(a=>typeof a=="string")))throw new SyntaxError("Invalid extension enablement lists");return{enabled:n.enabled??[],disabled:n.disabled??[]}}async function S(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{status:"absent",enabled:[],disabled:[]}:{status:"unreadable",enabled:[],disabled:[],error:{code:"settings_unreadable",path:e}}}try{return{status:"ok",...j(r)}}catch{return{status:"invalid",enabled:[],disabled:[],error:{code:"settings_invalid",path:e}}}}async function A(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){if(f(t))try{if((await u.stat(c.dirname(e))).isDirectory())return{status:"absent",entries:[]}}catch(n){if(f(n))return{status:"absent",entries:[]}}return{status:"unreadable",entries:[],error:{code:"managed_state_unreadable",path:e}}}try{let t=JSON.parse(r),n=_(t);if(!n||typeof t!="object"||t===null||!Array.isArray(t.entries)||n.entries.length!==t.entries.length)throw new SyntaxError("Invalid managed extension state");return{status:"ok",entries:n.entries}}catch{return{status:"invalid",entries:[],error:{code:"managed_state_invalid",path:e}}}}async function M(e){try{return{directories:(await u.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}}catch(r){return f(r)?{directories:[]}:{directories:[],error:{code:"extensions_unreadable",path:e}}}}async function N(e){let r;try{r=await u.readFile(e,"utf8")}catch(t){return f(t)?{manifest:null,error:{code:"manifest_invalid",path:e}}:{manifest:null,error:{code:"manifest_unreadable",path:e}}}try{let t=v(JSON.parse(r));return t?{manifest:t}:{manifest:null,error:{code:"manifest_invalid",path:e}}}catch{return{manifest:null,error:{code:"manifest_invalid",path:e}}}}function z(e){let r=e.manifest?.name??e.directory,t=new Set(g(e.settings.enabled)),n=new Set(g(e.settings.disabled)),a=!b(e.settings.status)||!e.manifest?null:!n.has(r)&&(t.size===0||t.has(r)),o=b(e.managed.status)?e.managed.entries.some(d=>i(d.name)===i(r)||i(d.directory)===i(e.directory)):null;return{name:r,directory:e.directory,scope:e.scope,installed:!0,status:e.manifest?a===!1?"inactive":"installed":"malformed_manifest",configured_enabled:a,managed:o,runtime_active:null,...e.manifest?{version:e.manifest.version}:{}}}async function J(e){let r=e.scope??"project",t=r==="global"?w(e.cwd??process.cwd()):e.pmRoot,n=c.join(t,"extensions"),a=await S(c.join(t,"settings.json")),o=await A(c.join(n,".managed-extensions.json")),d=await M(n),l=[];for(let s of[a,o,d])s.error&&l.push(s.error);let m=e.name?.trim(),y=[];for(let s of d.directories){let x=c.join(n,s,"manifest.json"),p=await N(x);p.error&&l.push(p.error);let h=z({directory:s,scope:r,manifest:p.manifest,settings:a,managed:o});m&&![h.name,s].some(E=>i(E)===i(m))||y.push(h)}return m&&y.length===0&&l.every(s=>s.code!=="extensions_unreadable")&&y.push({name:m,directory:null,scope:r,installed:!1,status:"absent",configured_enabled:b(a.status)?!1:null,managed:b(o.status)?!1:null,runtime_active:null}),{scope:r,complete:l.length===0,settings_status:a.status,managed_state_status:o.status,extensions:y,errors:l}}export{J as a};
2
+ //# sourceMappingURL=chunk-XFADNMGD.js.map
@@ -1,4 +1,4 @@
1
- import{B as us,H as cn,e as Mr,f as $r,j as as,m as an,n as Pr,o as Dr,p as cs,r as St,u as Be,v as Y,w as xt}from"./chunk-2UQU7HRR.js";import{Ad as Te,Aj as U,Bd as Tr,Dj as on,Ej as Ae,Fh as tn,Fi as rs,Fj as ss,Ga as yr,Gh as nn,Gj as Lr,Ha as gr,Hb as Hi,He as Qi,Ia as ji,Ib as S,Ie as es,Ja as Er,Ka as ut,Kb as lt,Lb as He,Lj as sn,Mb as x,Nb as qi,Nc as Sr,Oc as Gi,Pa as Jt,Ta as wr,Tb as Bi,Te as en,Ua as me,Uc as xr,Ud as Ji,Va as Se,Vc as Ki,Wa as Ve,Wd as Ar,Wh as Rr,Xa as dt,Xb as Wi,Xh as Or,Y as $i,Ya as W,Yb as F,Yh as ts,Z as Pi,Zc as br,Zh as kr,_c as Qt,_h as ns,aa as Di,ae as Cr,b as st,be as pt,ca as ct,e as Oi,fd as Xi,ge as _t,gj as os,hc as be,i as ki,ii as Et,ji as Nr,lb as xe,m as Ni,me as ht,n as Li,nb as zi,nd as ce,ne as Zi,ob as Ui,od as mt,pc as Yi,pd as qe,pj as pe,tb as Vi,tj as is,u as Mi,ue as yt,uh as vr,vc as ft,ve as Ir,wb as Zt,we as gt,wj as rn,xj as wt}from"./chunk-NGJ5ERBF.js";import{A as m,B as Xt,C as p,D as Fi,E as P,G as D,H as C,K as A,L as hr,M as at,m as pr,u as Q,z as _r}from"./chunk-YYT3MIRF.js";var cl=new Set(["rename-type","rename-field","remap-status",...Oi]);function ul(e,t){if(t&&!cl.has(e))throw new p(`schema ${e} does not support --dry-run. Preview is supported for rename-type, rename-field, remap-status and workflow-policy actions. Remove --dry-run only when you intend to apply changes.`,m.USAGE,{code:"invalid_argument_value",examples:["pm schema rename-type Spike --to Experiment --dry-run"]})}var un=new WeakSet,Fr=new WeakMap,ls=new WeakSet;function jr(e){return ls.add(e),e}function zr(e){return ls.has(e)}function bt(e){un.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),un.add(r)}return e}function fs(e,t){return un.has(e)||t!==void 0&&Fr.get(e)?.has(t)===!0}function dl(e,t){let n=new Set(t);Fr.set(e,n);for(let r of n){let o=Reflect.get(e,r);if(!Array.isArray(o))continue;let i=[...o];Reflect.set(e,r,i),un.add(i)}return e}function ms(e,t){if(zr(e)&&jr(t),fs(e))return bt(t);let n=Fr.get(e);return n?dl(t,n):t}function xx(e){return fs(e)?"sdk":"cli"}function ds(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function Tt(e){return`Pass unset: ["${e}"] to clear it`}function dn(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${ds("sdk",t)} must not be empty. ${Tt(t)}, or omit ${ds("sdk",t)}.`}var ue="-",_s=/^[A-Za-z0-9_.-]+$/u,Ur=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function hs(e,t){if(e.startsWith("```")||e.includes(`
1
+ import{B as us,H as cn,e as Mr,f as $r,j as as,m as an,n as Pr,o as Dr,p as cs,r as St,u as Be,v as Y,w as xt}from"./chunk-23K6DQQY.js";import{Ab as mt,Ba as S,Bb as qe,Da as lt,Dh as pe,Ea as He,Fa as x,Ga as qi,Gc as yt,Hc as Ir,Hh as is,I as $i,Ic as gt,If as vr,J as Pi,Kh as rn,Lh as wt,M as Di,Mb as Te,Nb as Tr,Oh as U,Qa as be,R as yr,Rh as on,S as gr,Sh as Ae,T as ji,Tc as Qi,Tf as tn,Tg as rs,Th as ss,U as Er,Uc as es,Uf as nn,Uh as Lr,V as ut,Ya as Yi,Zh as sn,_ as Jt,a as Oi,ca as wr,da as me,dd as en,e as ki,ea as Se,eb as xr,ec as Ji,fa as Ve,fb as Ki,ga as dt,gc as Ar,ha as W,i as Ni,ig as Rr,j as Li,jb as br,jg as Or,kb as Qt,kg as ts,lg as kr,mc as Cr,mg as ns,nc as pt,rb as Xi,sc as _t,uh as os,wg as Et,xg as Nr,yc as ht,zb as ce,zc as Zi}from"./chunk-FXJYZBWV.js";import{A as Vi,D as Zt,J as Wi,K as F,Z as Sr,_ as Gi,b as st,j as Mi,s as xe,u as zi,v as Ui}from"./chunk-7IROAPWI.js";import{C as Hi,D as Bi,E as ft,a as ct}from"./chunk-7X253M6Z.js";import{A as m,B as Xt,C as p,D as Fi,E as P,G as D,H as C,K as A,L as hr,M as at,m as pr,u as Q,z as _r}from"./chunk-YYT3MIRF.js";var cl=new Set(["rename-type","rename-field","remap-status",...Oi]);function ul(e,t){if(t&&!cl.has(e))throw new p(`schema ${e} does not support --dry-run. Preview is supported for rename-type, rename-field, remap-status and workflow-policy actions. Remove --dry-run only when you intend to apply changes.`,m.USAGE,{code:"invalid_argument_value",examples:["pm schema rename-type Spike --to Experiment --dry-run"]})}var un=new WeakSet,Fr=new WeakMap,ls=new WeakSet;function jr(e){return ls.add(e),e}function zr(e){return ls.has(e)}function bt(e){un.add(e);for(let[t,n]of Object.entries(e)){if(!Array.isArray(n))continue;let r=[...n];Reflect.set(e,t,r),un.add(r)}return e}function fs(e,t){return un.has(e)||t!==void 0&&Fr.get(e)?.has(t)===!0}function dl(e,t){let n=new Set(t);Fr.set(e,n);for(let r of n){let o=Reflect.get(e,r);if(!Array.isArray(o))continue;let i=[...o];Reflect.set(e,r,i),un.add(i)}return e}function ms(e,t){if(zr(e)&&jr(t),fs(e))return bt(t);let n=Fr.get(e);return n?dl(t,n):t}function xx(e){return fs(e)?"sdk":"cli"}function ds(e,t){return e==="cli"?`--${t}`:t.replace(/-([a-z])/gu,(n,r)=>r.toUpperCase())}function Tt(e){return`Pass unset: ["${e}"] to clear it`}function dn(e,t,n=""){return e==="cli"?`--${t} must not be empty${n}`:`${ds("sdk",t)} must not be empty. ${Tt(t)}, or omit ${ds("sdk",t)}.`}var ue="-",_s=/^[A-Za-z0-9_.-]+$/u,Ur=new Set(["actual_result","body","cmd","command","customer_impact","description","environment","expected_result","impact","location","message","note","outcome","repro_steps","resolution","text","title","unblock_note","value","why_now"]);function hs(e,t){if(e.startsWith("```")||e.includes(`
2
2
  `))return!0;let n=t.map(r=>r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|");return new RegExp(`^(?:[-*+]\\s+)?(?:${n})\\s*[:=]`,"i").test(e)}function ys(e){let t=e.trim();if(t==="")return[];let r=(_l(t)??t.split(",")).map(o=>o.trim()).filter(Boolean).map(o=>o.toLowerCase());return Array.from(new Set(r)).sort((o,i)=>o.localeCompare(i))}function gs(e){if(!Array.isArray(e)||e.length===0)return[];let t=[];for(let n of e)if(typeof n=="string")for(let r of ys(n))t.push(r);return Array.from(new Set(t)).sort((n,r)=>n.localeCompare(r))}function Es(e){return Array.isArray(e)?e.filter(t=>typeof t=="string").map(t=>t.trim().toLowerCase()).filter(Boolean):[]}function ll(e){return typeof e!="string"?[]:e.split(";").map(t=>t.trim()).filter(Boolean)}function fl(e,t,n){let r=e.map(s=>s.trim()).filter(Boolean);for(let s of t??[]){let a=s.trim();if(a.includes(";"))throw new p('Acceptance criteria added with --add-ac cannot contain ";" because semicolons delimit stored criteria',m.USAGE,{code:"acceptance_criteria_semicolon_forbidden",required:"Pass one semicolon-free criterion per --add-ac value",why:"A semicolon inside one criterion would be re-read as multiple criteria",nextSteps:["Split the text into repeated --add-ac values, or replace the semicolon with punctuation that is not the storage delimiter"]});a.length>0&&!r.includes(a)&&r.push(a)}let o=[],i=r;for(let s of n??[]){let a=s.trim();if(a.length!==0){if(!i.includes(a)){o.push(a);continue}i=i.filter(c=>c!==a)}}return{criteria:i,unmatchedRemovals:o}}function ml(e,t){let n=Es(e);if(!t||t.length===0)return Array.from(new Set(n)).sort((o,i)=>o.localeCompare(i));let r=new Set(n);for(let o of gs(t))r.add(o);return Array.from(r).sort((o,i)=>o.localeCompare(i))}function pl(e,t){let n=Array.from(new Set(Es(e))).sort((o,i)=>o.localeCompare(i));if(!t||t.length===0)return n;let r=new Set(gs(t));return r.size===0?n:n.filter(o=>!r.has(o))}function _l(e){if(!e.startsWith("["))return null;let t;try{t=JSON.parse(e)}catch{return null}return t.map(r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean"?String(r):"").filter(r=>r.length>0)}function Vr(e){return e.replace(/\r\n/g,`
3
3
  `)}function ws(e){let t=Vr(e).trim();if(!t.startsWith("```"))return e;let n=t.split(`
4
4
  `);return n.length<2||n.at(-1)?.trim()!=="```"?e:n.slice(1,-1).join(`
@@ -122,4 +122,4 @@ Enable telemetry now? [${e?"Y/n":"y/N"}] `,r=Hw.createInterface({input:qw,output
122
122
  `)){let r=n.trim();if(r.length!==0)try{let o=JSON.parse(r);o&&typeof o=="object"&&typeof o.endpoint=="string"&&o.endpoint.trim().length>0&&"payload"in o&&typeof o.attempts=="number"&&Number.isFinite(o.attempts)&&((typeof o.id!="string"||o.id.length===0)&&(o.id=tx(o)),t.push(o))}catch{}}return t}function nx(e,t){if(typeof e.enqueued_at!="string"||e.enqueued_at.trim().length===0)return!1;let n=Date.parse(e.enqueued_at);return Number.isNaN(n)?!1:n<t}function Ii(e,t){let n=Zd(t),r=[],o=0;for(let i of e){if(JSON.stringify(i).length>dr||nx(i,n)||i.attempts>=Od){o+=1;continue}r.push(i)}if(r.length>hd){let i=r.length-hd;return o+=i,{entries:r.slice(i),prunedCount:o}}return{entries:r,prunedCount:o}}async function rx(e,t){let n=t.map(o=>JSON.stringify(o)).join(`
123
123
  `),r=n.length>0?`${n}
124
124
  `:"";for(let o=0;;o+=1)try{await A(Kt(e),r,{createParentDirectories:!ie(process.env[fe])});return}catch(i){let s=kd[o];if(s===void 0||!el(i))throw i;await tl(s)}}async function Td(e,t,n,r){return Ee(async()=>{let o=await C(Kt(e)),i=o===null?[]:Ci(o),s=[];for(let c of i){if(n.has(c.id))continue;let u=r.get(c.id);s.push(u?{...c,attempts:u.attempts,next_attempt_after:u.next_attempt_after}:c)}let{entries:a}=Ii(s,t);return await rx(e,a),a.length},e)}async function ox(e,t){let n=await C(Kt(e));if(n===null||n.trim().length===0){await ar(e,{pending_otel_spans:0},null);return}let r=Ci(n),{entries:o,prunedCount:i}=Ii(r,t),s=o.filter(h=>Ai(h.next_attempt_after)).slice(0,uS);if(s.length===0){let h=i>0?await Td(e,t,new Set,new Map):o.length;await ar(e,{pending_otel_spans:h},null);return}let a=F(),c=new Set,u=new Map,d=0,l;await Promise.all(s.map(async h=>{try{let g=await Hd(h.endpoint,{"content-type":"application/json"},JSON.stringify(h.payload));if(g<200||g>=300)throw new Error(`local_otel_export_http_${g}`);c.add(h.id),d+=1}catch(g){l=g instanceof Error?O(Bn(g.message),"redacted"):"local_otel_export_failed";let y=h.attempts+1;u.set(h.id,{attempts:y,next_attempt_after:Xd(y)})}}));let f=await Td(e,t,c,u),_={pending_otel_spans:f,last_otel_attempt_at:a};d>0&&(_.last_otel_success_at=a),l!==void 0?(_.last_otel_failure_at=a,_.last_otel_failure_error=l):f===0&&(_.last_otel_failure_at=void 0,_.last_otel_failure_error=void 0),await ar(e,_,null)}async function nl(e,t,n){try{await cx(e,t,n)}catch{}try{await ox(e,n)}catch{}}async function ix(e,t=yS,n=z().endpoint){try{let r=DS(e),o=await rS(r,{withFileTypes:!0}),i=Date.now(),s=new Set([qt("events.jsonl",n),qt("state.json",n)]),a=c=>{if(!s.has(c))return/^\.events(?:\.[a-f0-9]{16})?\.jsonl\.\d+\.\d+\.[a-f0-9]+\.tmp$/.test(c)?i-Math.max(0,t):/^(?:events\.[a-f0-9]{16}\.jsonl|state\.[a-f0-9]{16}\.json)$/.test(c)?i-gS:void 0};await Promise.all(o.map(async c=>{let u=c.isFile()?a(c.name):void 0;if(u===void 0)return;let d=k.join(r,c.name);(await Id(d)).mtimeMs<u&&await yi(d,{force:!0})}))}catch{}}async function Ee(e,t=me(process.cwd()),n=5e3){let r=wd.catch(()=>{}).then(()=>os(async()=>{let o=await Te(t,"telemetry-queue",60,"telemetry",!1,!1,n,{createParentDirectories:!ie(process.env[fe])});try{return an(t),await e()}finally{await o()}}));return wd=r.catch(()=>{}),r}async function mr(e,t=z().endpoint){let n=await C(Gt(e,t));return n===null||n.trim().length===0?[]:Kd(n)}async function fi(e,t,n,r=z().endpoint){return Ee(async()=>{let o=await mr(e,r),{entries:i}=fr(o,n),s=i.filter(a=>!t.has(a.event.event_id));return await Qd(e,s,r),s},e)}async function sx(e,t,n,r,o=z().endpoint){return Ee(async()=>{let i=await mr(e,o),{entries:s}=fr(i,r),a=s.map(c=>{if(!t.has(c.event.event_id))return c;let u=c.attempts+1;return{...c,attempts:u,last_attempt_at:n,next_attempt_after:Xd(u)}});return await Qd(e,a,o),a},e)}function ax(e,t){return t===null?e:qn(e)}async function cx(e,t,n){let r=z().endpoint;await ix(e,void 0,r);let o=(r??t).trim(),i=ax(o,r),s=y=>ar(e,y,r);if(o.length===0)return;let a=await C(Gt(e,r));if(a===null||a.trim().length===0){await s({endpoint:i,queue_entries:0});return}let c=Kd(a);if(c.length===0){await s({endpoint:i,queue_entries:0});return}let{entries:u,prunedCount:d}=fr(c,n);if(u.length===0){let y=await fi(e,new Set,n,r);await s({endpoint:i,queue_entries:y.length});return}let l=u.filter(y=>Jd(y)).slice(0,dS);if(l.length===0){let y=d>0?await fi(e,new Set,n,r):u;await s({endpoint:i,queue_entries:y.length});return}let f=new Set(l.map(y=>y.event.event_id)),_=F(),h={"content-type":"application/json"},g=process.env.PM_TELEMETRY_INGEST_KEY?.trim();g&&(h["x-pm-telemetry-key"]=g);try{let y=await Hd(o,h,JSON.stringify({schema_version:ur,events:l.map(E=>E.event)}));if(y<200||y>=300)throw new Error(`telemetry_flush_http_${y}`)}catch(y){let E=await sx(e,f,_,n,r),w=y instanceof Error?O(Bn(y.message),"redacted"):"telemetry_flush_failed";await s({endpoint:i,queue_entries:E.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:w});return}try{let y=await fi(e,f,n,r);await s({endpoint:i,queue_entries:y.length,last_attempted_flush_at:_,last_successful_flush_at:_,last_failed_flush_at:void 0,last_failed_flush_error:void 0})}catch(y){let E=y instanceof Error?O(Bn(y.message),"redacted"):"telemetry_flush_failed",w=await mr(e,r).catch(()=>u);await s({endpoint:i,queue_entries:w.length,last_attempted_flush_at:_,last_failed_flush_at:_,last_failed_flush_error:E})}}async function ux(e){let t=wi(e);ie(process.env[fe])||await di(k.dirname(t),{recursive:!0});try{return await di(t),!0}catch(n){if(typeof n!="object"||n===null||!("code"in n)||n.code!=="EEXIST")throw n}try{let n=await Id(t);return Date.now()-n.mtimeMs<Nd?!1:(await yi(t,{recursive:!0,force:!0}),await di(t),!0)}catch{return!1}}function dx(e,t){try{return Date.now()-Cd(e).mtimeMs<t}catch{return!1}}function rl(e){try{nS(e,{recursive:!0,force:!0})}catch{}}function lx(e){if(typeof e!="object"||e===null||!("code"in e))return;let t=e.code;return typeof t=="string"?t:void 0}function fx(e){try{return ui(e),!0}catch(t){if(lx(t)==="EEXIST"||!D(t))return!1}try{return ui(k.dirname(e),{recursive:!0}),ui(e),!0}catch{return!1}}function mx(e){if(dx(wi(e),Nd))return!1;let t=$d(e);try{if(Date.now()-Cd(t).mtimeMs<ES)return!1;rl(t)}catch(n){if(!D(n))return!1}return fx(t)}function hi(e){rl($d(e))}async function px(e,t,n){let r=await ux(e);if(hi(e),!r)return!1;try{await nl(e,t,n)}finally{try{await yi(wi(e),{recursive:!0,force:!0})}catch{}}return!0}async function Ad(e,t){let n=new Set;try{let{entries:r}=fr(await mr(e),t);for(let o of r.filter(Jd))n.add(`event:${o.event.event_id}`)}catch{}try{let r=await C(Kt(e));if(r!==null)for(let o of Ii(Ci(r),t).entries)Ai(o.next_attempt_after)&&n.add(`span:${o.id}`)}catch{}return n}function vi(e,t,n){if(!Dr(e)){if(jS())return li=li.then(()=>nl(e,t,n)),li;try{if(!mx(e))return;let o=tS(process.execPath,[FS()],{detached:!0,stdio:"ignore",cwd:gi.tmpdir(),env:{...process.env,PM_GLOBAL_PATH:e,[fe]:"1"}});o.on("error",()=>{hi(e)}),o.unref()}catch{hi(e)}}}async function zR(e=me(process.cwd())){if(!K().telemetry_disabled)try{await Pr(e,async()=>{let t=ie(process.env[fe]),n=!0;for(;n;){if(!(await Y(e)).telemetry.enabled)return;let o=await Ee(()=>Ti(e),e);if(!o)return;let i=t?await Ad(e,o.retentionDays):new Set;if(!await px(e,o.endpoint,o.retentionDays)||!t)return;let a=await Ad(e,o.retentionDays);n=a.size>0&&(a.size!==i.size||[...a].some(c=>!i.has(c)))}},()=>ie(process.env[fe]))}catch{}}async function _x(e){if(K().telemetry_disabled||e.command==="telemetry"&&e.args.some(t=>t.trim().toLowerCase()==="clear"))return null;try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return null;let r=e.global.noExtensions===!0||is(e.command),o=await Ee(async()=>{let i=await Ti(t);if(!i)return null;let{installationId:s,endpoint:a,retentionDays:c,captureLevel:u}=i,d=qd(e.pm_version),l=Wd(e.global),f=j(s,e.pm_root),_=j(s,process.cwd()),h=WS(),g=F(),y={schema_version:ur,event_id:J.randomUUID(),event_type:"command_start",occurred_at:g,installation_id:s,session_id:lr,command:e.command,payload:XS({captureLevel:u,context:e,pmVersion:d,sourceContext:l,pmRootHash:f,cwdHash:_,installationId:s})},E=await _d(t,e.command,r);E===1&&await cr(t,y);let w=$e(e.command),b={...E<1?{sample_rate:E}:{},started_at:g,started_at_ms:Date.now(),command:e.command,command_taxonomy:w,pm_version:d,source_context:l.source_context,source_context_source:l.source_context_source,installation_id:s,pm_root_hash:f,cwd_hash:_,endpoint:a,retention_days:c,global_pm_root:t,capture_level:u,otel_traces_endpoint:h??void 0,otel_trace_id:h?J.randomBytes(16).toString("hex"):void 0,otel_span_id:h?J.randomBytes(8).toString("hex"):void 0};return E<1&&sr.set(b,y),b},t,Ei);return o&&o.sample_rate===void 0&&vi(t,o.endpoint,o.retention_days),o}catch{return null}}async function hx(e,t){if(!(!e||K().telemetry_disabled))try{if(!await Ee(async()=>{let r=await Y(e.global_pm_root);if(K().telemetry_disabled||!r.telemetry.enabled||r.telemetry.installation_id!==e.installation_id)return sr.delete(e),!1;let o=sr.get(e),i=t.ok?e.sample_rate??1:1;if(o){if(sr.delete(e),J.randomBytes(6).readUIntBE(0,6)/281474976710656>=i)return!1;o.payload.sample_rate=i,await cr(e.global_pm_root,o)}let s=F(),a=Math.max(0,Date.now()-e.started_at_ms),c=Si(qo({ok:t.ok,errorCode:t.error_code,errorMessage:t.error,exitCode:t.exit_code})),u=Bd({ok:t.ok,errorCode:c,errorCategory:t.error_category}),d=xi(t.exit_code,t.ok),l=t.command_resolution??rt({ok:t.ok,errorCode:c,errorCategory:u}),f=t.resolution_stage??"execute",_={schema_version:ur,event_id:J.randomUUID(),event_type:"command_finish",occurred_at:s,installation_id:e.installation_id,session_id:lr,command:e.command,payload:{...o?{sample_rate:i}:{},...JS({captureLevel:e.capture_level,pmVersion:e.pm_version,sourceContext:{source_context:e.source_context,source_context_source:e.source_context_source},outcome:t,durationMs:a,startedAt:e.started_at,command:e.command,installationId:e.installation_id,commandTaxonomy:e.command_taxonomy,exitCode:d,errorCode:c,errorCategory:u,commandResolution:l,resolutionStage:f})}};await cr(e.global_pm_root,_);let h=GS(e,{...t,exit_code:d,error_code:c,error_category:u},s,a,i);return h&&await ex(e.global_pm_root,h),!0},e.global_pm_root,Ei))return;await vi(e.global_pm_root,e.endpoint,e.retention_days)}catch{}}async function yx(e){if(!K().telemetry_disabled)try{let t=me(process.cwd());if(!(await Y(t)).telemetry.enabled)return;let r=await Ee(async()=>{let o=await Ti(t);if(!o)return null;let{installationId:i,captureLevel:s}=o,a=qd(e.pm_version),c=Wd(e.global),u=j(i,e.pm_root),d=j(i,process.cwd()),l=F(),f=Si(qo({ok:!1,errorCode:e.error_code,errorMessage:e.error_message,exitCode:e.exit_code})),_=e.error_category??Xt(f),h=xi(e.exit_code,!1),g=e.command.trim().length>0?e.command:"<unknown>",y=$e(g),E=e.command_resolution??rt({ok:!1,errorCode:f,errorCategory:_}),w=e.resolution_stage??"unknown",b={schema_version:ur,event_id:J.randomUUID(),event_type:"command_error",occurred_at:l,installation_id:i,session_id:lr,command:O(g,"redacted"),payload:ZS({captureLevel:s,pmVersion:a,sourceContext:c,command:g,commandTaxonomy:y,commandResolution:E,resolutionStage:w,args:e.args,options:e.options,pmRootHash:u,cwdHash:d,installationId:i,errorCode:f,errorCategory:_,exitCode:h,errorMessage:e.error_message})};return await cr(t,b),o},t,Ei);r&&await vi(t,r.endpoint,r.retentionDays)}catch{}}function fN(e){let t=e?.trim()??"";return/^[A-Za-z][A-Za-z0-9+.-]*:\/\//u.test(t)||/^(?:github|gitlab|jira|linear):/iu.test(t)}function mN(e){let t=e?.trim().toLowerCase();return t==="global"||t==="external"}export{ul as a,zr as b,fs as c,dl as d,xx as e,ds as f,dn as g,hs as h,ys as i,ll as j,fl as k,ml as l,pl as m,Ix as n,qr as o,Sl as p,vx as q,xl as r,Rx as s,At as t,Tl as u,Ct as v,Ox as w,Al as x,ln as y,kx as z,We as A,Il as B,vl as C,Dx as D,Wr as E,Fx as F,jx as G,It as H,zx as I,Ts as J,Fl as K,tb as L,zl as M,Vl as N,ql as O,Bl as P,sb as Q,Yl as R,fn as S,vt as T,Zl as U,nf as V,fb as W,uf as X,pb as Y,df as Z,lf as _,_b as $,Gr as aa,$s as ba,hf as ca,Kr as da,yf as ea,pn as fa,Fs as ga,Cf as ha,zs as ia,Ye as ja,de as ka,kf as la,Yb as ma,Lf as na,Vs as oa,Mf as pa,$f as qa,Df as ra,Ff as sa,jf as ta,oT as ua,Vf as va,dT as wa,Wf as xa,Gf as ya,Kf as za,Xf as Aa,Jf as Ba,Zr as Ca,em as Da,ET as Ea,wT as Fa,ST as Ga,xT as Ha,bT as Ia,TT as Ja,AT as Ka,om as La,im as Ma,sm as Na,am as Oa,cm as Pa,um as Qa,Ge as Ra,sa as Sa,Fm as Ta,WT as Ua,Rt as Va,Ym as Wa,pa as Xa,no as Ya,_a as Za,tA as _a,Km as $a,Jm as ab,Zm as bb,Qm as cb,ep as db,ro as eb,EA as fb,rC as gb,IA as hb,vA as ib,RA as jb,va as kb,yp as lb,mo as mb,VA as nb,po as ob,Dt as pb,Je as qb,Ft as rb,n_ as sb,za as tb,r_ as ub,PC as vb,yo as wb,Ua as xb,l_ as yb,DC as zb,f_ as Ab,m_ as Bb,HC as Cb,Ln as Db,Ka as Eb,wo as Fb,C_ as Gb,I_ as Hb,WC as Ib,Xa as Jb,Ze as Kb,So as Lb,bo as Mb,Fn as Nb,oI as Ob,ko as Pb,zn as Qb,rc as Rb,Un as Sb,No as Tb,Lo as Ub,Mo as Vb,$o as Wb,uc as Xb,dc as Yb,ic as Zb,bh as _b,tt as $b,qt as ac,Ch as bc,qn as cc,CI as dc,K as ec,Le as fc,Lh as gc,Sc as hc,xc as ic,bc as jc,Ph as kc,NI as lc,zh as mc,LI as nc,MI as oc,Bt as pc,Hc as qc,Cy as rc,Wt as sc,GI as tc,KI as uc,Iy as vc,vy as wc,XI as xc,JI as yc,rt as zc,jy as Ac,zy as Bc,Uy as Cc,Vy as Dc,Wy as Ec,Yy as Fc,Ky as Gc,$E as Hc,zu as Ic,XE as Jc,ku as Kc,JE as Lc,mv as Mc,ew as Nc,tw as Oc,pv as Pc,ei as Qc,Vu as Rc,Uu as Sc,ow as Tc,iw as Uc,Hu as Vc,Iv as Wc,vv as Xc,Gu as Yc,Ku as Zc,Xu as _c,Rv as $c,Qu as ad,fw as bd,ed as cd,Ov as dd,kv as ed,Nv as fd,td as gd,Lv as hd,pw as id,_w as jd,hw as kd,ww as ld,xw as md,Tw as nd,Aw as od,Rw as pd,kw as qd,Nw as rd,ir as sd,Uw as td,Vw as ud,Zw as vd,ur as wd,Od as xd,Ee as yd,zR as zd,_x as Ad,hx as Bd,yx as Cd,fN as Dd,mN as Ed};
125
- //# sourceMappingURL=chunk-TZY5MVJF.js.map
125
+ //# sourceMappingURL=chunk-YOPTAIBD.js.map