@unbrained/pm-cli 2026.9.22 → 2026.9.25

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 (107) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/AGENTS.md +6 -20
  3. package/CHANGELOG.md +43 -0
  4. package/dist/cli/error-guidance.d.ts +9 -0
  5. package/dist/cli/error-guidance.js +1 -1
  6. package/dist/cli/help-content.js +1 -1
  7. package/dist/cli-bundle/bundle-manifest.json +144 -144
  8. package/dist/cli-bundle/chunks/{chunk-BJBBOUYQ.js → chunk-25KTCTBL.js} +2 -2
  9. package/dist/cli-bundle/chunks/{chunk-UDNYAMCM.js → chunk-3IB4THWX.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-3OFFMS2N.js → chunk-445ARBKY.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-SBTT42A4.js → chunk-5AP67ZXH.js} +3 -3
  12. package/dist/cli-bundle/chunks/{chunk-JSW33Q6R.js → chunk-COFQCKF4.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-4XOV7Q5R.js → chunk-CZ3VJJEA.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-ZSPZJOMK.js → chunk-GAU55CWI.js} +28 -28
  15. package/dist/cli-bundle/chunks/{chunk-ML42DLI3.js → chunk-GOWZEBTH.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-CM57QHVK.js → chunk-JDHWZYZU.js} +73 -73
  17. package/dist/cli-bundle/chunks/{chunk-GFTN5OS4.js → chunk-P7ZSJOWH.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-AVWHZUNC.js → chunk-YABJDOOX.js} +63 -62
  19. package/dist/cli-bundle/chunks/{chunk-D2OV2UBV.js → chunk-YDIGMRLZ.js} +2 -2
  20. package/dist/cli-bundle/chunks/{register-list-query-VOS5CBX4.js → register-list-query-IZ7ZVTDE.js} +2 -2
  21. package/dist/cli-bundle/chunks/{register-mutation-LWZH6UFJ.js → register-mutation-IPAZTFDZ.js} +2 -2
  22. package/dist/cli-bundle/chunks/{register-operations-YJK4DNFZ.js → register-operations-APN33LNI.js} +2 -2
  23. package/dist/cli-bundle/chunks/{register-setup-Q3CYF67Q.js → register-setup-HPHIKG5U.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-CASXNCNQ.js → chunk-ABA3KRPY.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-XR5EBU3B.js → chunk-HQPTDJLF.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/{chunk-PRMQTT7X.js → chunk-IXNNMP2R.js} +2 -2
  27. package/dist/cli-bundle/focused-chunks/chunk-KRIHJH5U.js +75 -0
  28. package/dist/cli-bundle/focused-chunks/{chunk-QFEDRPPI.js → chunk-MK5AKKHK.js} +2 -2
  29. package/dist/cli-bundle/focused-chunks/{chunk-LH24XUPJ.js → chunk-NRHTXBTI.js} +2 -2
  30. package/dist/cli-bundle/focused-chunks/{chunk-URH727T5.js → chunk-NVVB2HJC.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/{chunk-TSI73EEM.js → chunk-O7MIBEMK.js} +2 -2
  32. package/dist/cli-bundle/focused-chunks/{chunk-V2NARGRH.js → chunk-OY3VHCTX.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/{chunk-UT7VS4X2.js → chunk-PMPFLA6X.js} +2 -2
  34. package/dist/cli-bundle/focused-chunks/{chunk-FKYUTTFL.js → chunk-Q355NPLH.js} +28 -28
  35. package/dist/cli-bundle/focused-chunks/{chunk-JCD5YESL.js → chunk-TLF6N56J.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-MXESHALQ.js → chunk-UIFVIE5F.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-IOL25GKH.js → chunk-V2X37U6J.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-AO5FR7PN.js → chunk-XKH2FC5D.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-UAU4DJSR.js → chunk-Y2M4QLAA.js} +2 -2
  40. package/dist/cli-bundle/main.js +22 -22
  41. package/dist/cli-bundle/sdk-authoring.js +1 -1
  42. package/dist/cli-bundle/sdk-contracts.js +1 -1
  43. package/dist/cli-bundle/sdk-core.js +30 -45
  44. package/dist/cli-bundle/sdk-governance.js +1 -1
  45. package/dist/cli-bundle/sdk-graph.js +1 -1
  46. package/dist/cli-bundle/sdk-merge.js +58 -42
  47. package/dist/cli-bundle/sdk-query.js +1 -1
  48. package/dist/cli-bundle/sdk-runtime.js +1 -1
  49. package/dist/cli-bundle/sdk-testing.js +1 -1
  50. package/dist/cli-bundle/sdk.js +9 -10
  51. package/dist/core/policy/workflow-policy-store.js +1 -1
  52. package/dist/core/shared/errors.d.ts +13 -0
  53. package/dist/core/shared/errors.js +1 -1
  54. package/dist/sdk/cli-contracts/commander-types.d.ts +11 -11
  55. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  56. package/dist/sdk/completion/bash.js +1 -1
  57. package/dist/sdk/governance/health.d.ts +1 -1
  58. package/dist/sdk/governance/health.js +1 -1
  59. package/dist/sdk/init-agent-guidance.d.ts +2 -1
  60. package/dist/sdk/init-agent-guidance.js +2 -2
  61. package/dist/sdk/merge/install.js +2 -2
  62. package/dist/sdk/merge/worktree-config.d.ts +9 -0
  63. package/dist/sdk/merge/worktree-config.js +2 -0
  64. package/dist/sdk/pagination.js +1 -1
  65. package/dist/sdk/public-surface.json +1 -1
  66. package/docs/AGENT_RECOVERY_AND_GUIDANCE.md +49 -0
  67. package/docs/CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md +2 -0
  68. package/docs/CLAUDE_CODE_PLUGIN.md +18 -7
  69. package/docs/CODEX_PLUGIN.md +5 -12
  70. package/docs/DEFECT_RECURRENCE.md +8 -1
  71. package/docs/DEPENDENCY_KIND_CONTRACT.md +27 -0
  72. package/docs/MERGE_SAFETY.md +28 -5
  73. package/docs/QUALITY_EVIDENCE.md +70 -0
  74. package/docs/README.md +1 -0
  75. package/docs/RELEASE_RELIABILITY.md +70 -0
  76. package/docs/RELEASING.md +4 -0
  77. package/docs/TESTING.md +25 -0
  78. package/docs/VALIDATION_PORTABILITY.md +20 -11
  79. package/marketplace.json +2 -2
  80. package/package.json +12 -6
  81. package/packages/pm-beads/package.json +1 -1
  82. package/packages/pm-calendar/package.json +1 -1
  83. package/packages/pm-command-kit/package.json +1 -1
  84. package/packages/pm-digital-twin/package.json +1 -1
  85. package/packages/pm-governance-audit/package.json +1 -1
  86. package/packages/pm-guide-shell/package.json +1 -1
  87. package/packages/pm-kanban/package.json +1 -1
  88. package/packages/pm-lifecycle-hooks/package.json +1 -1
  89. package/packages/pm-linked-test-adapters/package.json +1 -1
  90. package/packages/pm-search-advanced/package.json +1 -1
  91. package/packages/pm-templates/package.json +1 -1
  92. package/packages/pm-todos/package.json +1 -1
  93. package/packages/pm-vcs/package.json +1 -1
  94. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  95. package/plugins/pm-claude/README.md +6 -5
  96. package/plugins/pm-claude/hooks/hooks.json +1 -1
  97. package/plugins/pm-claude/hooks/session-start.mjs +9 -6
  98. package/plugins/pm-claude/package.json +9 -0
  99. package/plugins/pm-claude/scripts/plugin-runtime.mjs +84 -0
  100. package/plugins/pm-claude/scripts/pm-mcp-server.mjs +39 -96
  101. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  102. package/plugins/pm-codex/.mcp.json +0 -3
  103. package/plugins/pm-codex/README.md +1 -1
  104. package/plugins/pm-codex/package.json +9 -0
  105. package/plugins/pm-codex/scripts/plugin-runtime.mjs +84 -0
  106. package/plugins/pm-codex/scripts/pm-mcp-server.mjs +38 -99
  107. package/dist/cli-bundle/focused-chunks/chunk-QYN77MQP.js +0 -59
@@ -1,2 +1,2 @@
1
- import{$g as v,Ef as $,Uc as w,Vc as S,Wc as L,Xc as A,Yc as b,Zc as _,Ze as F,Zn as y,_e as D,_g as B,ad as M,cf as V,g as P,h as m,j as E,k as N,la as p,na as h,tb as I}from"./chunk-CM57QHVK.js";import{Command as Q}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59132bc6-2d45-5049-981f-fadcf0c75091")}catch{}})();function Ge(e){return new Q().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{$(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the result encoding for reads and mutations").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include row selectors, encoding metadata, and read-output receipts").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdf3dec8-63d1-5ea6-a413-64be0ae8f69f")}catch{}})();function je(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function ee(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function te(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ke(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function Ye(e,t){if(e instanceof Error)return e;let n=new Error(t),o=ee(e);return o!==void 0&&(n.exitCode=te(o)),n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d22b586a-5c12-518e-b1ee-4baa0d04243b")}catch{}})();function Qe(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let n=B();v(t);let o=!1;return()=>{o||(o=!0,n===void 0?v(void 0):v(n))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69117358-9878-589b-8918-e71599e6c7df")}catch{}})();var f=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function C(e,t,n,o){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:n,required:`${f.clock} and ${f.seed}; ${f.tickMs} is optional`,nextSteps:[`Set ${f.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${f.seed} to a non-empty reproducibility seed.`,`Optionally set ${f.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:o,missing_required_fields:t==="incomplete"?[f.clock,f.seed].filter(i=>!o.includes(i)):void 0}})}function ne(e){let t=e[f.clock],n=e[f.tickMs],o=e[f.seed],i=[[f.clock,t],[f.tickMs,n],[f.seed,o]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||o===void 0)throw C("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?f.clock:f.seed,i);if(o.trim().length===0)throw C(`${f.seed} must not be empty.`,"invalid_value",f.seed,i);if(!V(t))throw C(`${f.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",f.clock,i);let s=n===void 0?1:Number(n);if(n?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw C(`${f.tickMs} must be a non-negative integer.`,"invalid_value",f.tickMs,i);return F({clock:t,seed:o,tickMs:s})}function oe(e){let t=ne(e);return t===void 0?n=>n():D(t)}async function st(e,t){return oe(e)(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e1db7644-e481-5049-a773-fcffa09f1779")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),ie=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function se(e,t,n){let o=R.has(n)?t+1:void 0,i=b(e.slice(t+1));if(i===void 0)return o;let s=t+1+i,a=`${n} ${e[s]}`,r=m(a);return r===a?n==="item"&&e[s]==="complete"?s+1:o:G(r)?O(e,s,r):void 0}function O(e,t,n){if(["history","context","ctx","update","close","item"].includes(n))return se(e,t,n);let o=z.get(n);if(o===void 0)return t+1;let i=e[t+1]?.toLowerCase()===o;return t+(i?2:1)}function re(e){let t=new Map;for(let n of y(e))for(let o of[n.flag,n.short,...n.aliases??[]])o&&t.set(o,n);return t}function ae(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o==="--id"?(t.push({index:n,consumed:2,value:e[n+1]}),n+=1):o.startsWith("--id=")&&t.push({index:n,consumed:1,value:o.slice(5)})}return t}function ce(e,t,n){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let i=n.get(e);return i!==void 0&&i.value_type!=="boolean"}function le(e,t,n,o,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<o)return!0;s+=1;continue}ce(r,e[a+1],i)&&(a+=1)}}return s>(ie.get(m(n))??0)}function W(e){let t=b(e),n=t===void 0?void 0:e[t]?.toLowerCase();if(n!=="context"&&n!=="ctx"&&!G(n))return{argv:[...e],changed:!1,conflict:!1};let o=O(e,t,n);if(o===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=o>t+1?`${m(e.slice(t,o-1).join(" "))} ${e[o-1]}`:n,s=re(i),a=ae(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||le(e,o,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let c=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],l=b(c),u=O(c,l,n);return c.splice(u,0,r.value),{argv:c,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ef3b254-0494-57bc-8bbf-8ee58eb7d152")}catch{}})();var ue=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function de(e,t,n){let o=e[t];if(S.has(o))return n.booleanFlags.add(o),1;let i=o.indexOf("="),s=i>0?o.slice(0,i):o;if(!w.has(s))return 1;let a=i>0?o.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),c=a??(r?e[t+1]:void 0);return s==="--author"?n.author=c??"":typeof c=="string"&&c.length>0&&(ue.has(s)?n.outputValues:n.pathValues).set(s,c),r?2:1}function fe(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},n=0;for(;n<e.length&&e[n]!=="--";)n+=de(e,n,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json"),quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...t.outputValues.get("--output-format")==="toon"||t.outputValues.get("--output-format")==="json"?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function j(e){let t=[],n=0;for(;n<e.length;){let o=e[n];if(o==="--")break;if(S.has(o)||o==="--profile"||o==="--id-only"||o==="--full-changed-fields"||o==="--explain"){n+=1;continue}if(w.has(o)){n+=A(o,e[n+1])?2:1;continue}if(L(o)){n+=1;continue}t.push(o),n+=1}return t}function pe(e){let t=j(e);if(t[0]?.trim().toLowerCase()==="help"){let s=[];for(let a=1;a<t.length;a+=1){let r=t[a];if(r.startsWith("-"))break;s.push(r.trim().toLowerCase())}return{requested:!0,commandPathTokens:s}}if(t.findIndex(s=>s==="--help"||s==="-h")<0)return{requested:!1,commandPathTokens:[]};let i=[];for(let s of t){if(s.startsWith("-"))break;i.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:i}}function k(e){return b(e)}function me(e){return _(e)}function he(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:pe(e).requested}function _t(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],n=t.map(s=>process.env[s]),o=()=>{for(let[s,a]of t.entries()){let r=n[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=fe(e);return he(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),o}var ge=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function be(e){let t=k(e);if(t===void 0||e[t]!=="extension")return[...e];let n=e[t+1];if(!n||n.startsWith("-"))return[...e];if(!ge.has(n))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let o=`--${n}`;return e.includes(o)?[...e]:[...e.slice(0,t+1),o,...e.slice(t+2)]}var ye=new Set(["pm","pm-cli"]);function we(e,t){let n=k(e);if(n===void 0)return e;let o=e[n];return ye.has(o.trim().toLowerCase())?(t.push({from:o,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,n),...e.slice(n+1)]):e}function Ie(e,t){let n=k(e);if(n!==void 0&&e[n]==="help"){let r=k(e.slice(n+1));n=r===void 0?void 0:n+1+r}if(n===void 0)return e;let o=e[n],i=N[o.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,n),...s,...e.slice(n+1)];return t.push({from:o,to:s,reason:"command_alias",confidence:"high"}),a}function x(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function U(e){return x(e).replace(/-/g,"")}function q(e,t,n){let o=e.get(t);if(o===void 0){e.set(t,n);return}o!==n&&e.set(t,null)}function _e(e){let t=[],n=o=>{typeof o=="string"&&o.startsWith("--")&&t.push(o)};n(e.flag);for(let o of e.aliases??[])n(o);return t}function ve(e,t){let n=t??y(e),o=new Map,i=new Map,s=new Map,a=new Set;for(let r of n){let c=_e(r);if(c.length===0)continue;let l=`--${x(c[0])}`;for(let d of c)q(o,x(d),l),q(i,U(d),l);let u=U(l);s.has(l)||s.set(l,u),r.list===!0&&a.add(l)}return{canonicalByNormalized:o,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,c])=>({canonicalFlag:r,comparable:c})),listCanonicalFlags:a}}function K(e,t){let n=x(e),o=t.canonicalByNormalized.get(n);if(typeof o=="string")return{flag:o,reason:"flag_alias",confidence:"high"};let i=n.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,c,l=!1;for(let u of t.canonicalComparables){let d=I(i,u.comparable,a);if(d!==null){if(d<r){r=d,c=u.canonicalFlag,l=!1;continue}d===r&&c!==u.canonicalFlag&&(l=!0)}}return!c||l||!Number.isFinite(r)||r<=0?null:{flag:c,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function vt(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ce(e,t=!1){if(t||e.includes("://"))return null;let n=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!n)return null;let o=n[1],i=n[3];return i.length===0?null:{key:o,value:i}}function ke(e,t,n=!1){if(n||!e.startsWith("--"))return{tokens:[e]};let o=e.indexOf("="),i=o>=0?e.slice(0,o):e,s=o>=0?e.slice(o+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function xe(e){let t=new Set,n=!1;for(let o=0;o<e.length;o+=1){if(n){t.add(o),n=!1;continue}let i=e[o];n=i==="--path"||i==="--pm-path"}return t}function Te(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function Ee(e,t,n){n.push(e[t]);let o=e[t+1];return typeof o=="string"&&o!=="--"?(n.push(o),t+2):t+1}function Se(e,t,n,o){if(n.inlineValue!==void 0)return{originalTokens:[e[t]],value:n.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||o.has(n.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Ae(e,t,n,o){let i=e.get(n);if(i){i.values.push(o.value),i.occurrences+=1;return}e.set(n,{outputIndex:t.length,originalTokens:o.originalTokens,values:[o.value],occurrences:1}),t.push(null)}function Oe(e,t){let n=[],o=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){o.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let r=`${i}=${s.values.join(",")}`;o.push({outputIndex:s.outputIndex,tokens:[r]}),n.push({from:`${i} (x${s.occurrences})`,to:[r],reason:"list_merge",confidence:"high"})}return{events:n,splices:o}}function Pe(e,t){t.sort((n,o)=>o.outputIndex-n.outputIndex);for(let n of t)e.splice(n.outputIndex,1,...n.tokens)}function Ne(e,t,n=new Set,o=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let l=e[a];if(l==="--"){i.push(...e.slice(a));break}if(n.has(l)){a=Ee(e,a,i);continue}let u=Te(l);if(!u||!t.has(u.flag)){i.push(l),a+=1;continue}let d=Se(e,a,u,o);if(d.value===void 0){i.push(l),a+=d.consumed;continue}Ae(s,i,u.flag,{originalTokens:d.originalTokens,value:d.value}),a+=d.consumed}let{events:r,splices:c}=Oe(s,o);return Pe(i,c),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Le(e,t){if(e!=="test"||t.length<2)return!1;let n=t[t.length-1],o=t[t.length-2],i=Y.get(o);return i!==void 0&&i.has(n)}function Me(e,t){return e==="search"||Le(e,t)}function Fe(e,t,n){if(t!=="test")return e;let o=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return o.push(...e.slice(i)),o;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){o.push(s),i+=1;continue}let c=i+2;for(;c<e.length&&!e[c].startsWith("-");)c+=1;if(c-(i+2)!==1){o.push(s),i+=1;continue}let l=e[i+2],u=`${r}=${l}`;o.push(s,u),n.push({from:`${s} ${r} ${l}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return o}function De(e,t,n,o){let i=[],s=xe(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let c=s.has(a),l=i[i.length-1];if(r.startsWith("--")){let d=ke(r,t,c);i.push(...d.tokens),d.event&&o.push(d.event);continue}let u=Ce(r,c);if(u&&!(typeof l=="string"&&l.startsWith("-"))&&!Me(n,i)){let d=K(u.key,t);if(d){let g=[d.flag,u.value];i.push(...g),o.push({from:r,to:g,reason:"bare_key_value",confidence:d.confidence});continue}}i.push(r)}return i}function Ve(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--verify"){let o=e[t+1];if(o===void 0||o==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${o}`)}else(w.has(n)||n==="--output"||n==="--hash-algorithm")&&(t+=1)}}function Ct(e){let t=[],n=we(e,t),o=be(n);(o.length!==n.length||o.some((T,J)=>T!==n[J]))&&t.push({from:n.join(" "),to:[...o],reason:"legacy_extension_action",confidence:"high"});let i=Ie(o,t),s=W(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=me(s.argv),r=X(s.argv),c=m(r??a??""),l=ve(r??a),u=De(s.argv,l,c,t),d=Fe(u,c,t),g=Ne(d,l.listCanonicalFlags,w,a==="create"?new Set(["--tags"]):new Set);for(let T of g.events)t.push(T);return r==="history attest"&&Ve(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=j(e),n=t[0]?.trim().toLowerCase(),o=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(n==="extension"||n==="package"||n==="packages")&&typeof o=="string"&&o.length>0&&!o.startsWith("-")?`${n} ${o}`:n}function kt(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--type"){let o=e[t+1];if(typeof o=="string"&&o.trim().length>0)return o.trim();continue}if(n.startsWith("--type=")){let o=n.slice(7).trim();if(o.length>0)return o}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function At(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function $e(e,t){let n=Z(t);if(!n)return;let o=y(e).find(i=>i.flag===n||i.aliases?.includes(n));return o?o.value_type==="boolean"?null:`<${o.value_name??"value"}>`:"<value>"}function Ot(e,t,n){let o=[...e],i=o.indexOf("--"),s=i<0?o.length:i;for(let a of n){let r=Z(a);if(!r||o.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let c=$e(t,r),l=c?[r,c]:[r];o.splice(s,0,...l),s+=l.length}return o.length===e.length?void 0:M(o)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="925e5fec-4cc0-5315-a331-03cb128893f0")}catch{}})();var Be={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" "),s=Be[o]?.indexOf(m(n));if(s!==void 0&&s>=0)return s;if(n===o)return 10;if(i.includes(o))return 11;if(i.some(c=>c.startsWith(o)))return 12;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let c of i){let l=I(c,o,a);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?20+r:n.includes(o)?30:Number.POSITIVE_INFINITY}function Vt(e,t){return e.map(n=>({path:n,score:H(n,t)})).filter(n=>Number.isFinite(n.score)).sort((n,o)=>n.score!==o.score?n.score-o.score:n.path===o.path?0:n.path<o.path?-1:1).map(n=>n.path)}function $t(e,t,n){let o=new Set(t),i=E.filter(r=>r.lifecycle==="deprecated").slice().sort((r,c)=>c.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let c=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),l=r;if(c){let u=r.slice(c.alias.length);if(!o.has(`${c.canonical}${u}`))return[];l=`${c.canonical_argv.join(" ")}${u}`}return n!==void 0&&H(r,n)<10&&s.push(l),[l]});return[...new Set(s.length>0?s:a)]}export{Ge as a,je as b,ee as c,te as d,Ke as e,Ye as f,Qe as g,f as h,ne as i,oe as j,st as k,G as l,W as m,fe as n,j as o,pe as p,k as q,me as r,_t as s,be as t,vt as u,Ne as v,Fe as w,Ct as x,kt as y,At as z,$e as A,Ot as B,H as C,Vt as D,$t as E};
2
- //# sourceMappingURL=chunk-BJBBOUYQ.js.map
1
+ import{$g as v,Ef as $,Uc as w,Vc as S,Wc as L,Xc as A,Yc as b,Zc as _,Ze as F,Zn as y,_e as D,_g as B,ad as M,cf as V,g as P,h as m,j as E,k as N,la as p,na as h,tb as I}from"./chunk-JDHWZYZU.js";import{Command as Q}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59132bc6-2d45-5049-981f-fadcf0c75091")}catch{}})();function Ge(e){return new Q().name("pm").description("Universal, flexible, extensible, agent-optimized project management CLI for any project or programming language.").version(e).showHelpAfterError(!1).allowExcessArguments(!1).allowUnknownOption(!1).configureOutput({writeOut:t=>{$(t)},writeErr:()=>{}}).option("--json","Output JSON instead of TOON; mutations emit a flat receipt with top-level id/status/changed_field_count while reads use documented entity or collection envelopes").option("--lean","Omit null and empty containers from JSON output").option("--token-accounting","Attach a bounded per-section token-cost receipt to command output").option("--output-include <fields>","Retain comma-separated fields or sections in read output").option("--output-limit <count>","Bound rows in read output").option("--output-budget <tokens|unbounded>","Bound estimated tokens in read output or explicitly disable the default ceiling").option("--output-format <toon|json>","Select the result encoding for reads and mutations").option("--output-session <state>","Carry a JSON session budget and served-item ledger across read calls").option("--output-cursor <cursor>","Resume a budget-compacted declared row collection").option("--output-row-contract","Include row selectors, encoding metadata, and read-output receipts").option("--quiet","Suppress stdout output").option("--no-changed-fields","Omit the changed_fields array from mutation output (keeps changed_field_count)").option("--full-changed-fields","Restore the legacy full mutation envelope and changed_fields array").option("--id-only","Print only id and status for single-item mutation output").option("--pm-path <dir>","Explicit tracker storage path for this command (preferred over --path)").option("--path <dir>","Backward-compatible alias for --pm-path; this is the tracker storage path, not a workspace cwd").option("--no-extensions","Disable extension loading").option("--no-pager","Disable pager integration for help and long output").option("--explain","Render extended rationale and examples in help output").option("--all","Reveal every public command and compatibility alias").option("--profile","Print deterministic timing diagnostics").option("--author <id>","Override mutation author for this invocation").exitOverride()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bdf3dec8-63d1-5ea6-a413-64be0ae8f69f")}catch{}})();function je(e){return e instanceof h||e instanceof Error?e.message:"Unknown failure"}function ee(e){if(typeof e!="object"||e===null||!("exitCode"in e))return;let t=e.exitCode;return typeof t=="number"&&Number.isFinite(t)?t:void 0}function te(e){let t=Math.trunc(e);return t>p.SUCCESS?t:p.GENERIC_FAILURE}function Ke(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&e.code.startsWith("commander.")}function Ye(e,t){if(e instanceof Error)return e;let n=new Error(t),o=ee(e);return o!==void 0&&(n.exitCode=te(o)),n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d22b586a-5c12-518e-b1ee-4baa0d04243b")}catch{}})();function Qe(e){if(e===void 0)return()=>{};let t=e.trim();if(t.length===0)throw new h("--author requires a non-empty value.",p.USAGE,{code:"missing_required_argument",nextSteps:["Pass an explicit author identifier with --author <id>."]});let n=B();v(t);let o=!1;return()=>{o||(o=!0,n===void 0?v(void 0):v(n))}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="69117358-9878-589b-8918-e71599e6c7df")}catch{}})();var f=Object.freeze({clock:"PM_CLOCK",tickMs:"PM_CLOCK_TICK_MS",seed:"PM_SEED"});function C(e,t,n,o){return new h(e,p.USAGE,{code:"invalid_reproducible_process_environment",reason:t,field:n,required:`${f.clock} and ${f.seed}; ${f.tickMs} is optional`,nextSteps:[`Set ${f.clock} to an ISO-8601 instant with Z or a numeric UTC offset and ${f.seed} to a non-empty reproducibility seed.`,`Optionally set ${f.tickMs} to a non-negative integer; it defaults to 1.`,"Unset all three variables to retain normal wall-clock and cryptographic-random behavior."],recovery:{recovery_mode:"compact",provided_fields:o,missing_required_fields:t==="incomplete"?[f.clock,f.seed].filter(i=>!o.includes(i)):void 0}})}function ne(e){let t=e[f.clock],n=e[f.tickMs],o=e[f.seed],i=[[f.clock,t],[f.tickMs,n],[f.seed,o]].filter(a=>a[1]!==void 0).map(([a])=>a);if(i.length===0)return;if(t===void 0||o===void 0)throw C("Reproducible process execution requires PM_CLOCK and PM_SEED together.","incomplete",t===void 0?f.clock:f.seed,i);if(o.trim().length===0)throw C(`${f.seed} must not be empty.`,"invalid_value",f.seed,i);if(!V(t))throw C(`${f.clock} must be a valid ISO-8601 instant with Z or a numeric UTC offset.`,"invalid_value",f.clock,i);let s=n===void 0?1:Number(n);if(n?.trim().length===0||!Number.isSafeInteger(s)||s<0)throw C(`${f.tickMs} must be a non-negative integer.`,"invalid_value",f.tickMs,i);return F({clock:t,seed:o,tickMs:s})}function oe(e){let t=ne(e);return t===void 0?n=>n():D(t)}async function st(e,t){return oe(e)(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e1db7644-e481-5049-a773-fcffa09f1779")}catch{}})();var R=new Set(["append","claim","close","close-task","comments","copy","delete","deps","docs","files","focus","get","history","history-compact","history-redact","history-repair","learnings","notes","pause-task","release","restore","start-task","test","update"]),z=new Map([["files","discover"],["item","complete"]]),ie=new Map([["append",1],["close",1],["close-task",1],["comments",1],["item complete",1],["learnings",1],["notes",1],["restore",1]]);function G(e){let t=m(e?.trim().toLowerCase()??"");return R.has(t)||z.has(t)}function se(e,t,n){let o=R.has(n)?t+1:void 0,i=b(e.slice(t+1));if(i===void 0)return o;let s=t+1+i,a=`${n} ${e[s]}`,r=m(a);return r===a?n==="item"&&e[s]==="complete"?s+1:o:G(r)?O(e,s,r):void 0}function O(e,t,n){if(["history","context","ctx","update","close","item"].includes(n))return se(e,t,n);let o=z.get(n);if(o===void 0)return t+1;let i=e[t+1]?.toLowerCase()===o;return t+(i?2:1)}function re(e){let t=new Map;for(let n of y(e))for(let o of[n.flag,n.short,...n.aliases??[]])o&&t.set(o,n);return t}function ae(e){let t=[];for(let n=0;n<e.length;n+=1){let o=e[n];if(o==="--")break;o==="--id"?(t.push({index:n,consumed:2,value:e[n+1]}),n+=1):o.startsWith("--id=")&&t.push({index:n,consumed:1,value:o.slice(5)})}return t}function ce(e,t,n){if(e.indexOf("=")>=0||t===void 0||t.startsWith("-"))return!1;let i=n.get(e);return i!==void 0&&i.value_type!=="boolean"}function le(e,t,n,o,i){let s=0;for(let a=t;a<e.length;a+=1){let r=e[a];if(r==="--")break;if(r==="--id"){a+=1;continue}if(!r.startsWith("--id=")){if(!r.startsWith("-")){if(a<o)return!0;s+=1;continue}ce(r,e[a+1],i)&&(a+=1)}}return s>(ie.get(m(n))??0)}function W(e){let t=b(e),n=t===void 0?void 0:e[t]?.toLowerCase();if(n!=="context"&&n!=="ctx"&&!G(n))return{argv:[...e],changed:!1,conflict:!1};let o=O(e,t,n);if(o===void 0)return{argv:[...e],changed:!1,conflict:!1};let i=o>t+1?`${m(e.slice(t,o-1).join(" "))} ${e[o-1]}`:n,s=re(i),a=ae(e),r=a[0];if(!r||!r.value?.trim())return{argv:[...e],changed:!1,conflict:!1};if(a.length>1||le(e,o,i,r.index,s))return{argv:[...e],changed:!1,conflict:!0,itemId:r.value};let c=[...e.slice(0,r.index),...e.slice(r.index+r.consumed)],l=b(c),u=O(c,l,n);return c.splice(u,0,r.value),{argv:c,changed:!0,conflict:!1,itemId:r.value}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8ef3b254-0494-57bc-8bbf-8ee58eb7d152")}catch{}})();var ue=new Set(["--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor"]);function de(e,t,n){let o=e[t];if(S.has(o))return n.booleanFlags.add(o),1;let i=o.indexOf("="),s=i>0?o.slice(0,i):o;if(!w.has(s))return 1;let a=i>0?o.slice(i+1):void 0,r=a===void 0&&A(s,e[t+1]),c=a??(r?e[t+1]:void 0);return s==="--author"?n.author=c??"":typeof c=="string"&&c.length>0&&(ue.has(s)?n.outputValues:n.pathValues).set(s,c),r?2:1}function fe(e){let t={booleanFlags:new Set,outputValues:new Map,pathValues:new Map},n=0;for(;n<e.length&&e[n]!=="--";)n+=de(e,n,t);return{path:t.pathValues.get("--pm-path")??t.pathValues.get("--path"),noExtensions:t.booleanFlags.has("--no-extensions")||["history attest","history-attest"].includes(X(e)??""),noPager:t.booleanFlags.has("--no-pager"),json:t.booleanFlags.has("--json"),quiet:t.booleanFlags.has("--quiet"),lean:t.booleanFlags.has("--lean"),tokenAccounting:t.booleanFlags.has("--token-accounting"),...t.booleanFlags.has("--output-row-contract")?{outputRowContract:!0}:{},...t.outputValues.get("--output-include")===void 0?{}:{outputInclude:t.outputValues.get("--output-include")},...t.outputValues.get("--output-limit")===void 0?{}:{outputLimit:t.outputValues.get("--output-limit")},...t.outputValues.get("--output-budget")===void 0?{}:{outputBudget:t.outputValues.get("--output-budget")},...t.outputValues.get("--output-format")==="toon"||t.outputValues.get("--output-format")==="json"?{outputFormat:t.outputValues.get("--output-format")}:{},...t.outputValues.get("--output-session")===void 0?{}:{outputSession:t.outputValues.get("--output-session")},...t.outputValues.get("--output-cursor")===void 0?{}:{outputCursor:t.outputValues.get("--output-cursor")},...t.author===""?{authorMissingValue:!0}:t.author!==void 0?{author:t.author}:{}}}function j(e){let t=[],n=0;for(;n<e.length;){let o=e[n];if(o==="--")break;if(S.has(o)||o==="--profile"||o==="--id-only"||o==="--full-changed-fields"||o==="--explain"){n+=1;continue}if(w.has(o)){n+=A(o,e[n+1])?2:1;continue}if(L(o)){n+=1;continue}t.push(o),n+=1}return t}function pe(e){let t=j(e);if(t[0]?.trim().toLowerCase()==="help"){let s=[];for(let a=1;a<t.length;a+=1){let r=t[a];if(r.startsWith("-"))break;s.push(r.trim().toLowerCase())}return{requested:!0,commandPathTokens:s}}if(t.findIndex(s=>s==="--help"||s==="-h")<0)return{requested:!1,commandPathTokens:[]};let i=[];for(let s of t){if(s.startsWith("-"))break;i.push(s.trim().toLowerCase())}return{requested:!0,commandPathTokens:i}}function k(e){return b(e)}function me(e){return _(e)}function he(e,t){return t.noPager?!0:process.stdout.isTTY===!0?!1:pe(e).requested}function _t(e){let t=["PAGER","MANPAGER","GIT_PAGER","LESS"],n=t.map(s=>process.env[s]),o=()=>{for(let[s,a]of t.entries()){let r=n[s];r===void 0?delete process.env[a]:process.env[a]=r}},i=fe(e);return he(e,i)&&(process.env.PAGER="cat",process.env.MANPAGER="cat",process.env.GIT_PAGER="cat",(typeof process.env.LESS!="string"||process.env.LESS.trim().length===0)&&(process.env.LESS="FRX")),o}var ge=new Set(["install","uninstall","explore","manage","doctor","adopt","adopt-all","activate","deactivate"]);function be(e){let t=k(e);if(t===void 0||e[t]!=="extension")return[...e];let n=e[t+1];if(!n||n.startsWith("-"))return[...e];if(!ge.has(n))return[...e];if(e.includes("--help")||e.includes("-h"))return[...e];let o=`--${n}`;return e.includes(o)?[...e]:[...e.slice(0,t+1),o,...e.slice(t+2)]}var ye=new Set(["pm","pm-cli"]);function we(e,t){let n=k(e);if(n===void 0)return e;let o=e[n];return ye.has(o.trim().toLowerCase())?(t.push({from:o,to:[],reason:"executable_alias",confidence:"high"}),[...e.slice(0,n),...e.slice(n+1)]):e}function Ie(e,t){let n=k(e);if(n!==void 0&&e[n]==="help"){let r=k(e.slice(n+1));n=r===void 0?void 0:n+1+r}if(n===void 0)return e;let o=e[n],i=N[o.trim().toLowerCase()];if(!i)return e;let s=i.split(" "),a=[...e.slice(0,n),...s,...e.slice(n+1)];return t.push({from:o,to:s,reason:"command_alias",confidence:"high"}),a}function x(e){return e.replace(/^--?/,"").replace(/_/g,"-").replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase()}function U(e){return x(e).replace(/-/g,"")}function q(e,t,n){let o=e.get(t);if(o===void 0){e.set(t,n);return}o!==n&&e.set(t,null)}function _e(e){let t=[],n=o=>{typeof o=="string"&&o.startsWith("--")&&t.push(o)};n(e.flag);for(let o of e.aliases??[])n(o);return t}function ve(e,t){let n=t??y(e),o=new Map,i=new Map,s=new Map,a=new Set;for(let r of n){let c=_e(r);if(c.length===0)continue;let l=`--${x(c[0])}`;for(let d of c)q(o,x(d),l),q(i,U(d),l);let u=U(l);s.has(l)||s.set(l,u),r.list===!0&&a.add(l)}return{canonicalByNormalized:o,canonicalByCompact:i,canonicalComparables:[...s.entries()].map(([r,c])=>({canonicalFlag:r,comparable:c})),listCanonicalFlags:a}}function K(e,t){let n=x(e),o=t.canonicalByNormalized.get(n);if(typeof o=="string")return{flag:o,reason:"flag_alias",confidence:"high"};let i=n.replace(/-/g,""),s=t.canonicalByCompact.get(i);if(typeof s=="string")return{flag:s,reason:"flag_alias",confidence:"high"};let a=i.length>=8?2:1,r=Number.POSITIVE_INFINITY,c,l=!1;for(let u of t.canonicalComparables){let d=I(i,u.comparable,a);if(d!==null){if(d<r){r=d,c=u.canonicalFlag,l=!1;continue}d===r&&c!==u.canonicalFlag&&(l=!0)}}return!c||l||!Number.isFinite(r)||r<=0?null:{flag:c,reason:"flag_typo",confidence:r>=2?"medium":"high"}}function vt(e){let t=[`${e}s`];return e.endsWith("y")&&e.length>1&&t.push(`${e.slice(0,-1)}ies`),t}function Ce(e,t=!1){if(t||e.includes("://"))return null;let n=e.match(/^([A-Za-z][A-Za-z0-9_-]{1,63})([:=])(.*)$/);if(!n)return null;let o=n[1],i=n[3];return i.length===0?null:{key:o,value:i}}function ke(e,t,n=!1){if(n||!e.startsWith("--"))return{tokens:[e]};let o=e.indexOf("="),i=o>=0?e.slice(0,o):e,s=o>=0?e.slice(o+1):void 0,a=K(i,t);if(!a)return{tokens:[e]};let r=s===void 0?a.flag:`${a.flag}=${s}`;return r===e?{tokens:[e]}:{tokens:[r],event:{from:e,to:[r],reason:a.reason,confidence:a.confidence}}}function xe(e){let t=new Set,n=!1;for(let o=0;o<e.length;o+=1){if(n){t.add(o),n=!1;continue}let i=e[o];n=i==="--path"||i==="--pm-path"}return t}function Te(e){if(!e.startsWith("--"))return null;let t=e.indexOf("=");return t<0?{flag:e}:{flag:e.slice(0,t),inlineValue:e.slice(t+1)}}function Ee(e,t,n){n.push(e[t]);let o=e[t+1];return typeof o=="string"&&o!=="--"?(n.push(o),t+2):t+1}function Se(e,t,n,o){if(n.inlineValue!==void 0)return{originalTokens:[e[t]],value:n.inlineValue,consumed:1};let i=[],s=t+1;for(;s<e.length&&e[s]!=="--"&&!e[s].startsWith("-")&&(i.length===0||o.has(n.flag));)i.push(e[s]),s+=1;let a=i.length===0?1:1+i.length;return{originalTokens:e.slice(t,t+a),value:i.length===0?void 0:i.join(","),consumed:a}}function Ae(e,t,n,o){let i=e.get(n);if(i){i.values.push(o.value),i.occurrences+=1;return}e.set(n,{outputIndex:t.length,originalTokens:o.originalTokens,values:[o.value],occurrences:1}),t.push(null)}function Oe(e,t){let n=[],o=[];for(let[i,s]of e){if(!(s.occurrences>=2||t.has(i)&&s.originalTokens.length>2)){o.push({outputIndex:s.outputIndex,tokens:s.originalTokens});continue}let r=`${i}=${s.values.join(",")}`;o.push({outputIndex:s.outputIndex,tokens:[r]}),n.push({from:`${i} (x${s.occurrences})`,to:[r],reason:"list_merge",confidence:"high"})}return{events:n,splices:o}}function Pe(e,t){t.sort((n,o)=>o.outputIndex-n.outputIndex);for(let n of t)e.splice(n.outputIndex,1,...n.tokens)}function Ne(e,t,n=new Set,o=new Set){if(t.size===0)return{argv:[...e],events:[]};let i=[],s=new Map,a=0;for(;a<e.length;){let l=e[a];if(l==="--"){i.push(...e.slice(a));break}if(n.has(l)){a=Ee(e,a,i);continue}let u=Te(l);if(!u||!t.has(u.flag)){i.push(l),a+=1;continue}let d=Se(e,a,u,o);if(d.value===void 0){i.push(l),a+=d.consumed;continue}Ae(s,i,u.flag,{originalTokens:d.originalTokens,value:d.value}),a+=d.consumed}let{events:r,splices:c}=Oe(s,o);return Pe(i,c),{argv:i,events:r}}var Y=new Map([["--add",new Set(["command","cmd","path"])],["--remove",new Set(["command","path"])]]);function Le(e,t){if(e!=="test"||t.length<2)return!1;let n=t[t.length-1],o=t[t.length-2],i=Y.get(o);return i!==void 0&&i.has(n)}function Me(e,t){return e==="search"||Le(e,t)}function Fe(e,t,n){if(t!=="test")return e;let o=[],i=0;for(;i<e.length;){let s=e[i];if(s==="--")return o.push(...e.slice(i)),o;let a=Y.get(s),r=a?e[i+1]:void 0;if(!a||typeof r!="string"||!a.has(r)){o.push(s),i+=1;continue}let c=i+2;for(;c<e.length&&!e[c].startsWith("-");)c+=1;if(c-(i+2)!==1){o.push(s),i+=1;continue}let l=e[i+2],u=`${r}=${l}`;o.push(s,u),n.push({from:`${s} ${r} ${l}`,to:[s,u],reason:"bare_key_value",confidence:"high"}),i+=3}return o}function De(e,t,n,o){let i=[],s=xe(e);for(let a=0;a<e.length;a+=1){let r=e[a];if(r==="--"){i.push(...e.slice(a));break}let c=s.has(a),l=i[i.length-1];if(r.startsWith("--")){let d=ke(r,t,c);i.push(...d.tokens),d.event&&o.push(d.event);continue}let u=Ce(r,c);if(u&&!(typeof l=="string"&&l.startsWith("-"))&&!Me(n,i)){let d=K(u.key,t);if(d){let g=[d.flag,u.value];i.push(...g),o.push({from:r,to:g,reason:"bare_key_value",confidence:d.confidence});continue}}i.push(r)}return i}function Ve(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--verify"){let o=e[t+1];if(o===void 0||o==="--")throw new h("history attest --verify requires a bundle file.",p.USAGE);e.splice(t,2,`--verify=${o}`)}else(w.has(n)||n==="--output"||n==="--hash-algorithm")&&(t+=1)}}function Ct(e){let t=[],n=we(e,t),o=be(n);(o.length!==n.length||o.some((T,J)=>T!==n[J]))&&t.push({from:n.join(" "),to:[...o],reason:"legacy_extension_action",confidence:"high"});let i=Ie(o,t),s=W(i);if(s.conflict)throw new h("Provide the item id either positionally or with --id, not both.",p.USAGE);s.changed&&t.push({from:`--id ${s.itemId}`,to:[s.itemId],reason:"item_id_alias",confidence:"high"});let a=me(s.argv),r=X(s.argv),c=m(r??a??""),l=ve(r??a),u=De(s.argv,l,c,t),d=Fe(u,c,t),g=Ne(d,l.listCanonicalFlags,w,a==="create"?new Set(["--tags"]):new Set);for(let T of g.events)t.push(T);return r==="history attest"&&Ve(g.argv),{argv:g.argv,commandName:a,trace:t}}function X(e){let t=j(e),n=t[0]?.trim().toLowerCase(),o=t[1]?.trim().toLowerCase(),i=P(t);return i?i.canonical:(n==="extension"||n==="package"||n==="packages")&&typeof o=="string"&&o.length>0&&!o.startsWith("-")?`${n} ${o}`:n}function kt(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")break;if(n==="--type"){let o=e[t+1];if(typeof o=="string"&&o.trim().length>0)return o.trim();continue}if(n.startsWith("--type=")){let o=n.slice(7).trim();if(o.length>0)return o}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4f7274c6-547e-5590-b7c9-a4d6418bf860")}catch{}})();function Z(e){return e.trim().match(/--[a-z0-9][a-z0-9_-]*/i)?.[0]?.replaceAll("_","-").toLowerCase()}function At(e){if(!(!Array.isArray(e)||e.length===0))return _(e)}function $e(e,t){let n=Z(t);if(!n)return;let o=y(e).find(i=>i.flag===n||i.aliases?.includes(n));return o?o.value_type==="boolean"?null:`<${o.value_name??"value"}>`:"<value>"}function Ot(e,t,n){let o=[...e],i=o.indexOf("--"),s=i<0?o.length:i;for(let a of n){let r=Z(a);if(!r||o.slice(0,s).some(u=>u===r||u.startsWith(`${r}=`)))continue;let c=$e(t,r),l=c?[r,c]:[r];o.splice(s,0,...l),s+=l.length}return o.length===e.length?void 0:M(o)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bd9a8d3b-bc6f-5309-a3fb-7e5f41ef9dab")}catch{}})();(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="925e5fec-4cc0-5315-a331-03cb128893f0")}catch{}})();var Be={add:["create","append"],fetch:["get"],inspect:["get","health"],log:["history","comments","notes"],ls:["list"],pause:["release"],read:["get"],remove:["delete"],rm:["delete"],show:["get"],start:["start-task"]};function H(e,t){let n=e.trim().toLowerCase(),o=t.trim().toLowerCase();if(o.length===0)return Number.POSITIVE_INFINITY;let i=n.split(" "),s=Be[o]?.indexOf(m(n));if(s!==void 0&&s>=0)return s;if(n===o)return 10;if(i.includes(o))return 11;if(i.some(c=>c.startsWith(o)))return 12;let a=o.length>=5?2:1,r=Number.POSITIVE_INFINITY;for(let c of i){let l=I(c,o,a);l!==null&&(r=Math.min(r,l))}return Number.isFinite(r)?20+r:n.includes(o)?30:Number.POSITIVE_INFINITY}function Vt(e,t){return e.map(n=>({path:n,score:H(n,t)})).filter(n=>Number.isFinite(n.score)).sort((n,o)=>n.score!==o.score?n.score-o.score:n.path===o.path?0:n.path<o.path?-1:1).map(n=>n.path)}function $t(e,t,n){let o=new Set(t),i=E.filter(r=>r.lifecycle==="deprecated").slice().sort((r,c)=>c.alias.length-r.alias.length),s=[],a=e.flatMap(r=>{let c=i.find(u=>r===u.alias||r.startsWith(`${u.alias} `)),l=r;if(c){let u=r.slice(c.alias.length);if(!o.has(`${c.canonical}${u}`))return[];l=`${c.canonical_argv.join(" ")}${u}`}return n!==void 0&&H(r,n)<10&&s.push(l),[l]});return[...new Set(s.length>0?s:a)]}export{Ge as a,je as b,ee as c,te as d,Ke as e,Ye as f,Qe as g,f as h,ne as i,oe as j,st as k,G as l,W as m,fe as n,j as o,pe as p,k as q,me as r,_t as s,be as t,vt as u,Ne as v,Fe as w,Ct as x,kt as y,At as z,$e as A,Ot as B,H as C,Vt as D,$t as E};
2
+ //# sourceMappingURL=chunk-25KTCTBL.js.map
@@ -1,6 +1,6 @@
1
- import{A as Nn,Ab as Zn,Bb as Be,Cc as io,D as Un,E as Gn,O as Wn,P as Bn,Rb as eo,S as $n,Tb as to,Vb as ro,Wb as no,a as fe,b as K,bb as Jn,c as _n,ca as wt,d as wn,da as vt,ea as zn,fa as Vn,ga as Kn,ha as Qn,ka as Yn,la as bt,ma as Et,na as We,r as Ln,ta as Xn,v as me,w as On,x as jn,y as Ge,yc as oo,z as qn}from"./chunk-3OFFMS2N.js";import{$h as ln,Aj as En,B as q,Bc as T,Bi as Te,Bj as Sn,D as ct,Dj as yt,Ej as In,Fh as V,Gc as Lr,Gh as tn,Gk as Dn,Hc as lt,Hh as mt,Ih as le,Ii as Me,Jh as de,K as ie,Kc as Y,Kh as ht,Ki as Fe,L as Ee,Lc as Or,Lf as L,Lh as O,Li as mn,Mc as se,Mh as rn,Mi as De,N as Se,Nh as ue,Ni as Pe,O as Dr,Oh as nn,Oi as hn,Pf as A,Pi as pn,Pj as Le,Qf as ut,Qh as pt,Qi as He,Rb as H,Rf as N,Sa as G,Si as gn,Th as on,Ti as yn,Tj as Oe,Tn as Hn,Vh as sn,Wh as Z,Xh as gt,Yh as an,Zh as Ce,_a as x,_f as W,_h as cn,_k as ee,ab as Hr,ad as X,af as S,ag as J,cb as z,cd as jr,ck as kn,df as ke,dh as Ae,dj as vn,dk as xn,eb as Ie,ef as Wr,eh as Qr,ej as bn,ff as Br,fh as ce,ga as Pr,gf as dt,hf as $r,hk as Rn,id as qr,ki as j,kl as Pn,la as m,lg as Vr,lk as An,mk as Cn,na as h,nd as Nr,ng as ae,nk as je,od as Ur,oi as dn,ok as Tn,ph as ft,pk as qe,qk as Ne,rf as zr,rg as Kr,rh as Yr,rk as Ue,sg as xe,sk as Mn,tg as Re,ud as Gr,vi as un,wh as Xr,wk as Fn,x as be,xh as Jr,xk as _t,yh as Zr,yi as fn,z as Fr,zh as en}from"./chunk-CM57QHVK.js";import ao from"node:fs/promises";import co from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function Ri(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 Ai(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 so(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Ri(t.ids,r,t.minEntries)}return Ai(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function Ci(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 h("history-compact --before requires a non-empty value.",m.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=N(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.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 h(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,m.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new h(`History for this item contains invalid timestamp at entry ${i+1}.`,m.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function Ti(e,t){let r=le(),n=le();for(let o=0;o<e.length;o+=1){let i=e[o];r=Z(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Mi(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Yr.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&ht(ue(e.document),n,A(r.hash_algorithm)).includes(r.after_hash))}}function Fi(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 Di(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 Pi(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Ti(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=N(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:A(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:O(le()),after:O(t),message:Di(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Xr(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[Jr({...s,before_hash:ht(le(),i.item_hash_version??1,A(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:O(r),after:O(r),message:Fi(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Hi(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=await K(n,e,o,i.type_to_folder);return Be({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>Li(s,t,a)})}function Li(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new h(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=Ci(t.before,o),a=s.compactCount>0,l=!!t.dryRun,d=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=Mi(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:p,auditEntryAdded:y}=Pi({historyEntries:o,boundary:s,changed:a,dryRun:l,author:d,options:t}),_=N(o,!0),g=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:l,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:f.length,baseline_entry_added:p,audit_entry_added:y,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,...b])].sort((v,E)=>v.localeCompare(E)),generated_at:S()})}}var Oi=3;function ji(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`history-compact ${r} must be a non-negative safe integer.`,m.USAGE)}let t=Sn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",m.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:En(t)}}function qc(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 h("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",m.USAGE);if(e!==void 0&&(r||n))throw new h("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.",m.USAGE);if(r&&n)throw new h("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",m.USAGE)}function qi(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function Ni(e){let t=W(e.settings.schema),r=Ge(t),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(d=>[d.id,r.classify(d.status)])),i=co.join(e.pmRoot,"history"),s=[],a=[];if(!await be(i))return{candidates:s,preselectionErrors:a};let l=(await ao.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,c)=>d.localeCompare(c));for(let d of l){let c=co.join(i,d),u=d.slice(0,-6);try{let f=await ao.readFile(c,"utf8");await se({path:c,scope:"project"}),s.push({id:u,entries:qi(f),bucket:o.get(u)??null})}catch(f){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function Ui(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 Hi(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)}}}}async function Nc(e,t){let r=ji(e),{pmRoot:n,settings:o,typeRegistry:i}=await fe(t.path),{candidates:s,preselectionErrors:a}=await Ni({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),l=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??Oi,c=o.history.compact_policy,u=l==="scan"&&e.allOver===void 0&&c.enabled,f=e.allOver??(u?c.max_entries:void 0),p=so(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:f}),y=!!e.dryRun,_=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let b=await Ui({row:w,options:r,dryRun:y,global:t});if(_.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:y,mode:l,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:u},totals:g,results:_,generated_at:S()}}import St from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function It(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function uo(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function fo(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",m.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(r=t.slice(1,o),n=uo(t.slice(o+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",m.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",m.USAGE)}return{kind:"regex",source:r,flags:n}}function mo(e,t){let r=[...new Set(It(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),n=[...new Set(It(t).map(i=>i.trim()))].filter(i=>i.length>0).map(fo),o=[...r,...n];if(o.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",m.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 o}function ho(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 po(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 kt(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?ho(n,i.value,r):po(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function he(e,t,r){if(typeof e=="string")return kt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=he(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=he(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function lo(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=he(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function Gi(e){let t=structuredClone(mt),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];de(t,void 0,A(i.hash_algorithm))!==i.before_hash&&(r+=1),t=Z(t,i.patch,o+1,i.op),de(t,void 0,A(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Wi(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=kt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(o=!0)}let a=lo(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let l=e.reanchor_evidence?.map(d=>{let c=d.patch?lo(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?he(d.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let f=c.replacements>0||u.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:p,record:y,record_hash:_,record_hash_version:g,...w}=d;return c.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...l?{reanchor_evidence:l}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function Bi(e,t,r){let n=structuredClone(mt),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=Zr(l);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,m.GENERIC_FAILURE);let c=Wi(l,t,r);i+=c.replacements,c.changed&&(o+=1);let u=de(n,void 0,A(l.hash_algorithm));n=Z(n,c.entry.patch,a+1,c.entry.op);let f=de(n,void 0,A(l.hash_algorithm));s.push(en(l,{...c.entry,before_hash:u,after_hash:f},{retainPriorRecord:c.changed,retainPriorRecordHash:!c.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function go(e){return Object.keys(e.metadata).length>0}function $i(e){if(!go(e.finalDocument))return{raw:null,path:null,document:null};let t=Re(O(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new h("history-redact would change the item id; narrow your patterns.",m.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:xe(t,{format:"toon",schema:e.settings.schema})}}function zi(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 Vi(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??O(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 Ki(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Me(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 q(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await St.rm(e.currentItem.path,{force:!0}),await q(e.subject.historyPath,on(e.rewrittenEntries))}catch(l){try{await Qi(e.subject.historyPath,r,o,i)}finally{await ft(e.subject.historyPath)}throw l}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Fe({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 Yi(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function Qi(e,t,r,n){t===null?await St.rm(e,{force:!0}):await q(e,t);for(let o of r){let i=n.get(o);i===void 0?await St.rm(o,{force:!0}):await q(o,i)}}async function Yi(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await Y({path:o,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function il(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=t.replacement??"",a=s.length===0,l=a?"[redacted]":s,d=mo(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return Be({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>Xi({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:d,replacement:l,replacementIsDefault:a},u)})}function Xi(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:l,replacementIsDefault:d}=e,c=t.entries,u=Gi(c),f=Bi(c,a,l),p=u.hashMismatchesBefore+u.hashMismatchesAfter,y=!!s.dryRun,_=f.replacements>0,g=[];p>0&&g.push(`history_redact_preexisting_hash_mismatches:${p}`),_||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},b=$i({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),v=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),E=t.author,C=zi(s,f),{rewrittenEntries:k,auditEntryAdded:I}=Vi({rewritten:f,dryRun:y,changed:_,nextItemDocument:b.document,author:E,message:C});return{changed:_,rewrittenEntries:k,...Ki({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:E,rewrittenEntries:k}),report:({verification:R,warnings:st})=>({id:n.id,dry_run:y,changed:_,patterns:{literal_count:a.filter(M=>M.kind==="literal").length,regex_count:a.filter(M=>M.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:I,verify_ok:R.ok,verify_errors:R.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:v},warnings:[...new Set([...g,...st])].sort((M,at)=>M.localeCompare(at)),generated_at:S()})}}var sl={applyLiteralRule:ho,applyRegexRule:po,buildRedactionRules:mo,hasItemMetadata:go,normalizeRegexFlags:uo,normalizeStringArrayInput:It,parseRegexRule:fo,redactStringValue:kt,redactUnknownValue:he};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();var xt={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 Ji}from"node:crypto";import{isUtf8 as Zi}from"node:buffer";import pe from"node:fs/promises";import Rt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0001f37-7941-5cad-8950-2c6925056d10")}catch{}})();async function yo(e){try{return(await pe.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Fr(t))return[];throw t}}function es(e,t,r,n){let o=t.at(-1),i;for(let l=t.length-1;l>=0;l-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[l].op)){i=t[l];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?A(o.hash_algorithm):null,rewrite_count:t.reduce((l,d)=>l+(d.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 ts(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!Zi(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 pt(n).ok?es(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await pe.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Rt.join(e,"history"),n=await yo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),l={id:a,digest:null,stream:null};i.push(l);let d=Rt.join(r,s);try{let c=await pe.lstat(d);if(o.set(s,H([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await pe.readFile(d);l.digest=Ji(t).update(u).digest("hex"),l.stream=ts(a,u,l.digest)}catch{}}if(H(n)!==H(await yo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let l=await pe.lstat(Rt.join(r,s));if(a!==H([l.ino,l.size,l.mtimeMs,l.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch{}})();function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function te(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function rs(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:te(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||te(e.latest_record_hash,e.latest_hash_algorithm))}function ns(e){return e===null?!0:!Ct(e)||!Tt(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"&&ke(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function os(e,t){return!Ct(e)||!Tt(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)&&te(e.stream_digest,t)&&rs(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&ns(e.last_maintenance)}function _o(e){if(!Ct(e)||!Tt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==xt.format||e.version!==1||typeof e.generated_at!="string"||!ke(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(!os(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(ut(H(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function wo(e={}){let t=A(e.hashAlgorithm),r=e.generatedAt??S();if(!ke(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(x(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:xt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return _o({...i,workspace_digest:ut(H(i),t)})}async function vo(e,t={}){let r=_o(e),n=await At(x(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),l=n.filter(c=>c.stream===null).map(c=>c.id),d=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||H(u.stream)!==H(c))&&d.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+l.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:l,transitions:d}}import bo from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch{}})();async function Ml(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 h(`history attest ${n} requires a nonempty string.`,m.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new h("history attest --verify cannot be combined with --output or --hash-algorithm",m.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await bo.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",m.USAGE)}return vo(n,{pmRoot:t.path})}let r=await wo({pmRoot:t.path,hashAlgorithm:A(e.hashAlgorithm)});if(e.output===void 0)return r;try{await bo.writeFile(e.output,`${JSON.stringify(r,null,2)}
1
+ import{A as Nn,Ab as Zn,Bb as Be,Cc as io,D as Un,E as Gn,O as Wn,P as Bn,Rb as eo,S as $n,Tb as to,Vb as ro,Wb as no,a as fe,b as K,bb as Jn,c as _n,ca as wt,d as wn,da as vt,ea as zn,fa as Vn,ga as Kn,ha as Qn,ka as Yn,la as bt,ma as Et,na as We,r as Ln,ta as Xn,v as me,w as On,x as jn,y as Ge,yc as oo,z as qn}from"./chunk-445ARBKY.js";import{$h as ln,Aj as En,B as q,Bc as T,Bi as Te,Bj as Sn,D as ct,Dj as yt,Ej as In,Fh as V,Gc as Lr,Gh as tn,Gk as Dn,Hc as lt,Hh as mt,Ih as le,Ii as Me,Jh as de,K as ie,Kc as Y,Kh as ht,Ki as Fe,L as Ee,Lc as Or,Lf as L,Lh as O,Li as mn,Mc as se,Mh as rn,Mi as De,N as Se,Nh as ue,Ni as Pe,O as Dr,Oh as nn,Oi as hn,Pf as A,Pi as pn,Pj as Le,Qf as ut,Qh as pt,Qi as He,Rb as H,Rf as N,Sa as G,Si as gn,Th as on,Ti as yn,Tj as Oe,Tn as Hn,Vh as sn,Wh as Z,Xh as gt,Yh as an,Zh as Ce,_a as x,_f as W,_h as cn,_k as ee,ab as Hr,ad as X,af as S,ag as J,cb as z,cd as jr,ck as kn,df as ke,dh as Ae,dj as vn,dk as xn,eb as Ie,ef as Wr,eh as Qr,ej as bn,ff as Br,fh as ce,ga as Pr,gf as dt,hf as $r,hk as Rn,id as qr,ki as j,kl as Pn,la as m,lg as Vr,lk as An,mk as Cn,na as h,nd as Nr,ng as ae,nk as je,od as Ur,oi as dn,ok as Tn,ph as ft,pk as qe,qk as Ne,rf as zr,rg as Kr,rh as Yr,rk as Ue,sg as xe,sk as Mn,tg as Re,ud as Gr,vi as un,wh as Xr,wk as Fn,x as be,xh as Jr,xk as _t,yh as Zr,yi as fn,z as Fr,zh as en}from"./chunk-JDHWZYZU.js";import ao from"node:fs/promises";import co from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d51da34a-9f37-5441-91f0-15a16b601709")}catch{}})();function Ri(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 Ai(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 so(e,t){if(t.ids!==void 0&&t.ids.length>0){let r=new Map(e.map(n=>[n.id,n]));return Ri(t.ids,r,t.minEntries)}return Ai(e,t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1dede7b7-eeea-520d-97ce-a71687d93bc2")}catch{}})();function Ci(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 h("history-compact --before requires a non-empty value.",m.USAGE);if(/^\d+$/.test(r)){let i=Number.parseInt(r,10),s=N(t);if(!Number.isSafeInteger(i)||i<s+1||i>s+t.length+1)throw new h(`history-compact --before version must be between ${s+1} and ${s+t.length+1}.`,m.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 h(`Invalid history-compact --before value "${e}". Use a version number or ISO timestamp.`,m.USAGE);let o=0;for(let[i,s]of t.entries()){let a=Date.parse(s.ts);if(!Number.isFinite(a))throw new h(`History for this item contains invalid timestamp at entry ${i+1}.`,m.GENERIC_FAILURE);if(a>=n)break;o+=1}return{kind:"timestamp",raw:r,compactCount:o,retainedCount:t.length-o}}function Ti(e,t){let r=le(),n=le();for(let o=0;o<e.length;o+=1){let i=e[o];r=Z(r,i.patch,o+1,i.op),o+1===t&&(n=structuredClone(r))}return{checkpoint:n,finalReplay:r}}function Mi(e,t){if(!e)return{loadedItem:null,currentItemRawBeforeLock:null,matchedChainBefore:null};let r=t[t.length-1];return{loadedItem:e,currentItemRawBeforeLock:e.raw,matchedChainBefore:Yr.some(n=>(r.item_hash_version===void 0||r.item_hash_version===n)&&ht(ue(e.document),n,A(r.hash_algorithm)).includes(r.after_hash))}}function Fi(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 Di(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 Pi(e){if(!e.changed)return{rewrittenEntries:e.historyEntries,baselineEntryAdded:!1,auditEntryAdded:!1};let{checkpoint:t,finalReplay:r}=Ti(e.historyEntries,e.boundary.compactCount),n=e.historyEntries.slice(e.boundary.compactCount),o=N(e.historyEntries,!0),i=e.historyEntries[e.boundary.compactCount-1],s=V({hashAlgorithm:A(i.hash_algorithm),nowIso:e.historyEntries[e.boundary.compactCount-1].ts,author:e.author,op:"history_compact_baseline",before:O(le()),after:O(t),message:Di(e.boundary),context:{history_compaction:{contract_version:1,version_offset:o===null?null:o+e.boundary.compactCount-1,checkpoint_timestamp_semantics:"last_compacted_entry",pruned_entry_count:e.boundary.compactCount,pruned_stream_digest:Xr(e.historyEntries.slice(0,e.boundary.compactCount)),retained_proof:"stream_digest_and_checkpoint",limitation:"individual_pruned_entries_require_pre_compaction_stream"}}}),a=[Jr({...s,before_hash:ht(le(),i.item_hash_version??1,A(i.hash_algorithm))[0],after_hash:i.after_hash,item_hash_version:i.item_hash_version}),...n];return e.dryRun||a.push(V({nowIso:S(),author:e.author,op:"history_compact",before:O(r),after:O(r),message:Fi(e.options,e.boundary)})),{rewrittenEntries:a,baselineEntryAdded:!0,auditEntryAdded:!e.dryRun}}async function Hi(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=await K(n,e,o,i.type_to_folder);return Be({pmRoot:n,subject:s,settings:o,typeRegistry:i,operation:"history-compact",options:t,transform:a=>Li(s,t,a)})}function Li(e,t,r){let n=e.historyPath,o=r.entries,i=r.verification;if(!i.ok)throw new h(`history-compact requires a valid history chain (${i.errors.join(", ")}). Run pm history-repair ${e.id} first.`,m.CONFLICT);let s=Ci(t.before,o),a=s.compactCount>0,l=!!t.dryRun,d=r.author,c=[];a||c.push("history_compact_noop_before_boundary");let u=Mi(r.loadedItem,o);u.matchedChainBefore===!1&&c.push("history_compact_item_chain_mismatch");let{rewrittenEntries:f,baselineEntryAdded:p,auditEntryAdded:y}=Pi({historyEntries:o,boundary:s,changed:a,dryRun:l,author:d,options:t}),_=N(o,!0),g=s.retainedCount>0&&_!==null?_+s.compactCount+1:null;return{changed:a,rewrittenEntries:f,report:({verification:w,warnings:b})=>({id:e.id,dry_run:l,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:f.length,baseline_entry_added:p,audit_entry_added:y,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,...b])].sort((v,E)=>v.localeCompare(E)),generated_at:S()})}}var Oi=3;function ji(e){for(let r of["allOver","minEntries"]){let n=e[r];if(n!==void 0&&(!Number.isSafeInteger(n)||n<0))throw new h(`history-compact ${r} must be a non-negative safe integer.`,m.USAGE)}let t=Sn(e.ids);if(e.ids!==void 0&&t==="")throw new h("history-compact ids requires at least one valid item ID.",m.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:En(t)}}function qc(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 h("history-compact: provide an item <id>, or a bulk selector (--ids, --all-over <N>, --closed, or --all-streams).",m.USAGE);if(e!==void 0&&(r||n))throw new h("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.",m.USAGE);if(r&&n)throw new h("history-compact: --ids is mutually exclusive with --all-over/--closed/--all-streams; pass an explicit id list or a scan selector, not both.",m.USAGE)}function qi(e){let t=0;for(let r of e.split(/\r?\n/))r.trim().length>0&&(t+=1);return t}async function Ni(e){let t=W(e.settings.schema),r=Ge(t),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema),o=new Map(n.map(d=>[d.id,r.classify(d.status)])),i=co.join(e.pmRoot,"history"),s=[],a=[];if(!await be(i))return{candidates:s,preselectionErrors:a};let l=(await ao.readdir(i)).filter(d=>d.endsWith(".jsonl")).sort((d,c)=>d.localeCompare(c));for(let d of l){let c=co.join(i,d),u=d.slice(0,-6);try{let f=await ao.readFile(c,"utf8");await se({path:c,scope:"project"}),s.push({id:u,entries:qi(f),bucket:o.get(u)??null})}catch(f){a.push({id:u,outcome:"errored",entries_before:0,entries_after:null,skip_reason:null,changed:!1,error:f instanceof Error?f.message:String(f)})}}return{candidates:s,preselectionErrors:a}}async function Ui(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 Hi(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)}}}}async function Nc(e,t){let r=ji(e),{pmRoot:n,settings:o,typeRegistry:i}=await fe(t.path),{candidates:s,preselectionErrors:a}=await Ni({pmRoot:n,settings:o,typeToFolder:i.type_to_folder}),l=r.ids!==void 0&&r.ids.length>0?"ids":"scan",d=e.minEntries??Oi,c=o.history.compact_policy,u=l==="scan"&&e.allOver===void 0&&c.enabled,f=e.allOver??(u?c.max_entries:void 0),p=so(s,{ids:r.ids,scope:e.scope,minEntries:d,allOver:f}),y=!!e.dryRun,_=[...a],g={streams_considered:s.length+a.length,selected:0,items_compacted:0,items_skipped:0,items_errored:a.length};for(let w of p){let b=await Ui({row:w,options:r,dryRun:y,global:t});if(_.push(b.result),!b.selected){g.items_skipped+=1;continue}g.selected+=1,b.compacted&&(g.items_compacted+=1),b.errored&&(g.items_errored+=1)}return{bulk:!0,dry_run:y,mode:l,scope:e.scope??null,criteria:{min_entries:d,all_over:f??null,policy_threshold_applied:u},totals:g,results:_,generated_at:S()}}import St from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9d9d625b-152d-5417-8702-6e0e45839500")}catch{}})();function It(e){return Array.isArray(e)?e:typeof e=="string"?[e]:[]}function uo(e){let t=[];for(let r of e)t.includes(r)||t.push(r);return t.includes("g")||t.push("g"),t.join("")}function fo(e){let t=e.trim();if(t.length===0)throw new h("history-redact --regex requires a non-empty pattern.",m.USAGE);let r=t,n="g";if(t.startsWith("/")&&t.length>1){let o=t.lastIndexOf("/");o>0&&(r=t.slice(1,o),n=uo(t.slice(o+1)))}if(r.length===0)throw new h("history-redact --regex cannot use an empty pattern.",m.USAGE);try{new RegExp(r,n)}catch{throw new h("Invalid --regex value; provide a valid JavaScript regular expression.",m.USAGE)}return{kind:"regex",source:r,flags:n}}function mo(e,t){let r=[...new Set(It(e).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),n=[...new Set(It(t).map(i=>i.trim()))].filter(i=>i.length>0).map(fo),o=[...r,...n];if(o.length===0)throw new h("history-redact requires at least one matcher via --literal or --regex.",m.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 o}function ho(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 po(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 kt(e,t,r){let n=e,o=0;for(let i of t){let s=i.kind==="literal"?ho(n,i.value,r):po(n,i,r);n=s.value,o+=s.replacements}return{value:n,replacements:o}}function he(e,t,r){if(typeof e=="string")return kt(e,t,r);if(Array.isArray(e)){let n=0;return{value:e.map(i=>{let s=he(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=he(s,t,r);n+=a.replacements,o[i]=a.value}return{value:o,replacements:n}}return{value:e,replacements:0}}function lo(e,t,r){let n=0;return{patch:e.map(i=>{if(!Object.prototype.hasOwnProperty.call(i,"value"))return i;let s=he(i.value,t,r);return n+=s.replacements,s.replacements>0?{...i,value:s.value}:i}),replacements:n}}function Gi(e){let t=structuredClone(mt),r=0,n=0;for(let o=0;o<e.length;o+=1){let i=e[o];de(t,void 0,A(i.hash_algorithm))!==i.before_hash&&(r+=1),t=Z(t,i.patch,o+1,i.op),de(t,void 0,A(i.hash_algorithm))!==i.after_hash&&(n+=1)}return{hashMismatchesBefore:r,hashMismatchesAfter:n,finalDocument:t}}function Wi(e,t,r){let n=0,o=!1,i=!1,s=e.message;if(typeof e.message=="string"){let d=kt(e.message,t,r);s=d.value,n+=d.replacements,d.replacements>0&&(o=!0)}let a=lo(e.patch,t,r);n+=a.replacements,o||=a.replacements>0;let l=e.reanchor_evidence?.map(d=>{let c=d.patch?lo(d.patch,t,r):{patch:void 0,replacements:0},u=d.record?he(d.record,t,r):{value:void 0,replacements:0};n+=c.replacements,n+=u.replacements;let f=c.replacements>0||u.replacements>0;if(o||=f,!f)return d;i=!0;let{patch:p,record:y,record_hash:_,record_hash_version:g,...w}=d;return c.replacements>0?w:{...w,patch:d.patch}});return{entry:{...e,message:s,patch:a.patch,...l?{reanchor_evidence:l}:{}},replacements:n,changed:o,reanchorEvidenceRedacted:i}}function Bi(e,t,r){let n=structuredClone(mt),o=0,i=0,s=[];for(let a=0;a<e.length;a+=1){let l=e[a],d=Zr(l);if(!d.ok)throw new h(`history-redact refuses invalid immutable record ${a+1} (${d.error}).`,m.GENERIC_FAILURE);let c=Wi(l,t,r);i+=c.replacements,c.changed&&(o+=1);let u=de(n,void 0,A(l.hash_algorithm));n=Z(n,c.entry.patch,a+1,c.entry.op);let f=de(n,void 0,A(l.hash_algorithm));s.push(en(l,{...c.entry,before_hash:u,after_hash:f},{retainPriorRecord:c.changed,retainPriorRecordHash:!c.changed}))}return{entries:s,finalDocument:n,entriesChanged:o,replacements:i}}function go(e){return Object.keys(e.metadata).length>0}function $i(e){if(!go(e.finalDocument))return{raw:null,path:null,document:null};let t=Re(O(e.finalDocument),{schema:e.settings.schema});if(t.metadata.id!==e.subject.id)throw new h("history-redact would change the item id; narrow your patterns.",m.USAGE);return{document:t,path:z(e.pmRoot,t.metadata.type,e.subject.id,"toon",e.typeToFolder),raw:xe(t,{format:"toon",schema:e.settings.schema})}}function zi(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 Vi(e){let t=[...e.rewritten.entries];if(e.dryRun||!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let r=e.nextItemDocument??O(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 Ki(e){let t=[];return{applyRewrite:async({historyRawUnderLock:r})=>{let n=await Me(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 q(e.nextItem.path,e.nextItem.raw),e.currentItem.path&&(!e.nextItem.path||e.nextItem.path!==e.currentItem.path)&&await St.rm(e.currentItem.path,{force:!0}),await q(e.subject.historyPath,on(e.rewrittenEntries))}catch(l){try{await Qi(e.subject.historyPath,r,o,i)}finally{await ft(e.subject.historyPath)}throw l}await ft(e.subject.historyPath);let a=e.nextItem.path??e.currentItem.path;a&&(t=await Fe({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 Yi(e.subject.historyPath,[e.nextItem.path,e.currentItem.path])]}}async function Qi(e,t,r,n){t===null?await St.rm(e,{force:!0}):await q(e,t);for(let o of r){let i=n.get(o);i===void 0?await St.rm(o,{force:!0}):await q(o,i)}}async function Yi(e,t){let r=[],n=new Set(t.filter(o=>o!==null));for(let o of n)r.push(...await Y({path:o,scope:"project",op:"history_redact"}));return r.push(...await Y({path:e,scope:"project",op:"history_redact:history"})),r}async function il(e,t,r){let{pmRoot:n,settings:o,typeRegistry:i}=await fe(r.path),s=t.replacement??"",a=s.length===0,l=a?"[redacted]":s,d=mo(t.literal,t.regex),c=await K(n,e,o,i.type_to_folder);return Be({pmRoot:n,subject:c,settings:o,typeRegistry:i,operation:"history-redact",options:t,transform:u=>Xi({pmRoot:n,subject:c,settings:o,typeRegistry:i,options:t,rules:d,replacement:l,replacementIsDefault:a},u)})}function Xi(e,t){let{pmRoot:r,subject:n,settings:o,typeRegistry:i,options:s,rules:a,replacement:l,replacementIsDefault:d}=e,c=t.entries,u=Gi(c),f=Bi(c,a,l),p=u.hashMismatchesBefore+u.hashMismatchesAfter,y=!!s.dryRun,_=f.replacements>0,g=[];p>0&&g.push(`history_redact_preexisting_hash_mismatches:${p}`),_||g.push("history_redact_no_matches");let w={raw:t.loadedItem?.raw??null,path:n.located?.itemPath??null,document:t.loadedItem?.document??null},b=$i({pmRoot:r,subject:n,settings:o,typeToFolder:i.type_to_folder,finalDocument:f.finalDocument}),v=(w.path??null)!==(b.path??null)||(w.raw??null)!==(b.raw??null),E=t.author,C=zi(s,f),{rewrittenEntries:k,auditEntryAdded:I}=Vi({rewritten:f,dryRun:y,changed:_,nextItemDocument:b.document,author:E,message:C});return{changed:_,rewrittenEntries:k,...Ki({pmRoot:r,subject:n,settings:o,typeRegistry:i,currentItem:w,nextItem:b,author:E,rewrittenEntries:k}),report:({verification:R,warnings:st})=>({id:n.id,dry_run:y,changed:_,patterns:{literal_count:a.filter(M=>M.kind==="literal").length,regex_count:a.filter(M=>M.kind==="regex").length,total_count:a.length,replacement_is_default:d},history:{path:n.historyPath,entries_scanned:c.length,entries_changed:f.entriesChanged,replacements:f.replacements,hash_mismatches_before:u.hashMismatchesBefore,hash_mismatches_after:u.hashMismatchesAfter,preexisting_hash_mismatches:p,audit_entry_added:I,verify_ok:R.ok,verify_errors:R.errors},item:{existed_before:w.path!==null,exists_after:b.path!==null,path_before:w.path,path_after:b.path,changed:v},warnings:[...new Set([...g,...st])].sort((M,at)=>M.localeCompare(at)),generated_at:S()})}}var sl={applyLiteralRule:ho,applyRegexRule:po,buildRedactionRules:mo,hasItemMetadata:go,normalizeRegexFlags:uo,normalizeStringArrayInput:It,parseRegexRule:fo,redactStringValue:kt,redactUnknownValue:he};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();var xt={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 Ji}from"node:crypto";import{isUtf8 as Zi}from"node:buffer";import pe from"node:fs/promises";import Rt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d0001f37-7941-5cad-8950-2c6925056d10")}catch{}})();async function yo(e){try{return(await pe.readdir(e)).filter(t=>t.endsWith(".jsonl")).sort()}catch(t){if(Fr(t))return[];throw t}}function es(e,t,r,n){let o=t.at(-1),i;for(let l=t.length-1;l>=0;l-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(t[l].op)){i=t[l];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?A(o.hash_algorithm):null,rewrite_count:t.reduce((l,d)=>l+(d.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 ts(e,t,r){try{if(!/^[A-Za-z0-9_-]+$/u.test(e)||!Zi(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 pt(n).ok?es(e,n,t.length,r):null}catch{return null}}async function At(e,t){if(!(await pe.stat(e)).isDirectory())throw new TypeError("attestation tracker root must be a directory");let r=Rt.join(e,"history"),n=await yo(r),o=new Map,i=[];for(let s of n){let a=s.slice(0,-6),l={id:a,digest:null,stream:null};i.push(l);let d=Rt.join(r,s);try{let c=await pe.lstat(d);if(o.set(s,H([c.ino,c.size,c.mtimeMs,c.ctimeMs])),!c.isFile())continue;let u=await pe.readFile(d);l.digest=Ji(t).update(u).digest("hex"),l.stream=ts(a,u,l.digest)}catch{}}if(H(n)!==H(await yo(r)))throw new TypeError("attestation history inventory changed during read; retry");for(let[s,a]of o){let l=await pe.lstat(Rt.join(r,s));if(a!==H([l.ino,l.size,l.mtimeMs,l.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch{}})();function Ct(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Tt(e,t){return Object.keys(e).length===t.length&&t.every(r=>Object.hasOwn(e,r))}function te(e,t){return typeof e=="string"&&(t==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(e)}function rs(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:te(e.latest_after_hash,e.latest_hash_algorithm)&&(e.latest_record_hash===null||te(e.latest_record_hash,e.latest_hash_algorithm))}function ns(e){return e===null?!0:!Ct(e)||!Tt(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"&&ke(e.ts)&&(e.record_hash===null||te(e.record_hash,"sha256")||te(e.record_hash,"sha512"))}function os(e,t){return!Ct(e)||!Tt(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)&&te(e.stream_digest,t)&&rs(e)&&(e.checkpoint_digest===null||te(e.checkpoint_digest,"sha256"))&&ns(e.last_maintenance)}function _o(e){if(!Ct(e)||!Tt(e,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(e.format!==xt.format||e.version!==1||typeof e.generated_at!="string"||!ke(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(!os(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(ut(H(o),t)!==n)throw new TypeError("History attestation rollup mismatch");return e}async function wo(e={}){let t=A(e.hashAlgorithm),r=e.generatedAt??S();if(!ke(r))throw new TypeError("Invalid history attestation timestamp");let n=await At(x(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:xt.format,version:1,hash_algorithm:t,generated_at:r,streams:n.map(s=>s.stream)};return _o({...i,workspace_digest:ut(H(i),t)})}async function vo(e,t={}){let r=_o(e),n=await At(x(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),l=n.filter(c=>c.stream===null).map(c=>c.id),d=[];for(let c of r.streams){let u=o.get(c.id);u&&(u.digest!==c.stream_digest||H(u.stream)!==H(c))&&d.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+l.length+d.length===0,workspace_digest:r.workspace_digest,streams_checked:n.length,changed_streams:d.map(c=>c.id),missing_streams:s,added_streams:a,invalid_streams:l,transitions:d}}import bo from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch{}})();async function Ml(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 h(`history attest ${n} requires a nonempty string.`,m.USAGE)}if(e.verify!==void 0){if(e.output!==void 0||e.hashAlgorithm!==void 0)throw new h("history attest --verify cannot be combined with --output or --hash-algorithm",m.USAGE);let n;try{n=typeof e.verify=="string"?JSON.parse(await bo.readFile(e.verify,"utf8")):e.verify}catch{throw new h("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",m.USAGE)}return vo(n,{pmRoot:t.path})}let r=await wo({pmRoot:t.path,hashAlgorithm:A(e.hashAlgorithm)});if(e.output===void 0)return r;try{await bo.writeFile(e.output,`${JSON.stringify(r,null,2)}
2
2
  `,{flag:"wx",mode:384})}catch{throw new h("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",m.USAGE)}return{output:e.output,workspace_digest:r.workspace_digest,streams:r.streams.length}}import is from"fast-json-patch";import Mt from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="85aa928d-92b8-5f67-8482-0fe5715fef45")}catch{}})();async function Eo(e,t,r){let n=await hn(e,{schema:t.schema});return n.error===null?{raw:n.raw,document:n.document}:{raw:n.raw,document:So(r),recovered:!0}}function ss(e,t){return sn(e,t,{errorSubject:"restore",allowFutureTimestamp:!0})}function So(e){let t=gt(e,e.length-1);return Object.keys(t.metadata).length===0?{metadata:{},body:t.body}:Re(O(t))}async function as(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 cs(e,t){let r=ue(e),n=ue(t),o=is.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 ls(e){let t=await Zn({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"restore",readItem:r=>Eo(r,e.settings,e.history)});return{loadedItemUnderLock:t.loadedItemUnderLock,existingItemPath:t.locatedUnderLock?.itemPath??null}}function ds(e,t){return e?{document:e.document,originalRaw:e.raw}:{document:So(t),originalRaw:null}}function us(e){let t=e.document.metadata.assignee?.trim();if(!(t&&t!==e.author&&!e.force))return[];if(e.enforcement==="strict")throw new h(`Item ${e.resolvedId} is assigned to ${t}. Use --force to override.`,m.CONFLICT);return e.enforcement==="warn"?[`ownership_warning:assignee_conflict:${e.resolvedId}:${t}`]:[]}async function fs(e){if(e.existingItemPath&&e.resolvedOriginalRaw!==null&&e.restoredItemPath!==e.existingItemPath){await q(e.existingItemPath,e.resolvedOriginalRaw),await Mt.rm(e.restoredItemPath,{force:!0});return}if(e.existingItemPath&&e.resolvedOriginalRaw!==null){await q(e.existingItemPath,e.resolvedOriginalRaw);return}await Mt.rm(e.restoredItemPath,{force:!0})}async function ms(e){return[...await Y({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 Y({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 zl(e,t,r,n){let o=x(process.cwd(),n.path);await L(o);let i=await j(o),s=G(i,T()),a=await as(o,e,i,s.type_to_folder),l=a.id,{raw:d,entries:c}=await Qr(a.historyPath,l);if(c.length===0)throw new h(`No history exists for ${l}; restore is unavailable.`,m.NOT_FOUND);let u=ss(t,c),f=an(gt(c,u.historyIndex),u),p=rn(f,{schema:i.schema});if(p.metadata.id!==l)throw new h(`Restore target resolved to item ${p.metadata.id}, expected ${l}.`,m.GENERIC_FAILURE);let _=(a.located?await Eo(a.located,i,c):null)?.raw??null,g=Ae(r.author,i.author_default),w=await $r(o,l,i.locks.ttl_seconds,g,!!r.force,i.governance.force_required_for_stale_lock,i.locks.wait_ms);try{let{loadedItemUnderLock:b,existingItemPath:v}=await ls({pmRoot:o,subject:a,settings:i,typeRegistry:s,historyRawBeforeLock:d,currentItemRawBeforeLock:_,history:c}),E="toon",C=ds(b,c),k=us({document:C.document,author:g,force:r.force,enforcement:i.governance.ownership_enforcement,resolvedId:l}),I=cs(C.document,p),R=await un({pmRoot:o,settings:i,operation:"restore",author:g,before:C.document,after:p});await Or({pm_root:o,operation:"restore",before:C.document,after:p,changed_fields:I,sdk:gn({pmRoot:o,settings:i,typeToFolder:s.type_to_folder})});let st=xe(p,{format:E,schema:i.schema}),M=z(o,p.metadata.type,l,E,s.type_to_folder),at=await Me(o,g),Cr=[];try{await q(M,st),v&&M!==v&&await Mt.rm(v);let ki=V({nowIso:S(),author:g,op:"restore",before:C.document,after:p,message:r.message,context:R.decisions.length===0?void 0:{workflow_policies:R.decisions}});try{await tn(a.historyPath,ki)}catch(xi){throw await fs({existingItemPath:v,resolvedOriginalRaw:C.originalRaw,restoredItemPath:M}),xi}Cr=await Fe({pmRoot:o,preferredFormat:i.item_format,typeToFolder:s.type_to_folder,schema:i.schema,itemPath:M,previousItemPath:v??void 0,document:p})}finally{await at()}let Ii=await ms({restoredItemPath:M,historyPath:a.historyPath,before:C.document,after:p});Lr({id:p.metadata.id,op:"restore",item_type:p.metadata.type,previous_status:C.document.metadata.status,status:p.metadata.status,previous:lt(C.document.metadata,I),current:lt(p.metadata,I),changed_fields:I});let Tr=c[u.historyIndex],Mr=N(c,!0);return{item:p.metadata,restored_from:{kind:u.kind,target:u.raw,history_index:u.historyIndex+1,version:Mr===null?null:Mr+u.historyIndex+1,entry_ts:Tr.ts,entry_op:Tr.op},changed_fields:I,warnings:[...R.warnings,...b?.recovered?["restore_unreadable_item_recovered"]:[],...a.historyPolicyWarnings,...k,...Cr,...Ii]}}finally{await w()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2a9a4dc0-8027-5761-9bbf-cac1ef83bd10")}catch{}})();var hs=["status","type","tag","priority","deadlineBefore","deadlineAfter","updatedAfter","updatedBefore","createdAfter","createdBefore","ids","assignee","assigneeFilter","parent","sprint","release"],ps=["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 gs(e){return e!=null&&(typeof e!="string"||e.split(",").some(t=>t.trim().length>0))}function Kl(e,t,r={}){let n=r.includePagination!==!1;return[t,...hs.map(i=>e?.[i]),...n?[e?.limit,e?.offset]:[]].some(gs)||ps.some(i=>e?.[i]===!0)}function Io(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}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7a4a98b2-3872-506d-b88d-877b0033dd2d")}catch{}})();var ko=["parent","type","priority","status","assignee","tags","sprint","release"];function Ro(e,t){let r=Le(e,t,{strict:!0,flagLabel:"--status"});if(!(!r||r.length===0))return r}function Ao(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 h("Aggregate --sum and --avg must target the same numeric field",m.USAGE);let s=o??i;if(!t.includes(s))throw new h(`Aggregate numeric field "${s}" is not registered. Allowed: ${t.join(", ")}`,m.USAGE);return{field:s,sum:o!==void 0,avg:i!==void 0}}function Co(e){let t=e?.trim()??"status";if(t.length===0)throw new h("--group-by requires at least one field name",m.USAGE);let r=Pn(t);if(r.length===0)throw new h("--group-by requires a comma-separated list of fields",m.USAGE);for(let n of r)if(!ko.includes(n))throw new h(`Aggregate group fields must be one of ${ko.join("|")}; received "${n}"`,m.USAGE);return r}function To(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 Mo(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 To(t.tags);case"sprint":return t.sprint??null;case"release":return t.release??null;default:return null}}function Fo(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 $e(e,t){return e.map(r=>`${r}:${JSON.stringify(t[r]??null)}`).join("|")}var ys={parent:"(unparented)",type:"(untyped)",priority:"(no priority)",status:"(no status)",assignee:"(unassigned)",tags:"(untagged)",sprint:"(no sprint)",release:"(no release)"};function xo(e,t){return t==null||t===""?ys[e]:String(t)}function _s(e,t){return e.length===1?xo(e[0],t[e[0]]):e.map(r=>`${r}=${xo(r,t[r])}`).join(" | ")}function Do(e,t,r){for(let n of r){let o=Fo(e.group[n],t.group[n]);if(o!==0)return o}return 0}function Po(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 Ho(e,t){return t<=0?0:Math.round(e/t*1e4)/100}function Ft(e,t,r){let n=Vr(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 ws(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 vs(e,t){if(t===null){e.null_count+=1;return}e.numeric_count+=1,e.numeric_sum+=t}function bs(e){e.accumulator.row.count+=1,e.includeCompletion&&Ft(e.accumulator,e.item.status,e.statusRegistry),e.numericAggregation!==null&&vs(e.accumulator,e.numericValue)}function Es(e,t,r,n){for(let o of t){let i=$e(r,o),s=e.get(i);if(s){bs({...n,accumulator:s});continue}let a=ws(o,n.numericValue);n.includeCompletion&&Ft(a,n.item.status,n.statusRegistry),e.set(i,a)}}function Ss(e,t){let r={};for(let n of e)r[n]=Mo(n,t);return r}function Is(e,t,r){let n=[Ss(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(l=>({...a,[o]:l}))))}return n}function ks(e,t,r,n){let o={...e.row,group_label:_s(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=Ho(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 xs(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 ed(e,t){if(e.count===!1)throw new h("Aggregate grouped counts are always enabled; omit count=false.",m.USAGE);let r=x(process.cwd(),t.path),n=await j(r),o=W(n.schema),i=["estimate","estimated_minutes","priority",...J(n.schema).definitions.filter(v=>v.type==="number").map(v=>v.metadata_key)],s=Co(e.groupBy),a=e.setMode??"element";if(a!=="element"&&a!=="tuple")throw new h("Aggregate --set-mode must be element or tuple",m.USAGE);let l=Ro(e.status,o),d=Ao(e,[...new Set(i)].sort((v,E)=>v.localeCompare(E))),c=e.completion===!0,u=e.includeUnparented===!0,f=await We(void 0,{...Io(e),status:e.status,noTruncate:!0,strictRead:!0},t),p=new Map,y=0,_=0,g=0;for(let v of f.items){let E=v;if(s.includes("parent")&&E.parent===void 0&&!u){y+=1;continue}let C=d===null?null:Po(E,d.field),k=Is(s,E,a);Es(p,k,s,{item:E,statusRegistry:o,includeCompletion:c,numericAggregation:d,numericValue:C}),g+=k.length,_+=1}let w=[...p.values()].map(v=>ks(v,s,c,d)).sort((v,E)=>Do(v,E,s)),b=f.warnings&&f.warnings.length>0?f.warnings:void 0;return{...Rs(w,s,e),count:w.length,totals:{items_considered:f.items.length,items_grouped:_,items_skipped_unparented:y,group_memberships:g},filters:xs({groupBy:s,setMode:a,includeCompletion:c,includeUnparented:u,status:l,options:e,numericAggregation:d}),now:S(),...b?{warnings:b}:{}}}function Rs(e,t,r){let n=Xn(r.limit,"limit")??50,o=r.after===void 0?-1:e.findIndex(a=>$e(t,a.group)===r.after);if(r.after!==void 0&&o<0)throw new h("Aggregate --after cursor is absent from the current grouping; restart without --after.",m.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?$e(t,i.at(-1).group):null}}var td={buildGroupKey:$e,compareAggregateRows:Do,compareNullableGroupValue:Fo,completionPct:Ho,normalizeTagGroupValue:To,parseGroupBy:Co,parseNumericAggregation:Ao,parseStatus:Ro,readNumericAggregateValue:Po,resolveGroupValue:Mo,updateCompletionCounts:Ft};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="acda1c64-cb50-57b5-868d-a27ca6912979")}catch{}})();var Lo=1e6,Oo=20;function jo(e,t,r,n=Oo){if(!Number.isSafeInteger(n)||n<0)throw new h("Child projection sample limit must be a non-negative integer.",m.USAGE);let o=e.trim().toLowerCase(),i={},s=[],a=0;for(let g of t){if(a+=1,a>Lo)throw new h(`Child projection exceeded the ${Lo.toLocaleString("en-US")} item safety bound.`,m.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 l=new Map(s.map(g=>[g.id.trim().toLowerCase(),g])),d=$n(Bn(s,Wn())),c=new Set(d.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=>l.get(g)),f=0;for(let g of u){let w=g.status.trim().toLowerCase();i[w]=(i[w]??0)+1,ae(w,r)||(f+=1)}u.sort((g,w)=>g.id.localeCompare(w.id));let p=u.slice(0,n).map(g=>({id:g.id,title:g.title,type:g.type,status:g.status,priority:g.priority})),y=u.length>p.length,_=n===0?Oo:n;return{count:u.length,active:f,by_status:Object.fromEntries(Object.entries(i).sort(([g],[w])=>g.localeCompare(w))),sample:p,sample_limit:n,truncated:y,next_offset:y?p.length:null,continuation:y?`pm list --status all --parent ${e} --offset ${p.length} --limit ${_}`:null,scanned:a}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="926ca5b2-8cfc-56e7-8cbf-fb0e7152d834")}catch{}})();var As=new Set(["event","meeting","reminder"]);function Cs(e){return As.has(e.type.trim().toLowerCase())||e.deadline!==void 0||(e.reminders?.length??0)>0||(e.events?.length??0)>0}function Dt(e){if(!Cs(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}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="26bf8487-2515-5885-b6de-56ba6292fb65")}catch{}})();var Ms=new Set(["epic","feature","milestone","plan"]),Fs=new Set(Object.keys(Pr).map(e=>e.toLowerCase()));function Ht(e){return Object.fromEntries(["comments","notes","learnings","files","tests","docs","reminders","events"].map(r=>[r,e[r]?.length??0]))}function Ds(e,t){let r=Ht(e);return[...t.length>0?["body"]:[],...Object.entries(r).flatMap(([n,o])=>o>0?[n]:[]),...r.files+r.tests+r.docs>0?["linked"]:[],"children",...typeof e.assignee=="string"&&e.assignee.trim().length>0?["claim_state"]:[],...Dt(e)?["schedule"]:[]]}function No(e){let t=e.trim().toLowerCase();return t.length>0&&(Ms.has(t)||!Fs.has(t))}function qo(e){return{ts:e.ts,author:e.author,message:e.message??null}}function Ps(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?qo(o):null,last_release:i?qo(i):null}}function Hs(e){if(e===void 0||e.trim().length===0)return"standard";let t=e.trim().toLowerCase();if(t==="full")return"deep";if(wt.includes(t))return t;throw new h("Get --depth must be one of brief|standard|deep|full",m.USAGE)}function Ls(e,t){let r=Ht(e);if(t==="deep")return{...e,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:r.notes,tests_count:r.tests,collection_counts:r};let{comments:n,notes:o,learnings:i,files:s,tests:a,docs:l,reminders:d,events:c,...u}=e;return{...u,notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:r}}function Os(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 h("Get --fields requires a comma-separated list of field names",m.USAGE);return t}function Ve(e){return e.startsWith("item.")?e.slice(5):e}function js(e,t,r){if(e===null)return;let n=vt(t),o=new Set(n),i=e.filter(s=>{let a=Ve(s);return!o.has(s)&&!o.has(a)});if(i.length>0){let s=["get",r,"--fields","id,title,status"];throw new h(`Unknown get --fields value(s): ${i.join(", ")}`,m.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:X(s),suggested_retry_args:s}})}}var qs=new Set(["comments","notes","learnings","files","tests","test_runs","docs","reminders","events","dependencies","plan_steps","plan_decisions","plan_discoveries","plan_validation"]);function Ns(e,t,r){return Object.hasOwn(t,r)?t[r]:e[r]!==void 0?e[r]:qs.has(r)?[]:void 0}function Us(e,t){let r=e,n={notes_count:e.notes?.length??0,tests_count:e.tests?.length??0,collection_counts:Ht(e)},o={id:e.id};for(let i of t){let s=Ve(i);s==="body"||s==="linked"||s.startsWith("linked.")||s==="claim_state"||s.startsWith("claim_state.")||s==="children"||s.startsWith("children.")||s==="schedule"||s.startsWith("schedule.")||(o[s]=Ns(r,n,s))}return o}function ge(e,t){return e?.some(r=>r===t||r===`item.${t}`)??!1}function ze(e,t){return e.some(r=>{let n=Ve(r);return n===t||n.startsWith(`${t}.`)})}function Gs(e,t){if(e.full&&(e.fields!==void 0||e.depth!==void 0))throw new h("Get projection options are mutually exclusive; remove the extra projection flag and retry.",m.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:X(["get",t,"--full"]),suggested_retry_args:["get",t,"--full"]}});if(e.tree!==!0&&e.treeDepth!==void 0)throw new h("Get --tree-depth requires --tree",m.USAGE);if(e.at!==void 0&&e.tree===!0)throw new h("Get --at cannot be combined with --tree because workspace-level historical projections are not yet indexed.",m.USAGE);return{depth:e.full?"deep":Hs(e.depth),treeDepth:e.tree===!0?Ln(e.treeDepth,"--tree-depth"):void 0,fields:Os(e.fields),fieldProjection:e.fields!==void 0}}async function Ws(e,t,r){let n=x(process.cwd(),t.path);await L(n);let o=await j(n),i=G(o,T());if(r!==void 0){let l=await wn(e,r,{pmRoot:t.path});return{pmRoot:n,settings:o,typeToFolder:i.type_to_folder,locatedId:l.document.metadata.id,metadata:l.document.metadata,body:l.document.body,historical:l}}let s=await De(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 Pe(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 Bs(e,t,r,n){let o=J(t.schema).definitions.map(i=>i.metadata_key);if(js(e,o,n),r&&ze(e??[],"children"))throw new h("Get --at cannot project children because workspace-level historical relationships are not yet indexed.",m.USAGE)}function Pt(e){let{fieldProjection:t,depth:r,fields:n,field:o}=e;return t?o==="body"||o==="linked"?ge(n,o):ze(n,o):r!=="brief"}async function $s(e,t){if(!t)return;let r=Ie(e.pmRoot,e.locatedId),n=await ce(r,e.locatedId);return Ps(e.metadata.assignee,e.historical?n.slice(0,e.historical.target.historyIndex+1):n)}function zs(e,t,r,n){let o=n||ge(r,"linked.files"),i=n||ge(r,"linked.tests"),s=n||ge(r,"linked.docs");!n&&!o&&!i&&!s||(e.linked={files:o?t.metadata.files??[]:[],tests:i?t.metadata.tests??[]:[],docs:s?t.metadata.docs??[]:[]})}async function Vs(e,t){if(!t)return;let r=W(e.settings.schema),n=await He(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema);return jo(e.locatedId,n,r)}function Ks(e,t,r,n){if(!n)return;let o=Dt(t.metadata);if(o){if(r===null||ge(r,"schedule")){e.schedule=o;return}e.schedule=Object.fromEntries(Object.entries(o).filter(([i])=>r.some(s=>Ve(s)===`schedule.${i}`)))}}async function Qs(e,t,r,n){if(t.tree!==!0)return;let o=await We(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 Sd(e,t,r={}){let n=Gs(r,e),o=await Ws(e,t,r.at);Bs(n.fields,o.settings,o.historical!==void 0,o.locatedId);let i=Pt({...n,field:"body"}),s=Pt({...n,field:"linked"}),a=Pt({...n,field:"claim_state"}),l=o.historical===void 0&&(n.fieldProjection?ze(n.fields,"children"):n.depth==="deep"&&No(o.metadata.type)),d=n.fieldProjection?ze(n.fields,"schedule"):n.depth!=="brief",c=await $s(o,a),u={item:n.fieldProjection?Us(o.metadata,n.fields):Ls(o.metadata,n.depth)};i&&(u.item.body=o.body),zs(u,o,n.fields,s),c&&(u.claim_state=c),Ks(u,o,n.fields,d);let f=await Vs(o,l);f!==void 0&&(u.children=f);let p=await Qs(o,r,n.treeDepth,t);if(p!==void 0&&(u.tree=p),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 zr({pmRoot:o.pmRoot,author:Ae(void 0,o.settings.author_default),itemIds:[o.locatedId],intent:"get"})}catch{}return jr(u,Ds(o.metadata,o.body)),u}var Id={shouldAutoIncludeGetChildren:No};(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0cc18a30-5068-5c59-b559-7afc4d446ed8")}catch{}})();function Ys(e,t){return t===void 0?e:e.slice(Math.max(0,e.length-t))}function Xs(e,t){return e.map(({entry:r,version:n})=>{let o=new Set,i=nn(r.patch);for(let s of i)o.add(yt(s.path)),s.from&&o.add(yt(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 Js(e){if(e[0]?.op!=="history_compact_baseline")return;let t=N(e,!0);return{offset:t,first_version:t===null?null:t+1,last_version:t===null?null:t+e.length}}async function Zs(e,t){let r=x(process.cwd(),t.path);await L(r);let n=await j(r),o=G(n,T()),i=e.trim()===Ce,s=i?Ce:dn(e,n.id_prefix),a=await De(r,s,n.id_prefix,n.item_format,o.type_to_folder),l=a?.id??s,d=i?cn(r):Ie(r,l);if(!a&&!await be(d))throw new h(`Item ${e} not found`,m.NOT_FOUND);return a&&await Te({pmRoot:r,settings:n,itemId:a.id,commandLabel:"history"}),{historyPath:d,located:a,resolvedId:l,settings:n}}async function Pd(e,t,r){let n=Oe(t.limit),{historyPath:o,located:i,resolvedId:s,settings:a}=await Zs(e,r),l=await ce(o,s),d=Js(l),c=a.agent_identity.identity_vocabulary,u=eo(a.agent_identity.harness_signals),f=ro({harness:t.harness,agentInstance:t.agentInstance,provenance:t.provenanceFilter},c,u),p=ea(l).filter(({entry:I})=>f(I)),y=Ys(p,n),_=y.map(({entry:I})=>I),g=t.compact===!0,w=g?Xs(y,d):void 0,b=t.provenance===!0?y.map(({entry:I,durableVersion:R})=>to(I,c,{itemId:s,version:R})):void 0,v=t.provenance===!0?"provenance":g?"compact":"full",E={compact:{compact_history:w},provenance:{provenance_history:b},full:{history:_}}[v],k={id:s,...E,compact:g,projection:{mode:v,row_key:{compact:"compact_history",provenance:"provenance_history",full:"history"}[v]},omission_receipt:qr("history",v),count:_.length,limit:n??null,version_addressing:d,...t.provenanceSummary===!0?{provenance_summary:no(p.map(({entry:I})=>I),c,u)}:{}};if((t.diff||t.field!==void 0)&&(k.diff=In(l,{windowStartIndex:Math.max(0,l.length-_.length),field:t.field})),t.verify){let I=i?(await Pe(i,{schema:a.schema})).document:void 0;if(k.verification=_n(l,I),s===Ce&&k.verification.ok){let R=await ln(x(process.cwd(),r.path));k.verification={...k.verification,ok:R.ok,errors:R.ok?k.verification.errors:[...k.verification.errors,"verify_failed:workspace_state_mismatch"],workspace_state_matches_latest:R.ok,workspace_state_mismatches:R.mismatched_documents,workspace_state_missing:R.missing_documents,workspace_state_unreadable:R.unreadable_documents}}}return k}function ea(e){let t=N(e,!0);return e.map((r,n)=>({entry:r,version:n+1,durableVersion:t===null?void 0:t+n+1}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6a84083a-153e-590f-bb9b-cde96ed09a74")}catch{}})();function ta(e){if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(t!=="keyword"&&t!=="semantic"&&t!=="hybrid")throw new h("Search mode must be one of keyword|semantic|hybrid",m.USAGE);return t}function Ke(e){return e===!0}function Uo(e){return Dr(e,0,1)??void 0}function Go(e){if(e===void 0)return"or";let t=e.trim().toLowerCase();if(t!=="and"&&t!=="or"&&t!=="exact")throw new h("Search --match-mode must be one of and|or|exact",m.USAGE);return t}function Wo(e){if(e==null||e==="")return;let t=typeof e=="number"?e:Number(String(e).trim());if(!Number.isFinite(t)||t<0)throw new h("Search --min-score must be a finite number >= 0",m.USAGE);return t}function Q(e,t){if(e==null)return;let r=String(e).trim();if(r.length!==0)return dt(r,new Date,t)}function F(e){return e.toLowerCase().replace(/\s+/g," ").trim()}function Lt(e,t){if(e!==void 0)return dt(e,new Date,t)}function ra(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 h("Search --fields requires a comma-separated list of field names",m.USAGE);return[...new Set(t)]}function Qe(e,t="<query>"){let r=e.compact===!0,n=e.full===!0,o=ra(e.fields);if(Number(r)+Number(n)+ +(o!==void 0)>1)throw new h("Search projection options are mutually exclusive. Use one of --compact, --full, or --fields.",m.USAGE,{code:"projection_options_mutually_exclusive",recovery:{suggested_retry:X(["search",t,"--full"]),suggested_retry_args:["search",t,"--full"]}});return r?{mode:"compact",fields:[...zn]}:n?{mode:"full",fields:[]}:o?{mode:"fields",fields:o}:{mode:"full",fields:[]}}function Ot(e,t,r="<query>"){if(e.mode!=="fields")return;let n=Vn(t.definitions.flatMap(s=>[s.key,s.metadata_key])),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","id,title,status,score"];throw new h(`Unknown search --fields value(s): ${i.join(", ")}`,m.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:X(s),suggested_retry_args:s}})}}function Ye(e){let t=F(e);if(!t)throw new h("Search query must not be empty",m.USAGE);return t.split(/\s+/u).filter(Boolean)}function jt(e){let t=e.search?.max_results;return typeof t=="number"&&Number.isFinite(t)&&t>0?Math.floor(t):50}var na=["auto","keyword","semantic","hybrid"];function oa(e){let t=e.search?.default_mode;if(typeof t!="string")return"auto";let r=t.trim().toLowerCase();return na.includes(r)?r:"auto"}function qt(e){if(typeof e.requested=="string"&&e.requested.trim().length>0)return{mode:ta(e.requested),source:"explicit"};let t=oa(e.settings);return t!=="auto"?{mode:t,source:"settings"}:{mode:e.semanticRunnable?"hybrid":"keyword",source:"auto"}}function Nt(e){let t=e.search?.score_threshold;return typeof t=="number"&&Number.isFinite(t)?t:0}function Ut(e){let t=e.search?.hybrid_semantic_weight;return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=1?t:.7}function Gt(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)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="91b01dd0-6a8d-5b97-96d2-c27f4044c009")}catch{}})();function ia(e){return Ur("search",{query:e.query.trim(),mode:e.mode,options:Nr(e.searchOptions,Hn)})}function Bo(e){let t=Gr(e.sorted,{cursor:e.searchOptions.after,fingerprint:ia(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(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="48888c80-60e1-5905-afd5-8c1b6e532f99")}catch{}})();function $o(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 sa=[{optionKey:"status",summaryKey:"status",normalize:e=>$o(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 re(e){let{mode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:l,runtimeFieldFilters:d}=e,c={};return Yn(c,n,sa),Object.assign(c,Et(n)),Object.assign(c,bt(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=l),n.limit!==void 0&&(c.limit=n.limit),d&&Object.keys(d).length>0&&(c.runtime_filters=d),c}function ne(e){let{effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:i,phraseExact:s,scoreThreshold:a,hybridSemanticWeight:l,queryExpansion:d,rerank:c,runtimeFieldFilters:u}=e,f=p=>p??null;return{mode:t,match_mode:r,status:n.status===void 0||$o(n.status)?"all":n.status,type:f(n.type),tag:f(n.tag),priority:f(n.priority),deadline_before:f(n.deadlineBefore),deadline_after:f(n.deadlineAfter),updated_after:f(n.updatedAfter),updated_before:f(n.updatedBefore),created_after:f(n.createdAfter),created_before:f(n.createdBefore),assignee:f(n.assignee),sprint:f(n.sprint),release:f(n.release),parent:f(n.parent),...Et(n),...bt(n),include_linked:o,title_exact:i,phrase_exact:s,score_threshold:a,hybrid_semantic_weight:t==="hybrid"?l:null,query_expansion_enabled:d.enabled,query_expansion_provider:d.provider,rerank_enabled:c.enabled,rerank_model:c.model,rerank_top_k:c.top_k,limit:f(n.limit),runtime_filters:u}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bc52818b-d37f-5d00-954d-d50203a433c2")}catch{}})();var aa=1.2,ca=.75;function Wt(e){return ee(e)}function la(e){let t=new Map;for(let r of e)t.set(r,(t.get(r)??0)+1);return t}function Vo(e){let t=[],r=new Map,n=0;for(let i of e){let s=Wt(i.text),a=la(s);n+=s.length;for(let l of a.keys())r.set(l,(r.get(l)??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 da(e,t){return Math.log(1+(e-t+.5)/(t+.5))}function Ko(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,da(e.documentCount,a))}if(i.size===0)return n;for(let s of e.documents){let a=0;for(let[l,d]of i){let c=s.termFrequencies.get(l);if(c===void 0)continue;let u=1-r.b+r.b*s.length/e.averageDocumentLength,f=c+r.k1*u;a+=d*(c*(r.k1+1)/f)}a>0&&n.set(s.id,a)}return n}function zo(e,t,r,n){return typeof e!="number"||!Number.isFinite(e)?t:Math.min(n,Math.max(r,e))}function Qo(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 Yo(e){let t=e?.search?.bm25;return{k1:zo(t?.k1,aa,0,1e3),b:zo(t?.b,ca,0,1)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e2985104-efdb-59e5-9674-2dd865ebdf56")}catch{}})();var Bt=4,ua=20,fa=200,ma=new Set(["a","an","and","for","from","in","into","of","on","or","the","to","with"]);function $t(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 ha(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 pa(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 Xo(e,t=Bt){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=>!ma.has(a.toLowerCase())),i=n.map(a=>ha(a)),s=o.map(a=>pa(a));return $t([r,n.join(" "),o.join(" "),i.join(" "),s.join(" ")],Math.max(1,t))}function Jo(e){let t=Array.isArray(e)?e:e?.queries;return Array.isArray(t)?$t(t.filter(r=>typeof r=="string"),Bt):[]}function Zo(e,t,r){return $t([...e,...t],Math.max(1,r))}function ei(e,t){let n=e.search?.query_expansion,o=ie(n?.provider);return{enabled:n?.enabled===!0,provider:o??t,max_queries:Bt}}function ti(e,t){let n=e.search?.rerank,o=ie(n?.model),s=Se(n?.top_k)??ua;return{enabled:n?.enabled===!0,model:o??t,top_k:Math.min(fa,s)}}function ri(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=ie(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 ga(e,t){let r=e.length,n=0;for(let o=0;o<r;o+=1)n+=e[o]*t[o];return n}function ni(e){let t=0;for(let r=0;r<e.length;r+=1)t+=e[r]*e[r];return Math.sqrt(t)}function ya(e,t,r){if(!e||!t||e.length===0||t.length===0||e.length!==t.length)return 0;let n=ga(e,t),o=ni(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 oi(e,t,r,n,o){if(n.length===0)return new Map;let i=ie(t)??e.model,s=i===e.model?e:{...e,model:i},a=[r.trim(),...n.map(f=>f.text)],l=await je(s,a,o?{timeout_ms:o}:{}),d=l[0];if(!d)return new Map;let c=ni(d),u=new Map;for(let f=0;f<n.length;f+=1){let p=n[f],y=l[f+1];if(!y)continue;let _=ya(d,y,c);u.set(p.id,Math.max(0,Math.min(1,(_+1)/2)))}return u}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a5e4bd88-a099-559f-8194-7b56f325eb0e")}catch{}})();function oe(e){return Array.isArray(e)?e.filter(t=>typeof t=="string"):[]}function U(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.text=="string"):[]}function ye(e){return Array.isArray(e)?e.filter(t=>typeof t=="object"&&t!==null&&typeof t.id=="string"&&typeof t.kind=="string"):[]}function zt(e){let t=e.metadata;return[t.title,t.description,t.status,oe(t.tags).join(" "),e.body,U(t.comments).map(r=>r.text).join(" "),U(t.notes).map(r=>r.text).join(" "),U(t.learnings).map(r=>r.text).join(" "),qe(t).join(" "),Ne(t).join(" "),ye(t.dependencies).map(r=>`${r.id} ${r.kind}`).join(" "),Ue(t)]}function Vt(e,t){return zt(e).some(r=>F(r).includes(t))}function Kt(e,t,r){return!r.titleExact&&!r.phraseExact?e:e.filter(n=>!(r.titleExact&&F(n.metadata.title)!==t||r.phraseExact&&!Vt(n,t)))}function _a(e){if(e&&[...e].some(t=>t.toLowerCase()==="none"||t.toLowerCase()==="null"))throw new h('--assignee no longer accepts "none" or "null".',m.USAGE)}function wa(e,t,r){let n=me(e.assignee,{label:"--assignee"});_a(n);let o=Kn(e),i=Qn(e);return{typeFilter:On(e.type,t),tagFilter:me(e.tag,{label:"--tag",normalize:s=>s.toLowerCase()}),priorityFilter:jn(e.priority),deadlineBefore:Lt(e.deadlineBefore,"deadline-before"),deadlineAfter:Lt(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:me(e.sprint,{label:"--sprint"}),releaseFilter:me(e.release,{label:"--release"}),parentFilter:e.parent?.trim(),statusSet:r&&r.length>0?new Set(r):void 0,missingMetadataFilters:o,missingMetadataActive:qn(o),contentFieldFilters:i,contentFiltersActive:Un(i)}}function va(e,t){return ba(e,t)&&Br(e,t)&&Ea(e,t)}function ba(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&&!oe(e.tags).some(n=>r.has(n))||t.priorityFilter!==void 0&&!t.priorityFilter.has(e.priority))}function Ea(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 Sa(e,t,r,n){let o=e.metadata;return!(!va(o,t)||!xn(o,r)||t.missingMetadataActive&&!Nn(o,t.missingMetadataFilters,n)||t.contentFiltersActive&&!Gn(o,t.contentFieldFilters))}function Qt(e,t,r,n,o,i){let s=wa(t,r,o);return e.filter(a=>Sa(a,s,n,i))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a927991-1dbe-5906-a0eb-7da2534b6905")}catch{}})();var Ia=2,ka=120,xa=6,Ra=40,Aa=1e3,Ca=900,Ta="\xAB",Ma="\xBB",ii=60;function Xe(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 si=[{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=>oe(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=>U(e.metadata.comments).map(t=>t.text).join(" ")},{name:"notes",weightKey:"notes_weight",value:e=>U(e.metadata.notes).map(t=>t.text).join(" ")},{name:"learnings",weightKey:"learnings_weight",value:e=>U(e.metadata.learnings).map(t=>t.text).join(" ")},{name:"reminders",weightKey:"reminders_weight",value:e=>qe(e.metadata).join(" ")},{name:"events",weightKey:"events_weight",value:e=>Ne(e.metadata).join(" ")},{name:"dependencies",weightKey:"dependencies_weight",value:e=>ye(e.metadata.dependencies).map(t=>`${t.id} ${t.kind}`).join(" ")},{name:"plan",weightKey:"body_weight",value:e=>Ue(e.metadata)}],Fa=new Map(si.map(e=>[e.name,e]));function Yt(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=>`${Ta}${o}${Ma}`)}function Xt(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-ii),s=Math.min(e.length,n+o+ii),a=Yt(e.slice(i,s),t),l=i>0?"\u2026":"",d=s<e.length?"\u2026":"";return`${l}${a}${d}`}function Je(e,t,r){let n=[];for(let o of t){let i=Fa.get(o);if(i===void 0)continue;let s=Xt(i.value(e),r);s!==null&&n.push({field:o,snippet:s})}return n}function Da(e,t,r){return[...si.map(n=>({name:n.name,value:n.value(e),weight:r[n.weightKey]})),{name:"linked_content",value:t,weight:r.linked_content_weight}]}function Pa(e,t,r){let n=F(e.id),o=typeof r=="string"?r.trim().toLowerCase():"",i=F(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?Aa:Ca,matched_fields:["id"],matched_all_terms:!0,exact_id_match:!0}}function Ha(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 l=Xe(a.value.toLowerCase(),i);l>0&&(o.score+=l*a.weight,o.matched.add(a.name),o.matchedTokens.add(i))}}}function La(e,t,r,n){F(e.title)===t&&(n.score+=ka,n.matched.add("title"));for(let i of r){let s=Xe(F(i.value),t);s>0&&(n.score+=s*i.weight*xa,n.matched.add(i.name))}}function Jt(e,t,r,n,o,i,s=!1){let a=e.metadata,l=Pa(a,r,i);if(l)return l;let d=new Map;for(let _ of ee(a.title))d.set(_,(d.get(_)??0)+1);let c=Da(e,n,o),u={score:0,matched:new Set,matchedTokens:new Set};Ha(t,d,c,o,u);let f=new Set(t),p=f.size>0&&u.matchedTokens.size===f.size;return s&&f.size>1&&p&&(u.score+=Ra),t.length>=Ia&&r.includes(" ")&&La(a,r,c,u),u.score<=0?null:{item:a,score:u.score,matched_fields:[...u.matched].sort((_,g)=>_.localeCompare(g)),matched_all_terms:p}}function Zt(e,t){return[...e].sort((r,n)=>{let o=n.score-r.score;if(o!==0)return o;let i=ae(r.item.status,t),s=ae(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 l=Wr(n.item.updated_at,r.item.updated_at);return l!==0?l:r.item.id.localeCompare(n.item.id)})}function er(e,t,r,n,o,i,s,a=!1){return Jt(e,t,r,n?o.get(e.metadata.id)??"":"",i,s,a)}function _e(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(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0175d395-3f87-5a93-8d4f-a3150aaf16ae")}catch{}})();function et(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 tt(e){let t=(e instanceof Error?e.message:String(e)).toLowerCase(),r=et(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 tr(e,t){let r=tt(t);return`search_${e}_fallback:${r}:using_keyword_mode`}function ai(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 rr(e,t,r){try{let n=await Dn(e);n.warnings.length>0&&r.push(...n.warnings);let o=Jn(t.map(s=>({id:s.metadata.id,updated_at:s.metadata.updated_at})),n.entries);if(o.length===0)return;let i=ai(T());r.push(...ci(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 ci(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 rt(e,t,r,n){if(!t.active)throw new h(`Search mode '${e}' requires a configured embedding provider in settings.providers.openai or settings.providers.ollama`,m.USAGE);if(!r.active&&!n)throw new h(`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`,m.USAGE);return{provider:t.active,vectorStore:r.active??null}}var D=Ee;function we(e){let t=T(),r=vn(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=D(n.name)??D(r.definition.name)??e;if(!a)return null;let l={providerName:a,...typeof o=="function"?{query:o}:{},...typeof i=="function"?{queryExpansion:i}:{},...typeof s=="function"?{rerank:s}:{}};return!l.query&&!l.queryExpansion&&!l.rerank?null:l}function nr(e){let t=D(e.search?.provider),r=we(t);return r?.query?{providerName:r.providerName,query:r.query}:null}function or(e){let t=T(),r=D(e.vector_store?.adapter),n=bn(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:D(o.name)??D(n.definition.name)??r??"extension",query:i,...typeof s=="function"?{upsert:s}:{}}}function ir(e,t,r){let n=Array.isArray(t)?t:t?.hits;if(!Array.isArray(n))throw new h(`Extension search provider "${e}" must return an array of hits or { hits: [...] }`,m.GENERIC_FAILURE);let o=new Set,i=[];for(let s of n){if(typeof s!="object"||s===null)continue;let a=D(s.id),l=s.score;if(!a||typeof l!="number"||!Number.isFinite(l)||o.has(a))continue;let d=r.get(a);if(!d)continue;let c=s.matched_fields,u=Array.isArray(c)&&c.every(f=>typeof f=="string")?[...new Set(c.map(f=>f.trim()).filter(f=>f.length>0))].sort((f,p)=>f.localeCompare(p)):[`provider:${e}`];o.add(a),i.push({item:d.metadata,score:l,matched_fields:u})}return i}function sr(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 Ze(e,t){let r=t.filter(d=>d.exact_id_match===!0);if(r.length===0)return e;let n=new Set(r.map(d=>d.item.id)),o=e.filter(d=>!n.has(d.item.id)),i=o.reduce((d,c)=>Math.max(d,c.score),0),s=r.sort((d,c)=>c.score-d.score),a=i+s.length+1;return[...s.map((d,c)=>({...d,score:a-c,matched_fields:["id"]})),...o]}function nt(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=_e(t),l=_e(i),d=new Set([...t.keys(),...i.keys()]),c=1-n;return[...d].map(u=>{let f=e.get(u),p=a.get(u)??0,y=l.get(u)??0,_=p*n+y*c;if(_<=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:f.metadata,score:_,matched_fields:[...g].sort((w,b)=>w.localeCompare(b))}}).filter(u=>u!==null)}function ar(e){let t=e.configuredProvider?.trim().toLowerCase();return t==="bm25"?"explicit":t==="auto"&&!e.hasEmbeddingProvider&&!e.hasExtensionSearchProvider?"auto-fallback":null}function cr(e){let t=e.filteredDocuments.map(s=>({id:s.metadata.id,text:Qo(Mn(s,{fields:e.corpusFields}))})),r=Vo(t),n=Ko(r,Wt(e.query),e.bm25Params),o=new Map(e.filteredDocuments.map(s=>[s.metadata.id,s]));if(e.requestedMode==="semantic"){let s=[...n].map(([a,l])=>({item:o.get(a).metadata,score:l,matched_fields:["bm25"]}));return Ze(s,e.keywordHits)}let i=nt(o,n,e.keywordHits,e.hybridSemanticWeight,"bm25");return Ze(i,e.keywordHits)}function lr(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 dr(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 Oa(e,t){let r=e.queryExpansion.enabled?Xo(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 Zo(n,Jo(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 ja(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 h(`Extension vector adapter query failed and no built-in fallback store is configured (${o instanceof Error?o.message:String(o)})`,m.GENERIC_FAILURE);return e.warnings.push(`search_vector_adapter_failed:${e.extensionVectorAdapter.adapterName}:using_builtin`),await _t(e.vectorStore,t,r,n)}if(e.vectorStore)return await _t(e.vectorStore,t,r,n);throw new h("Semantic search requires either a configured vector store or an extension vector adapter query handler",m.USAGE)}function qa(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:dr(i)}:null}).filter(o=>o!==null)}async function Na(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=ri(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 Ua(e,t,r){let n=await Na(e,t,r);if(n)return n;let o=r.map(i=>({id:i.hit.item.id,text:i.text}));try{return await oi(e.provider,e.rerank.model,t,o,e.embeddingTimeoutMs)}catch{return e.warnings.push("search_rerank_failed:using_hybrid_scores"),null}}function Ga(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,l)=>a.localeCompare(l))}});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 Wa(e,t,r,n){if(!e.rerank.enabled||r.length<=1)return r;let o=qa(r,n,e.rerank.top_k),i=await Ua(e,t,o);return i&&i.size>0?Ga(r,i):r}async function ur(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 Oa(e,o),s=await je(e.provider,i,r),a=await Promise.all(s.map(async y=>await ja(e,y,t,n))),l=lr(a),d=new Map(e.filteredDocuments.map(y=>[y.metadata.id,y])),{semanticHits:c,semanticScores:u}=sr(l,d),f=u.size;if(e.requestedMode==="semantic")return{hits:Ze(c,e.keywordHits),vectorMatchCount:f};let p=await Wa(e,o,nt(d,u,e.keywordHits,e.hybridSemanticWeight),d);return{hits:Ze(p,e.keywordHits),vectorMatchCount:f}}function li(e){let t=we(e.provider??void 0);return t?.queryExpansion?{providerName:t.providerName,expand:t.queryExpansion}:null}function di(e){let t=we(D(e.search?.provider));return t?.rerank?{providerName:t.providerName,rerank:t.rerank}:null}import ot from"node:fs/promises";import fr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e743cc1-3ff0-58b1-bf11-351d1655864c")}catch{}})();function mr(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 ui(e){let t=fr.resolve(e);try{let r=await ot.realpath(t);return{resolved:t,realpath:r}}catch{return null}}async function hr(e,t){let[r,n]=await Promise.all([ui(e),ui(t)]);return{projectContainmentRoot:r,globalContainmentRoot:n}}async function pr(e,t){let r=mr(e.metadata),n=[];for(let o of r){let i=o.scope==="global"?t.globalContainmentRoot:t.projectContainmentRoot;if(!i)continue;let s=fr.resolve(i.resolved,o.path);if(!ct(i.resolved,s))continue;let a;try{a=await ot.realpath(s)}catch{continue}if(ct(i.realpath,a))try{await se({path:s,scope:o.scope}),n.push(await ot.readFile(s,"utf8"))}catch{}}return n.join(`
5
5
  `)}async function gr(e,t,r,n){let o=fn(T()),i=async(d,c,u)=>{let f=async(p,y)=>{await se({path:p,scope:"project"});let _=await ot.readFile(p,"utf8");return Kr(_,{format:y,schema:n,extensionFieldNames:o,onWarning:w=>s.push(w)}).body};try{return await f(c,u)}catch{let p=u==="toon"?"json_markdown":"toon",y=z(e,d.type,d.id,p,r);try{return await f(y,p)}catch{return s.push(`item_list_item_read_failed:${fr.relative(e,y)}`),""}}},s=[],a=await mn(e,t,r,s,n),l=[];if(a.length===0){let d=await pn(e,t,r,s,n);for(let c of d){let u=z(e,c.type,c.id,t,r),f=await i(c,u,t);l.push({metadata:c,body:f})}return{documents:l,warnings:[...new Set(s)].sort((c,u)=>c.localeCompare(u))}}for(let d of a){if(typeof d.body=="string"){l.push({metadata:d.metadata,body:d.body});continue}let c=await i(d.metadata,d.item_path,d.item_format);l.push({metadata:d.metadata,body:c})}return{documents:l,warnings:[...new Set(s)].sort((d,c)=>d.localeCompare(c))}}async function fi(e,t,r){let n=new Map;if(!e||t!=="keyword"&&t!=="hybrid")return n;let o=process.cwd(),i=await hr(o,Hr(o)),s=await Promise.all(r.map(async a=>[a.metadata.id,await pr(a,i)]));for(let[a,l]of s)n.set(a,l);return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5ff2b814-42b0-50fc-92dd-17e9fc521982")}catch{}})();var mi=["tag","status","type","priority"];function yr(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=mi.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 _r(e,t,r){let n={...e};for(let o of mi){let i=t[o];if(i!==void 0){if(Ee(n[o])!==void 0){r.push(`search_inline_filter_ignored:${o}:flag_takes_precedence`);continue}n[o]=i}}return n}function hi(e,t){let r=[],n=yr(e),o=Object.keys(n.inlineFilters).length>0;if(o&&n.residualQuery.trim().length===0)throw new h("Inline field:value tokens consumed the entire query, leaving no search terms.",m.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=_r(t,n.inlineFilters,r);return{query:i,options:s,inlineWarnings:r,highlight:s.highlight===!0,includeLinked:Ke(s.includeLinked),titleExact:Ke(s.titleExact),phraseExact:Ke(s.phraseExact),matchMode:Go(typeof s.matchMode=="string"?s.matchMode:void 0),minScoreOverride:Wo(s.minScore),countOnly:s.count===!0,tokens:Ye(i),normalizedQuery:F(i),limit:Oe(s.limit),projection:Qe(s,e),modeWasExplicit:typeof s.mode=="string"&&s.mode.trim().length>0}}function pi(e){if(e.after!==void 0&&e.count===!0)throw new h("Search --after cannot be combined with --count.",m.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="984a6fdc-9383-5f89-8e71-b0d3ed2a35cc")}catch{}})();function vr(e,t,r,n,o,i,s,a,l,d,c,u,f,p){let y=f?{total:0,count_only:!0}:{};if(d.mode==="compact"&&n.compact===!0){let w=re({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,...Ir(p),items:[],count:0,...y,filters:w,...c.length>0?{warnings:c}:{}}}let g=d.mode==="full"?null:[...d.fields];return{query:e.trim(),mode:t,mode_source:p,items:[],count:0,...y,filters:ne({effectiveMode:t,matchMode:r,options:n,includeLinked:o,titleExact:n.titleExact===!0,phraseExact:n.phraseExact===!0,scoreThreshold:i,hybridSemanticWeight:s,queryExpansion:a,rerank:l,runtimeFieldFilters:u??{}}),projection:{mode:d.mode,fields:g},now:S(),...c.length>0?{warnings:c}:{}}}function br(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 Er(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]=br(r,o);return n})}function Sr(e,t){return vr(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 gi(e,t){if(e.projection.mode==="compact"&&e.options.compact===!0)return wr({query:e.query.trim(),mode:e.effectiveMode,...Ir(e.modeSource),items:[],count:t,total:t,count_only:!0,filters:re({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 wr({query:e.query.trim(),mode:e.effectiveMode,mode_source:e.modeSource,items:[],count:t,total:t,count_only:!0,filters:ne({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:e.projection.mode,fields:r},now:S()},e.warnings)}function Ir(e){return e==="settings"?{mode_source:e}:{}}function wr(e,t){return t.length===0?e:{...e,warnings:t}}function ve(e,t){return t?{...e,workspace_memory:t}:e}function yi(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:Je(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 _i(e,t,r,n,o,i){let s=n<r?{total:r}:{};if(e.projection.mode==="compact"&&e.options.compact===!0)return wr({query:e.query.trim(),mode:e.effectiveMode,...Ir(e.modeSource),items:t,count:t.length,...s,...i,filters:re({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:ne({effectiveMode:e.effectiveMode,matchMode:e.matchMode,options:e.options,includeLinked:e.includeLinked,titleExact:e.titleExact,phraseExact:e.phraseExact,scoreThreshold:e.scoreThreshold,hybridSemanticWeight:e.hybridSemanticWeight,queryExpansion:e.queryExpansion,rerank:e.rerank,runtimeFieldFilters:e.runtimeFieldFilters}),projection:{mode:o.mode,fields:a},now:S(),...e.warnings.length>0?{warnings:e.warnings}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9e7719a0-9efa-59c2-85d5-e7a5eb30d8e3")}catch{}})();var Cf={applyFilters:Qt,applyExactQueryFilters:Kt,applyInlineQueryFilters:_r,buildHitHighlights:Je,buildVerboseSearchFilters:ne,buildExplicitSemanticFallbackWarning:tr,buildCompactSearchFilterSummary:re,buildHybridLexicalScore:er,buildRerankCorpus:dr,buildSemanticHits:sr,classifyImplicitSemanticFallbackReason:tt,collectErrorCauseCodes:et,collectExactPhraseFields:zt,collectLinkedPaths:mr,combineHybridHits:nt,computeBuiltInBm25Hits:cr,computeSemanticOrHybridHits:ur,resolveBuiltInBm25Mode:ar,countOccurrences:Xe,dependencyEntries:ye,documentContainsExactPhrase:Vt,emptySearchResult:vr,highlightFieldSnippet:Xt,loadDocuments:gr,markTokenRuns:Yt,parseInlineQueryFilters:yr,maybeEmitVectorIndexStaleWarning:rr,loadLinkedCorpus:pr,mergeVectorHitsById:lr,normalizeExtensionProviderHits:ir,normalizeScoreMap:_e,parseProjectionConfig:Qe,parseTimestampWindow:Q,parseTokens:Ye,projectSearchHits:Er,readSearchFieldValue:br,requireSemanticDependencies:rt,resolveExtensionSearchProvider:nr,resolveExtensionSearchProviderByName:we,resolveExtensionVectorAdapter:or,resolveLinkedCorpusRoots:hr,scoreDocument:Jt,sortHits:Zt,stringArray:oe,textEntries:U,validateSearchProjectionFields:Ot};async function Ba(e,t){let r=x(process.cwd(),t.path);await L(r);let n=await j(r),o=Rn(n).settings,i=W(o.schema),s=J(o.schema);Ot(e.projection,s,e.query);let a=kn(e.options,s,"search"),l=G(o,T()),d=Cn(o),c=Fn(o,r),u=nr(o),f=or(o),p=Uo(e.options.semanticWeight),y=ei(o,d.active?.name??null),_=ti(o,d.active?.model??D(o.search?.embedding_model)??"text-embedding-3-small");return{pmRoot:r,settings:o,statusRegistry:i,runtimeFieldRegistry:s,runtimeFieldFilters:a,typeRegistry:l,maxResults:jt(o),scoreThreshold:e.minScoreOverride??Nt(o),semanticWeightProvided:e.options.semanticWeight!==void 0,semanticWeightOverride:p,hybridSemanticWeight:p??Ut(o),tuning:Gt(o),providerResolution:d,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:f,bm25Mode:ar({configuredProvider:D(o.search?.provider),hasEmbeddingProvider:d.active!==null,hasExtensionSearchProvider:u!==null}),queryExpansion:y,queryExpansionExtension:li(y),rerank:_,rerankExtension:di(o),...$a({requested:e.options.mode,settings:o,configuredProvider:n.search?.provider??null,providerResolution:d,vectorResolution:c,extensionSearchProvider:u,extensionVectorAdapter:f})}}function $a(e){let r=An(e.providerResolution.active?.name,e.configuredProvider)==="configured"&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null),n=e.extensionSearchProvider!==null||r,o=qt({requested:e.requested,settings:e.settings,semanticRunnable:n});return{effectiveMode:o.mode,modeSource:o.source}}async function za(e,t){let r=await gr(t.pmRoot,t.settings.item_format??"toon",t.typeRegistry.type_to_folder,t.settings.schema),n=Le(typeof e.options.status=="string"?e.options.status:void 0,t.statusRegistry,{strict:!0}),o=Ge(t.statusRegistry),i=Qt(r.documents,e.options,t.typeRegistry,t.runtimeFieldFilters,n,o);return{warnings:r.warnings,allDocuments:r.documents,filteredDocuments:Kt(i,e.normalizedQuery,{titleExact:e.titleExact,phraseExact:e.phraseExact||e.matchMode==="exact"})}}async function Va(e,t,r){let n=await fi(e.includeLinked,t.effectiveMode,r),o=e.matchMode==="or";return r.map(i=>er(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 Ka(e,t,r,n,o){if(t.bm25Mode===null||t.effectiveMode==="keyword")return null;let i=cr({requestedMode:t.effectiveMode,query:e.query,filteredDocuments:r,keywordHits:n,corpusFields:Tn(t.settings),bm25Params:Yo(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 Qa(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 ir(t.extensionSearchProvider.providerName,i,n)}catch(i){if(!o)throw new h(`Extension search provider "${t.extensionSearchProvider.providerName}" failed: ${i instanceof Error?i.message:String(i)}`,m.GENERIC_FAILURE);return null}}function Ya(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 Xa(e,t,r,n,o){let i=!e.extensionSearchProvider&&e.providerResolution.active!==null&&(e.vectorResolution.active!==null||e.extensionVectorAdapter!==null);o&&i&&await rr(e.pmRoot,r,n),e.extensionSearchProvider||rt(t,e.providerResolution,e.vectorResolution,e.extensionVectorAdapter!==null)}async function Ja(e){let{prepared:t,runtime:r,filteredDocuments:n,keywordHits:o,warnings:i,modeWasExplicit:s}=e,a=o,l=await Ka(t,r,n,o,i),d=r.effectiveMode;if(l!==null||d==="keyword")return{effectiveMode:r.effectiveMode,hits:l??a};try{if(await Xa(r,d,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 Qa(t,r,n,c)??a,a===o){let{provider:u,vectorStore:f}=rt(d,r.providerResolution,r.vectorResolution,r.extensionVectorAdapter!==null),p=await ur({requestedMode:d,query:t.query,filteredDocuments:n,keywordHits:o,hybridSemanticWeight:r.hybridSemanticWeight,limit:t.limit,maxResults:r.maxResults,provider:u,vectorStore:f,extensionVectorAdapter:r.extensionVectorAdapter,queryExpansion:r.queryExpansion,queryExpansionExtension:r.queryExpansionExtension,rerank:r.rerank,rerankExtension:r.rerankExtension,warnings:i,settings:r.settings});a=Ya(d,p,o,i)}return{effectiveMode:r.effectiveMode,hits:a}}catch(c){return i.push(tr(r.effectiveMode,c)),{effectiveMode:"keyword",hits:o}}}async function wi(e,t,r){pi(t);let n=hi(e,t),o=await Ba(n,r),i=await za(n,o),s=i.warnings;s.push(...n.inlineWarnings);let a=await oo(i.allDocuments.map(E=>E.metadata),{pmRoot:o.pmRoot,statusRegistry:o.statusRegistry,now:S()});s.push(...a.warnings);let l=io(a,n.query);o.effectiveMode==="hybrid"&&o.semanticWeightProvided&&o.semanticWeightOverride===void 0&&s.push("search_hybrid_semantic_weight_override_invalid:using_settings_default");let d={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 ve(Sr({...d,effectiveMode:o.effectiveMode},n.countOnly),l);let c=await Va(n,o,i.filteredDocuments),u=await Ja({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 ve(Sr({...d,effectiveMode:u.effectiveMode},n.countOnly),l);let f=u.hits.filter(E=>E.exact_id_match===!0||E.score>=o.scoreThreshold),p=Zt(f,o.statusRegistry),y=p.length,_=Bo({sorted:p,query:n.query,mode:u.effectiveMode,searchOptions:n.options,limit:n.limit??o.maxResults}),g={...d,effectiveMode:u.effectiveMode};if(n.countOnly)return ve(gi(g,y),l);let{hits:w,projection:b}=yi(n,i.filteredDocuments,_.limited),v=Er(w,b);return ve(_i(g,v,y,_.limited.length,b,_.pageExtras),l)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="51927137-53a7-5667-a341-c4e28a2c3964")}catch{}})();var bi=10,B="https://schema.unbrained.dev/pm/eval-query-set/v1",Za={schema:B,accepted_top_level:["array","object"],required_query_fields:["query","relevant_ids"],optional_fields:["mode","description"],modes:["keyword","semantic","hybrid"]},it={schema:B,queries:[{query:"offline search",relevant_ids:["pm-75k9"],mode:"keyword"}]},P=class extends Error{constructor(t){super(t),this.name="EvalQuerySetError"}},ec=new Set(["keyword","semantic","hybrid"]);function vi(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 tc(e,t,r){if(t.size===0)return 0;let n=e.map(a=>t.has(a)?1:0),o=vi(n,r),i=Array.from({length:t.size},()=>1),s=vi(i,r);return s===0?0:o/s}function rc(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 kr(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 nc(e,t,r){return r<=0?0:kr(e,t,r)/r}function oc(e,t,r){return t.size===0?0:kr(e,t,r)/t.size}function Ei(e,t,r){return{ndcg:tc(e,t,r),mrr:rc(e,t,r),precision:nc(e,t,r),recall:oc(e,t,r),relevant_total:t.size,retrieved_relevant:kr(e,t,r)}}function Si(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 ic(e,t){if(typeof e!="object"||e===null)throw new P(`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 P(`Eval query at index ${t} must have a non-empty "query" string`);if(!Array.isArray(r.relevant_ids))throw new P(`Eval query at index ${t} must have a "relevant_ids" array`);if(r.relevant_ids.some(i=>typeof i!="string"))throw new P(`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 P(`Eval query at index ${t} must list at least one relevant id`);if(r.mode!==void 0&&(typeof r.mode!="string"||!ec.has(r.mode)))throw new P(`Eval query at index ${t} has an invalid mode (expected keyword|semantic|hybrid)`);return{query:n,relevant_ids:o,...r.mode!==void 0?{mode:r.mode}:{},...typeof r.description=="string"&&r.description.trim().length>0?{description:r.description.trim()}:{}}}function xr(e){let t=typeof e=="object"&&e!==null&&!Array.isArray(e)?e.schema:void 0;if(t!==void 0&&t!==B)throw new P(`Unsupported eval query set schema; expected "${B}"`);let r=Array.isArray(e)?e:typeof e=="object"&&e!==null?e.queries:void 0;if(!Array.isArray(r))throw new P('Eval query set must be an array of queries or an object with a "queries" array');if(r.length===0)throw new P("Eval query set must contain at least one query");return{schema:B,queries:r.map((n,o)=>ic(n,o))}}import sc from"node:fs/promises";import Rr from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f6cfdef-5456-5716-9067-8ccadf077f5f")}catch{}})();var ac=Rr.join("search","eval-queries.json"),Ar={schema:B,examples:[JSON.stringify(it)],nextSteps:["Create a git-tracked golden-query JSON file that follows the schema, then re-run pm eval."]},cc=new Set(["keyword","semantic","hybrid"]),lc=e=>{if(e===void 0)return"keyword";let t=e.trim().toLowerCase();if(!cc.has(t))throw new h("Eval --mode must be one of keyword|semantic|hybrid",m.USAGE);return t},dc=e=>{if(e===void 0||e==="")return bi;let t=Se(e);if(t===null)throw new h("Eval --k must be a positive integer",m.USAGE);return t},uc=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 h("Eval --fail-under must be a number in the range [0, 1]",m.USAGE);return r},$=e=>Math.round(e*1e4)/1e4,fc=async e=>{try{return await sc.readFile(e,"utf8")}catch{throw new h(`Eval query set not found at ${e}`,m.NOT_FOUND,{...Ar,examples:[`echo '${JSON.stringify(it)}' > ${e}`,"pm eval --queries ./my-eval.json"]})}},mc=(e,t)=>{try{return JSON.parse(e)}catch(r){throw new h(`Eval query set at ${t} is not valid JSON: ${r instanceof Error?r.message:String(r)}`,m.USAGE,Ar)}},hc=e=>{try{return xr(e)}catch(t){throw new h(t instanceof Error?t.message:String(t),m.USAGE,Ar)}},pc=async e=>hc(mc(await fc(e),e)),gc=(e,t)=>t?Rr.resolve(process.cwd(),t):Rr.join(e,ac),yc=async(e,t,r,n)=>{let o=e.mode??t,s=(await wi(e.query,{mode:o,limit:String(r),fields:"id"},n)).items.map(l=>l.id).filter(l=>typeof l=="string"),a=Ei(s,new Set(e.relevant_ids),r);return{metrics:a,report:{query:e.query,mode:o,relevant_total:a.relevant_total,retrieved_relevant:a.retrieved_relevant,ndcg:$(a.ndcg),mrr:$(a.mrr),precision:$(a.precision),recall:$(a.recall)}}},_c=(e,t,r,n)=>{let o=Si(r);return{k:e,query_count:t.length,aggregate:{ndcg:$(o.ndcg),mrr:$(o.mrr),precision:$(o.precision),recall:$(o.recall)},queries:t,...n!==void 0?{fail_under:n}:{},passed:n===void 0||o.ndcg>=n}},Gf=async(e,t)=>{let r=x(process.cwd(),t.path);await L(r);let n=dc(e.k),o=lc(e.mode),i=uc(e.failUnder),s=gc(r,e.queries),a=await pc(s),l=[],d=[];for(let c of a.queries){let{report:u,metrics:f}=await yc(c,o,n,t);d.push(f),l.push(u)}return _c(n,l,d,i)};export{Hi as a,Oi as b,qc as c,Nc as d,il as e,sl as f,xt as g,_o as h,wo as i,vo as j,Ml as k,Kl as l,zl as m,ed as n,td as o,Lo as p,Oo as q,jo as r,Cs as s,Dt as t,Sd as u,Id as v,Pd as w,jt as x,qt as y,Nt as z,Ut as A,Gt as B,ia as C,Bo as D,re as E,ne as F,et as G,tt as H,ai as I,ci as J,Cf as K,wi as L,B as M,Za as N,it as O,xr as P,ac as Q,Gf as R};
6
- //# sourceMappingURL=chunk-UDNYAMCM.js.map
6
+ //# sourceMappingURL=chunk-3IB4THWX.js.map