@unbrained/pm-cli 2026.10.24 → 2026.10.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 (156) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +20 -0
  3. package/dist/cli/error-guidance.js +2 -2
  4. package/dist/cli/extension-command-help.js +2 -2
  5. package/dist/cli/register-history-activity.js +1 -1
  6. package/dist/cli-bundle/bundle-manifest.json +1 -1
  7. package/dist/cli-bundle/chunks/{chunk-R7KWBFM2.js → chunk-3CYXE6BV.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-444VPGQT.js +20 -0
  9. package/dist/cli-bundle/chunks/{chunk-YEI4N4A6.js → chunk-4GD6QOP6.js} +21 -21
  10. package/dist/cli-bundle/chunks/{chunk-HZNFNETE.js → chunk-5ZPT67NJ.js} +6 -6
  11. package/dist/cli-bundle/chunks/{chunk-KGZGXC7T.js → chunk-7C3GCLOO.js} +29 -29
  12. package/dist/cli-bundle/chunks/{chunk-3VI4XDP2.js → chunk-7T3H24HN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-MA7SNKYK.js → chunk-EYCVAAIP.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-CDR5ES7Q.js → chunk-FNZT4BTE.js} +38 -34
  15. package/dist/cli-bundle/chunks/{chunk-CNEUJHA4.js → chunk-HMJSFWHK.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-ZDVTXLA6.js → chunk-LNKPH2DD.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-Z62RXNHW.js → chunk-MVJGGCGQ.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-3S5FLCG7.js → chunk-O3ZTGRIH.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FASDGYQC.js → chunk-RD6UW3MW.js} +3 -3
  20. package/dist/cli-bundle/chunks/{chunk-UY5UHI4I.js → chunk-RLXK2S7P.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-URZB3USE.js → chunk-RQKDANP7.js} +42 -42
  22. package/dist/cli-bundle/chunks/chunk-TLMXSYJA.js +2 -0
  23. package/dist/cli-bundle/chunks/{chunk-4PNAUT2E.js → chunk-UI3FD3DW.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-VSSHB6XI.js → chunk-VAEB6IUQ.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-TZYQ4JDZ.js → chunk-XYLBOXSH.js} +6 -6
  26. package/dist/cli-bundle/chunks/{chunk-CSE47ZAN.js → chunk-YCCGZHOR.js} +2 -2
  27. package/dist/cli-bundle/chunks/{indexed-receipt-blobs-XANVELIV.js → indexed-receipt-blobs-47I6KKDO.js} +2 -2
  28. package/dist/cli-bundle/chunks/{mutation-admission-NVTBZ7DH.js → mutation-admission-747C6IUR.js} +2 -2
  29. package/dist/cli-bundle/chunks/{register-list-query-2FE6K7FQ.js → register-list-query-COST6KRV.js} +3 -3
  30. package/dist/cli-bundle/chunks/{register-mutation-KZXQUZUH.js → register-mutation-JZVVJUHY.js} +2 -2
  31. package/dist/cli-bundle/chunks/register-operations-S4LKLUBJ.js +2 -0
  32. package/dist/cli-bundle/chunks/{register-setup-P3VLCTDY.js → register-setup-3ITZXPOL.js} +2 -2
  33. package/dist/cli-bundle/chunks/{settlement-hook-YUVCO65H.js → settlement-hook-5IVCF6ZY.js} +2 -2
  34. package/dist/cli-bundle/chunks/stage-3UUIYROS.js +2 -0
  35. package/dist/cli-bundle/focused-chunks/{chunk-JYXA4JIP.js → chunk-22727JYL.js} +2 -2
  36. package/dist/cli-bundle/focused-chunks/{chunk-RVUGTIIU.js → chunk-3FM75SBJ.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-RSEGFZTY.js → chunk-3M5FZCMC.js} +54 -54
  38. package/dist/cli-bundle/focused-chunks/{chunk-BUZ2Z4P3.js → chunk-46KDJH3K.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/chunk-5LBZR6YW.js +2 -0
  40. package/dist/cli-bundle/focused-chunks/{chunk-SHUPX6G2.js → chunk-74KC7FUQ.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-77NU7NPN.js +2 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-NX7TVNUM.js → chunk-7DEZT4JN.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-ES2NGVHZ.js → chunk-B5JOVH5F.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/chunk-HMYDUEQK.js +8 -0
  45. package/dist/cli-bundle/focused-chunks/chunk-IVLIUPVV.js +12 -0
  46. package/dist/cli-bundle/focused-chunks/{chunk-X5YRJMAY.js → chunk-KIIGME23.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-IUAYTD2S.js → chunk-LWJ2X75I.js} +24 -24
  48. package/dist/cli-bundle/focused-chunks/{chunk-SBJ2IKTH.js → chunk-MT5TYMEU.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-7RQOFHMH.js → chunk-NC5HUGHU.js} +3 -3
  50. package/dist/cli-bundle/focused-chunks/chunk-NI5SG2M2.js +2 -0
  51. package/dist/cli-bundle/focused-chunks/{chunk-ZMWLV2CE.js → chunk-QH5KMIYZ.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/{chunk-POLMFGPQ.js → chunk-U6HXIF6G.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-6HJCSHBG.js → chunk-URWYYJ7K.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-5MKNVJCM.js → chunk-W7MCCFYV.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-AGCEWJ27.js → chunk-WMPDY5ZU.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-R536272H.js → chunk-Y4JHHY24.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-TAHSXKAT.js → chunk-ZYCOMRFT.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{indexed-receipt-blobs-FVOA3XMI.js → indexed-receipt-blobs-YCLN2ZZG.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{mutation-admission-PB6YFY7S.js → mutation-admission-BQBQXILV.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{settlement-hook-2VXEB6PP.js → settlement-hook-XVS6P2XI.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/stage-VSIL4MTZ.js +2 -0
  62. package/dist/cli-bundle/main.js +19 -19
  63. package/dist/cli-bundle/sdk-authoring.js +1 -1
  64. package/dist/cli-bundle/sdk-contracts.js +2 -2
  65. package/dist/cli-bundle/sdk-core.js +15 -15
  66. package/dist/cli-bundle/sdk-governance.js +1 -1
  67. package/dist/cli-bundle/sdk-graph.js +1 -1
  68. package/dist/cli-bundle/sdk-merge.js +55 -56
  69. package/dist/cli-bundle/sdk-query.js +1 -1
  70. package/dist/cli-bundle/sdk-runtime.js +1 -1
  71. package/dist/cli-bundle/sdk-testing.js +1 -1
  72. package/dist/cli-bundle/sdk.js +3 -3
  73. package/dist/core/diagnostics/remediation.js +1 -1
  74. package/dist/core/shared/errors.d.ts +13 -0
  75. package/dist/core/shared/errors.js +1 -1
  76. package/dist/core/store/settings.js +2 -2
  77. package/dist/sdk/agent/command-recovery.js +1 -1
  78. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  79. package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
  80. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  81. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  82. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  83. package/dist/sdk/cli-contracts/registration-helpers.d.ts +2 -0
  84. package/dist/sdk/cli-contracts/registration-helpers.js +2 -2
  85. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  86. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  87. package/dist/sdk/completion/fish.js +3 -1
  88. package/dist/sdk/completion/zsh.js +3 -1
  89. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  90. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  91. package/dist/sdk/governance/health-merge-evidence.d.ts +5 -0
  92. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  93. package/dist/sdk/governance/health.js +1 -1
  94. package/dist/sdk/index.d.ts +1 -1
  95. package/dist/sdk/index.js +1 -1
  96. package/dist/sdk/merge/history-scalar-rebase.d.ts +9 -0
  97. package/dist/sdk/merge/history-scalar-rebase.js +2 -0
  98. package/dist/sdk/merge/ignored-artifacts.d.ts +13 -0
  99. package/dist/sdk/merge/ignored-artifacts.js +2 -0
  100. package/dist/sdk/merge/stage.js +1 -1
  101. package/dist/sdk/merge/three-way.js +1 -1
  102. package/dist/sdk/public-surface.json +1 -1
  103. package/dist/sdk/query/activity.d.ts +14 -2
  104. package/dist/sdk/query/activity.js +1 -1
  105. package/dist/sdk/query/calendar.d.ts +16 -0
  106. package/dist/sdk/query/calendar.js +3 -3
  107. package/dist/sdk/query/context.js +2 -2
  108. package/dist/sdk/query/get.js +1 -1
  109. package/dist/sdk/query/list.js +1 -1
  110. package/dist/sdk/query/search-contracts.js +1 -1
  111. package/dist/sdk/query/window-pagination.d.ts +20 -0
  112. package/dist/sdk/query/window-pagination.js +2 -0
  113. package/dist/sdk/read-output-contracts.js +1 -1
  114. package/dist/sdk/runtime.d.ts +1 -1
  115. package/dist/sdk/runtime.js +1 -1
  116. package/dist/sdk/schema-migration.js +2 -2
  117. package/dist/sdk/templates.d.ts +7 -1
  118. package/dist/sdk/templates.js +2 -2
  119. package/docs/COMMANDS.md +19 -1
  120. package/docs/EXTENSIONS.md +1 -1
  121. package/docs/MERGE_SAFETY.md +28 -0
  122. package/docs/SDK.md +85 -6
  123. package/docs/generated/FLAG_LEXICON_BUDGETS.md +2 -2
  124. package/docs/generated/REFUSAL_CLOSURE_CENSUS.md +5 -3
  125. package/marketplace.json +1 -1
  126. package/package.json +1 -1
  127. package/packages/pm-beads/package.json +1 -1
  128. package/packages/pm-calendar/extensions/calendar/index.ts +6 -0
  129. package/packages/pm-calendar/package.json +1 -1
  130. package/packages/pm-command-kit/package.json +1 -1
  131. package/packages/pm-digital-twin/package.json +1 -1
  132. package/packages/pm-governance-audit/package.json +1 -1
  133. package/packages/pm-guide-shell/package.json +1 -1
  134. package/packages/pm-kanban/package.json +1 -1
  135. package/packages/pm-lifecycle-hooks/package.json +1 -1
  136. package/packages/pm-linked-test-adapters/package.json +1 -1
  137. package/packages/pm-search-advanced/package.json +1 -1
  138. package/packages/pm-templates/extensions/templates/runtime.ts +3 -1
  139. package/packages/pm-templates/package.json +1 -1
  140. package/packages/pm-todos/package.json +1 -1
  141. package/packages/pm-vcs/package.json +1 -1
  142. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  143. package/plugins/pm-claude/package.json +1 -1
  144. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  145. package/plugins/pm-codex/package.json +1 -1
  146. package/plugins/pm-codex/plugin.json +1 -1
  147. package/runtime-dependencies.json +1 -1
  148. package/dist/cli-bundle/chunks/chunk-VPMQEVU6.js +0 -20
  149. package/dist/cli-bundle/chunks/register-operations-BOCBWNKJ.js +0 -2
  150. package/dist/cli-bundle/chunks/stage-WRDTMCCF.js +0 -2
  151. package/dist/cli-bundle/focused-chunks/chunk-3QYTS4OY.js +0 -12
  152. package/dist/cli-bundle/focused-chunks/chunk-CEEOWDB7.js +0 -8
  153. package/dist/cli-bundle/focused-chunks/chunk-GXAXDPD4.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-NFFPNMTH.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-XTYEASIY.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/stage-MQE4PFWT.js +0 -2
@@ -1,4 +1,4 @@
1
- import{$ as _t,Ea as je,Ga as me,Oa as Et,Wa as It,bb as vt,ca as wt,cb as fe,ea as bt,m as Ae,n as ht,ua as Le,va as Pe,wa as K,x as ue,y as gt,z as q}from"./chunk-IUAYTD2S.js";import{b as se}from"./chunk-RVUGTIIU.js";import{h as yt}from"./chunk-YLVHHWHN.js";import{Aa as Re,Ba as Ne,Ca as R,Dc as G,Kd as ft,Ld as pt,Na as ct,Ra as dt,Sa as lt,Ub as ut,a as ae,ic as Y,kc as ke,lc as de,ma as nt,mc as L,na as rt,nc as De,oc as le,pc as Oe,qa as at,sc as Me,va as ce,vd as mt,wd as Fe,xa as st}from"./chunk-7RQOFHMH.js";import{A as ot,B as X,D as A,H as D,s as F,x as it,y,z as f}from"./chunk-BUZ2Z4P3.js";import di from"node:crypto";import pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Tt(e){let i=[],t=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,a=n>=97&&n<=122;if(!r&&!a){t=i.length>0;continue}t&&(i.push("-"),t=!1),i.push(o)}return i.length===0?"pm-":`${i.join("")}-`}function V(e){let i=e.trim().toLowerCase();return i.startsWith("#")&&(i=i.slice(1)),i}function J(e,i){let t=Tt(i),o=V(e);return o.startsWith(t)?o:`${t}${o}`}function li(e){let i=mt(e);if(i!==void 0)return i;let t="";for(let o=0;o<e;o+=1)t+=di.randomInt(0,36).toString(36);return t}async function ui(e,i,t){let o=[...new Set(Object.values(t))].flatMap(n=>[pe.join(e,n,`${i}.md`),pe.join(e,n,`${i}.toon`)]);return o.push(pe.join(e,"history",`${i}.jsonl`)),(await Promise.all(o.map(n=>X(n)))).some(Boolean)}var Ct=4,St=12;function mi(e){return typeof e!="number"||!Number.isFinite(e)?Ct:Math.min(St,Math.max(Ct,Math.trunc(e)))}async function Go(e,i,t={}){let o=mi(t.tokenLength),n=Math.min(o+6,St),r=0;for(;o<=n;){for(let a=0;a<32;a+=1){let s=`${Tt(i)}${li(o)}`;if(!await(t.probeExisting===!1?X(pe.join(e,"history",`${s}.jsonl`)):ui(e,s,t.typeToFolder??F)))return s;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}import xt from"node:fs/promises";import Q from"node:path";import{isUtf8 as fi}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="7db1d069-0038-57f8-8c3e-0b0ba66579ca")}catch{}})();var pi=1048576,yi=4194304;async function Rt(e,i){let t=Q.dirname(e);for(;t!==Q.parse(e).root;){let n=await xt.stat(t).catch(r=>{if(A(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new f("Workflow policy storage ancestor must be a directory.",y.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}t=Q.dirname(t)}let o=await xt.open(e,"r").catch(n=>{if(A(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(i,n)+1),a=0;for(;a<r.length;){let s=await o.read(r,a,r.length-a,a);if(s.bytesRead===0)break;a+=s.bytesRead}if(a===r.length||!fi(r.subarray(0,a)))throw new f("Workflow policy input exceeds its byte bound or is not valid UTF-8.",y.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,a)}finally{await o.close()}}function hi(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let i;try{i=JSON.parse(e)}catch{throw new f("schema/policies.json must contain valid JSON.",y.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return ct(i)}async function gi(e){return hi(await Rt(Q.join(e,"schema","policies.json"),pi))}async function _i(e,i){let t=await Rt(R(e,i),yi);if(t===null)return[];let o;try{if(o=t.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!me(o).ok)throw new Error("invalid chain")}catch{throw new f("Approval evidence requires a valid item history chain.",y.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${i} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let a=r;return typeof a.policy_fingerprint!="string"||typeof a.content_fingerprint!="string"?[]:[{policy_fingerprint:a.policy_fingerprint,content_fingerprint:a.content_fingerprint,author:n.author}]})}async function wi(e,i,t){let o=t.before?.status!==t.after?.status&&i.policies.some(a=>a.rule.kind==="approval"&&dt(a,t)),n=t.before?.id??t.after?.id,r=o&&typeof n=="string"?await _i(e,n):[];return lt(i,{...t,approvals:r})}async function $e(e){let i=await gi(e.pmRoot),t=await wi(e.pmRoot,i,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(t.allowed)return t;let o=t.decisions.filter(d=>!d.satisfied&&d.effect==="refuse");if(!e.dryRun)try{await Et({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:t.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}catch(d){let u=new f("Workflow policy refusal could not be recorded in workspace history.",y.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw u.cause=d,u}let n=o.slice(0,3).map(d=>({policy_id:d.policy_id,rule:d.rule,description:i.policies.find(u=>u.id===d.policy_id).description,missing_fields:d.missing_fields})),r=[...new Set(n.flatMap(d=>d.missing_fields))],a=n.map(d=>`${d.policy_id} (${d.rule})`).join(", "),s=o.length>3?` and ${o.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,c=r.map(d=>{if(e.before===null)return`Supply ${d} in the original ${e.operation} request, then retry; the item was not created.`;let u=nt("update",d);return u===void 0?`Supply ${d} using its declared SDK or package mutation contract, then retry.`:G(["update",l,rt("update",u),`<${d}>`,"--pm-path",Q.resolve(e.pmRoot)])});throw new f(`Workflow policy refused ${e.operation}: ${a}${s}.${r.length?` Missing: ${r.join(", ")}.`:""}`,y.CONFLICT,{code:"workflow_policy_refused",reason:n.map(d=>d.policy_id).join(","),policy_violations:n,policy_violation_count:o.length,required:r.length?`Supply missing fields: ${r.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(d=>d.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:r},nextSteps:[...c,...new Set(o.slice(0,3).filter(d=>d.missing_fields.length===0).map(d=>d.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as bi}from"node:async_hooks";import{channel as Ei}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var He=new bi,We=Ei("@unbrained/pm-cli/item-metadata-enumeration/v1");function ye(e){We.publish(e)}async function un(e){let i={enumeration_calls:0,metadata_rows:0},t=o=>{He.getStore()?.includes(i)&&(i.enumeration_calls+=1,i.metadata_rows+=o)};We.subscribe(t);try{return{result:await He.run([...He.getStore()??[],i],e),work:{...i}}}finally{We.unsubscribe(t)}}import P from"node:fs/promises";import kt from"node:path";import{randomUUID as Ii}from"node:crypto";import{createRequire as vi}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ci="metadata-query-index.sqlite",Z="5",Ue;function ee(){return Ue!==void 0||(Ue=bt(process.versions.node,vi(import.meta.url))),Ue}function Nt(e,i){return Math.max(0,Math.floor(e===void 0?i:e))}function W(e){return kt.join(e,"runtime",Ci)}function Ti(e){e.exec(`
1
+ import{$ as _t,Ea as je,Ga as me,Oa as Et,Wa as It,bb as vt,ca as wt,cb as fe,ea as bt,m as Ae,n as ht,ua as Le,va as Pe,wa as K,x as ue,y as gt,z as q}from"./chunk-LWJ2X75I.js";import{b as se}from"./chunk-3FM75SBJ.js";import{h as yt}from"./chunk-YLVHHWHN.js";import{Aa as Re,Ba as Ne,Ca as R,Dc as G,Kd as ft,Ld as pt,Na as ct,Ra as dt,Sa as lt,Ub as ut,a as ae,ic as Y,kc as ke,lc as de,ma as nt,mc as L,na as rt,nc as De,oc as le,pc as Oe,qa as at,sc as Me,va as ce,vd as mt,wd as Fe,xa as st}from"./chunk-NC5HUGHU.js";import{A as ot,B as X,D as A,H as D,s as F,x as it,y,z as f}from"./chunk-46KDJH3K.js";import di from"node:crypto";import pe from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function Tt(e){let i=[],t=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,a=n>=97&&n<=122;if(!r&&!a){t=i.length>0;continue}t&&(i.push("-"),t=!1),i.push(o)}return i.length===0?"pm-":`${i.join("")}-`}function V(e){let i=e.trim().toLowerCase();return i.startsWith("#")&&(i=i.slice(1)),i}function J(e,i){let t=Tt(i),o=V(e);return o.startsWith(t)?o:`${t}${o}`}function li(e){let i=mt(e);if(i!==void 0)return i;let t="";for(let o=0;o<e;o+=1)t+=di.randomInt(0,36).toString(36);return t}async function ui(e,i,t){let o=[...new Set(Object.values(t))].flatMap(n=>[pe.join(e,n,`${i}.md`),pe.join(e,n,`${i}.toon`)]);return o.push(pe.join(e,"history",`${i}.jsonl`)),(await Promise.all(o.map(n=>X(n)))).some(Boolean)}var Ct=4,St=12;function mi(e){return typeof e!="number"||!Number.isFinite(e)?Ct:Math.min(St,Math.max(Ct,Math.trunc(e)))}async function Go(e,i,t={}){let o=mi(t.tokenLength),n=Math.min(o+6,St),r=0;for(;o<=n;){for(let a=0;a<32;a+=1){let s=`${Tt(i)}${li(o)}`;if(!await(t.probeExisting===!1?X(pe.join(e,"history",`${s}.jsonl`)):ui(e,s,t.typeToFolder??F)))return s;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}import xt from"node:fs/promises";import Q from"node:path";import{isUtf8 as fi}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="7db1d069-0038-57f8-8c3e-0b0ba66579ca")}catch{}})();var pi=1048576,yi=4194304;async function Rt(e,i){let t=Q.dirname(e);for(;t!==Q.parse(e).root;){let n=await xt.stat(t).catch(r=>{if(A(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new f("Workflow policy storage ancestor must be a directory.",y.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}t=Q.dirname(t)}let o=await xt.open(e,"r").catch(n=>{if(A(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(i,n)+1),a=0;for(;a<r.length;){let s=await o.read(r,a,r.length-a,a);if(s.bytesRead===0)break;a+=s.bytesRead}if(a===r.length||!fi(r.subarray(0,a)))throw new f("Workflow policy input exceeds its byte bound or is not valid UTF-8.",y.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,a)}finally{await o.close()}}function hi(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let i;try{i=JSON.parse(e)}catch{throw new f("schema/policies.json must contain valid JSON.",y.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return ct(i)}async function gi(e){return hi(await Rt(Q.join(e,"schema","policies.json"),pi))}async function _i(e,i){let t=await Rt(R(e,i),yi);if(t===null)return[];let o;try{if(o=t.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!me(o).ok)throw new Error("invalid chain")}catch{throw new f("Approval evidence requires a valid item history chain.",y.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${i} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let a=r;return typeof a.policy_fingerprint!="string"||typeof a.content_fingerprint!="string"?[]:[{policy_fingerprint:a.policy_fingerprint,content_fingerprint:a.content_fingerprint,author:n.author}]})}async function wi(e,i,t){let o=t.before?.status!==t.after?.status&&i.policies.some(a=>a.rule.kind==="approval"&&dt(a,t)),n=t.before?.id??t.after?.id,r=o&&typeof n=="string"?await _i(e,n):[];return lt(i,{...t,approvals:r})}async function $e(e){let i=await gi(e.pmRoot),t=await wi(e.pmRoot,i,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(t.allowed)return t;let o=t.decisions.filter(d=>!d.satisfied&&d.effect==="refuse");if(!e.dryRun)try{await Et({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:t.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}catch(d){let u=new f("Workflow policy refusal could not be recorded in workspace history.",y.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw u.cause=d,u}let n=o.slice(0,3).map(d=>({policy_id:d.policy_id,rule:d.rule,description:i.policies.find(u=>u.id===d.policy_id).description,missing_fields:d.missing_fields})),r=[...new Set(n.flatMap(d=>d.missing_fields))],a=n.map(d=>`${d.policy_id} (${d.rule})`).join(", "),s=o.length>3?` and ${o.length-3} more`:"",l=e.after?.metadata.id??e.before.metadata.id,c=r.map(d=>{if(e.before===null)return`Supply ${d} in the original ${e.operation} request, then retry; the item was not created.`;let u=nt("update",d);return u===void 0?`Supply ${d} using its declared SDK or package mutation contract, then retry.`:G(["update",l,rt("update",u),`<${d}>`,"--pm-path",Q.resolve(e.pmRoot)])});throw new f(`Workflow policy refused ${e.operation}: ${a}${s}.${r.length?` Missing: ${r.join(", ")}.`:""}`,y.CONFLICT,{code:"workflow_policy_refused",reason:n.map(d=>d.policy_id).join(","),policy_violations:n,policy_violation_count:o.length,required:r.length?`Supply missing fields: ${r.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:n.map(d=>d.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:r},nextSteps:[...c,...new Set(o.slice(0,3).filter(d=>d.missing_fields.length===0).map(d=>d.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as bi}from"node:async_hooks";import{channel as Ei}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var He=new bi,We=Ei("@unbrained/pm-cli/item-metadata-enumeration/v1");function ye(e){We.publish(e)}async function un(e){let i={enumeration_calls:0,metadata_rows:0},t=o=>{He.getStore()?.includes(i)&&(i.enumeration_calls+=1,i.metadata_rows+=o)};We.subscribe(t);try{return{result:await He.run([...He.getStore()??[],i],e),work:{...i}}}finally{We.unsubscribe(t)}}import P from"node:fs/promises";import kt from"node:path";import{randomUUID as Ii}from"node:crypto";import{createRequire as vi}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ci="metadata-query-index.sqlite",Z="5",Ue;function ee(){return Ue!==void 0||(Ue=bt(process.versions.node,vi(import.meta.url))),Ue}function Nt(e,i){return Math.max(0,Math.floor(e===void 0?i:e))}function W(e){return kt.join(e,"runtime",Ci)}function Ti(e){e.exec(`
2
2
  PRAGMA foreign_keys = ON;
3
3
  PRAGMA journal_mode = OFF;
4
4
  PRAGMA synchronous = OFF;
@@ -88,4 +88,4 @@ import{$ as _t,Ea as je,Ga as me,Oa as Et,Wa as It,bb as vt,ca as wt,cb as fe,ea
88
88
  WHERE item_search MATCH ?
89
89
  ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
90
90
  LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(r=>JSON.parse(String(r.metadata_json)));return t.close(),{source_cursor:o.source_cursor,items:n}}catch{return t?.close(),null}}async function we(e){await P.rm(W(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as xi,randomUUID as jt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var x=8,$t=500,Ri="metadata-derived-index",Ni="metadata-cache.json",ki="metadata-cache-bodies.json",Di="metadata-cache-collections.json",Oi="metadata-cache-delta.json",Mi="metadata-cache-manifest.json",Ft=4,Fi=["comments","notes","learnings","files","tests","test_runs","docs"];function Ht(){return se(Y())}function Ee(e){let i={...e},t={};for(let o of Fi)o in i&&(t[o]=i[o],delete i[o]);return{light:i,heavy:t}}function Wt(e,i){return!i||Object.keys(i).length===0?e:{...e,...i}}function Ut(e,i,t,o){let n=xi("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(i).sort(([a],[s])=>a.localeCompare(s)).map(([a,s])=>`${a}=${s}`).join(",");return n.update(`|types:${r}`),t&&n.update(`|schema:${JSON.stringify(t)}`),o.length>0&&n.update(`|extension_fields:${o.join(",")}`),n.digest("hex").slice(0,16)}function Ie(e){return w.join(e,"runtime",Ni)}function ve(e){return w.join(e,"runtime",ki)}function Ce(e){return w.join(e,"runtime",Di)}function ze(e){return w.join(e,"runtime",Oi)}function Xe(e){return w.join(e,"runtime",Mi)}function Te(e,i){let t=w.extname(e);return`${e.slice(0,-t.length)}.${i}${t}`}var Ai=24,v=new Map,Se=new WeakMap;function Ye(e){return Se.get(e)??e.source_cursor}function Li(e,i){let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.entry?e.entries[o]=n.entry:delete e.entries[o];e.directory_signatures=i.directory_signatures,e.source_cursor=i.source_cursor}}function Pi(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.body?e.bodies[o]=n.body:delete e.bodies[o];e.source_cursor=i.source_cursor}}function ji(e,i){if(!e)return;let t=Ye(e);if(!(i.base_source_cursor!==t||e.source_cursor===i.source_cursor)){Se.set(e,t);for(let[o,n]of Object.entries(i.changes))n.collections?e.collections[o]=n.collections:delete e.collections[o];e.source_cursor=i.source_cursor}}function $i(e,i,t,o){!e||!o||e.context_fingerprint!==o.context_fingerprint||(Li(e,o),Pi(i,o),ji(t,o))}function Be(e,i){v.size>=Ai&&!v.has(e)&&ut(v),v.set(e,i)}async function O(e,i){let t;try{t=await E.stat(e)}catch{return v.delete(e),null}let o=v.get(e);if(o&&te(o.signature,t.mtimeMs,t.ctimeMs,t.size))return v.delete(e),v.set(e,o),o.envelope;let n;try{n=i(await E.readFile(e,"utf8"))}catch{n=null}return Be(e,{signature:{mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size},envelope:n}),n}async function Hi(e,i,t){let o=s=>{let l=JSON.parse(s);return l.version!==x||typeof l.source_cursor!="string"||typeof l.entries!="object"||l.entries===null?null:l},n=Ie(e),r=await O(n,o);if(!i||r===null||r.context_fingerprint===i)return r;let a=await O(Te(n,i),o);return a===null&&ne(t,`metadata_cache_context_changed:${r.context_fingerprint}->${i}`),a}async function Wi(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.bodies!="object"||a.bodies===null?null:a},o=ve(e),n=await O(o,t);return i&&n?.context_fingerprint!==i?await O(Te(o,i),t):n}async function Ui(e,i){let t=r=>{let a=JSON.parse(r);return a.version!==x||typeof a.source_cursor!="string"||typeof a.collections!="object"||a.collections===null?null:a},o=Ce(e),n=await O(o,t);return i&&n?.context_fingerprint!==i?await O(Te(o,i),t):n}async function Ge(e){let i=ze(e),t=await O(i,o=>{let n=JSON.parse(o);return n.version!==x||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(t)return{envelope:t,invalid:!1};try{return await E.stat(i),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function qe(e){let i=Xe(e),t=await O(i,o=>{let n=JSON.parse(o);return n.version!==x||typeof n.context_fingerprint!="string"||typeof n.source_cursor!="string"||!Number.isInteger(n.entry_count)||n.entry_count<0||typeof n.directory_signatures!="object"||n.directory_signatures===null?null:n});if(t)return t;try{await E.stat(i),await U(e)}catch{}return null}async function ie(e,i){await E.mkdir(w.dirname(e),{recursive:!0}),await D(e,JSON.stringify(i));try{let o=await E.stat(e);Be(e,{signature:{mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size},envelope:i})}catch{v.delete(e)}let t=w.dirname(w.dirname(e));if(e===Ie(t)||e===ve(t)||e===Ce(t)){let o=Te(e,i.context_fingerprint);await D(o,JSON.stringify(i));try{let l=await E.stat(o);Be(o,{signature:{mtime_ms:l.mtimeMs,ctime_ms:l.ctimeMs,size:l.size},envelope:i})}catch{v.delete(o)}let n=w.dirname(e),r=w.extname(e),a=w.basename(e,r),s=(await E.readdir(n,{withFileTypes:!0}).catch(()=>[])).filter(l=>l.isFile()&&l.name!==w.basename(e)&&l.name.startsWith(`${a}.`)&&l.name.endsWith(r)).map(l=>w.join(n,l.name));if(s.length>Ft){let l=(await Promise.all(s.map(async c=>{try{return{path:c,mtime:(await E.stat(c)).mtimeMs}}catch{return null}}))).filter(c=>c!==null);for(let c of l.sort((d,u)=>d.mtime-u.mtime).slice(0,Math.max(0,l.length-Ft)))await E.rm(c.path,{force:!0}),v.delete(c.path)}}}function Bi(e,i,t){return t?i===t&&e!==t:i==="toon"&&e!=="toon"}function Bt(e,i,t){return e===void 0||Bi(e,i,t)}function ne(e,i){e&&!e.includes(i)&&e.push(i)}function te(e,i,t,o){return e.mtime_ms===i&&e.ctime_ms===t&&e.size===o}async function zi(e,i,t){let o=w.join(e,i);try{let n=await E.readdir(o);return{folder:i,dirPath:o,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!A(n)&&ne(t,`item_list_directory_read_failed:${i}`),{folder:i,dirPath:o,files:[]}}}async function Xi(e,i){try{let t=await E.stat(w.join(e,i));return[i,{exists:!0,mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size}]}catch{return[i,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function be(e,i){return Object.fromEntries(await Promise.all(i.map(async t=>await Xi(e,t))))}function oe(e,i){return!e||Object.keys(e).length!==Object.keys(i).length?!1:Object.entries(i).every(([t,o])=>{let n=e[t];return n!==void 0&&n.exists===o.exists&&te(n,o.mtime_ms,o.ctime_ms,o.size)})}function Yi(e){return ce.some(i=>e.toLowerCase().endsWith(i))}function Gi(e,i,t,o,n,r){o||(e.metadata=!0),i&&!n&&(e.body=!0),t&&!r&&(e.collections=!0)}async function qi(e,i,t){if(t)for(let o of await le({path:e,scope:"project"}))ne(i,o)}function At(e,i,t,o){if(e)return i&&t?t.collections:o}async function Ki(e,i,t){let o=await E.stat(e),n=o.mtimeMs,r=o.ctimeMs,{size:a}=o,s=Ne(e);await qi(e,t.warnings,t.dispatchReadHooks);let l=t.previousEntries[i],c=!t.forceSourceRead&&l!==void 0&&te(l,n,r,a),d=t.previousBodies[i],u=!t.forceSourceRead&&d!==void 0&&te(d,n,r,a),p=t.previousCollections[i],h=!t.forceSourceRead&&p!==void 0&&te(p,n,r,a);if(!(!c||t.includeBody&&!u||t.includeCollections&&!h))return{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:l.metadata,heavyMetadata:At(t.includeCollections,h,p,void 0),bodyLength:l.body_length,body:t.includeBody?d.body:void 0};let m=await E.readFile(e,"utf8"),_=ue(m,{format:s,schema:t.schema,extensionFieldNames:t.extensionFieldNames,onWarning:b=>ne(t.warnings,b)}),g=Ee(_.metadata);return Gi(t.state.misses,t.includeBody,t.includeCollections,c,u,h),{mtimeMs:n,ctimeMs:r,size:a,itemFormat:s,lightMetadata:c?l.metadata:g.light,heavyMetadata:At(t.includeCollections,h,p,g.heavy),bodyLength:c?l.body_length:_.body.length,body:t.includeBody?_.body:void 0}}function Vi(e,i,t,o){t.state.newEntries[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,metadata:o.lightMetadata,body_length:o.bodyLength},t.includeBody&&o.body!==void 0&&(t.state.newBodies[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,body:o.body}),t.includeCollections&&o.heavyMetadata!==void 0&&(t.state.newCollections[i]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,collections:o.heavyMetadata});let n=t.includeCollections?Wt(o.lightMetadata,o.heavyMetadata):o.lightMetadata,r=t.state.documentsById.get(n.id),a={metadata:n,body:o.body,item_format:o.itemFormat,item_path:e};Bt(r?.itemFormat,o.itemFormat,t.preferredFormat)&&t.state.documentsById.set(n.id,{candidate:a,itemFormat:o.itemFormat})}async function Ji(e,i,t,o){try{let n=await Ki(i,t,o);Vi(i,t,o,n)}catch{ne(o.warnings,`item_list_item_read_failed:${e}/${w.basename(i)}`)}}function Qi(e,i){return e&&e.context_fingerprint===i?e.entries:{}}function Zi(e,i){return e&&e.context_fingerprint===i?e.bodies:{}}function eo(e,i){return e&&e.context_fingerprint===i?e.collections:{}}function to(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function io(e,i){let t=[];for(let{folder:o,dirPath:n,files:r}of e)for(let a of r){if(!Yi(a))continue;let s=w.join(n,a),l=w.relative(i.pmRoot,s);t.push(Ji(o,s,l,i)),t.length===32&&(await Promise.all(t),t.length=0)}await Promise.all(t)}async function oo(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!oe(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await ie(Ie(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await ie(Xe(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let i=[...e.state.documentsById.values()].map(({candidate:t})=>({relativePath:w.relative(e.pmRoot,t.item_path),metadata:Ee(t.metadata).light,linkedFiles:t.metadata.files??[]}));i.length>=e.minimumIndexedItems?await Ot({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:i}):await we(e.pmRoot)}catch{}}async function no(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await ie(ve(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function ro(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await ie(Ce(e.pmRoot),{version:x,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function Ke(e,i,t={}){let o=await qe(e);return t.required!==!0&&(o===null||o.entry_count<$t)?async()=>{}:ft(e,Ri,30,i,!1,!1,3e3)}async function Fn(e,i){let t=await qe(e);if(t===null)return null;let o=await Ge(e);if(o.invalid)return await U(e),null;let n=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.source_cursor:t.source_cursor,r=o.envelope?.context_fingerprint===t.context_fingerprint&&o.envelope.base_source_cursor===t.source_cursor?o.envelope.directory_signatures:t.directory_signatures;return i&&!oe(r,await be(e,i))?null:{source_cursor:n,entry_count:t.entry_count}}function Lt(e,i){let t=w.relative(e,i);return t===""||t===".."||t.startsWith(`..${w.sep}`)||w.isAbsolute(t)?null:t}async function U(e){await Promise.all([Ie(e),ve(e),Ce(e),ze(e),Xe(e)].map(async i=>{await E.rm(i,{force:!0}),v.delete(i)})),await we(e)}async function ao(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let i=await E.stat(e.mutation.itemPath),t=Ee(e.mutation.document.metadata),o={mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size};return{entry:{...o,metadata:t.light,body_length:e.mutation.document.body.length},body:{...o,body:e.mutation.document.body},collections:{...o,collections:t.heavy}}}function so(e,i,t){return e?.context_fingerprint===i&&e.base_source_cursor===t?structuredClone(e.changes):{}}async function Ve(e){let i=Lt(e.pmRoot,e.itemPath),t=e.previousItemPath?Lt(e.pmRoot,e.previousItemPath):void 0;if(i===null||t===null)return await U(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let o=Ut(e.preferredFormat,e.typeToFolder,e.schema,Ht()),n=await qe(e.pmRoot);if(n===null||n.context_fingerprint!==o)return[];let r=n.source_cursor,a=await Ge(e.pmRoot);if(a.invalid)return await U(e.pmRoot),["metadata_derived_index_refresh_failed"];let s=so(a.envelope,o,r),l=a.envelope?.context_fingerprint===o&&a.envelope.base_source_cursor===r?a.envelope.source_cursor:r;t!==void 0&&(s[t]={entry:null,body:null,collections:null}),s[i]=await ao({mutation:e});let c=jt();return await ie(ze(e.pmRoot),{version:x,context_fingerprint:o,base_source_cursor:r,source_cursor:c,directory_signatures:await be(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:s}),await Mt({pmRoot:e.pmRoot,contextFingerprint:o,expectedSourceCursor:l,sourceCursor:c,row:e.document===null?null:{relativePath:i,metadata:Ee(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...t===void 0?[]:[t],...e.document===null?[i]:[]]})||await we(e.pmRoot),[]}catch{return await U(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function co(e){return[...e.documentsById.values()].sort((i,t)=>i.candidate.metadata.id.localeCompare(t.candidate.metadata.id)).map(i=>i.candidate)}function Pt(e,i,t){return e?.context_fingerprint===i&&e.source_cursor===t}function lo(e,i,t,o,n){return e.every(r=>(!i||o[r]!==void 0)&&(!t||n[r]!==void 0))}function uo(e){let i=new Map;for(let[t,o]of Object.entries(e.previousEntries)){let n=Ne(t);if(!n)continue;let r=e.includeCollections?Wt(o.metadata,e.previousCollections[t]?.collections):o.metadata,a=i.get(r.id);Bt(a?.itemFormat,n,e.preferredFormat)&&i.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[t]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,t)}})}return[...i.values()].sort((t,o)=>t.candidate.metadata.id.localeCompare(o.candidate.metadata.id)).map(t=>t.candidate)}function mo(e){return e.forceSourceScan||Oe()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!oe(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||Pt(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||Pt(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&lo(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function xe(e,i,t,o,n,r={}){let a=r.includeBody!==!1,s=r.includeCollections!==!1,l=Ht(),c=Ut(i,t,n,l),d=await Ge(e);d.invalid&&await U(e);let u=await Hi(e,c,r.cacheDiagnostics),p=a?await Wi(e,c):null,h=s?await Ui(e,c):null;$i(u,p,h,d.envelope);let m=Qi(u,c),_=Zi(p,c),g=eo(h,c),b=[...new Set(Object.values(t))],T=await be(e,b),$=Object.keys(m),N=Math.max(1,Math.floor(r.derivedIndexMinimumItems??$t));if(mo({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:c,existingCache:u,existingBodyCache:p,existingCollectionsCache:h,directorySignatures:T,entryKeys:$,minimumIndexedItems:N,includeBody:a,includeCollections:s,previousBodies:_,previousCollections:g}))return uo({pmRoot:e,preferredFormat:i,includeBody:a,includeCollections:s,previousEntries:m,previousBodies:_,previousCollections:g});let I=await Promise.all(b.map(H=>zi(e,H,o))),M=Oe(),C=to(),B={pmRoot:e,preferredFormat:i,warnings:o,schema:n,extensionFieldNames:l,includeBody:a,includeCollections:s,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:M,previousEntries:m,previousBodies:_,previousCollections:g,state:C};await io(I,B);let k=await be(e,b),S=oe(T,k)?k:{},z=C.misses.metadata||Object.keys(m).length!==Object.keys(C.newEntries).length||!oe(u?.directory_signatures,S)||u===null?jt():u.source_cursor;return await oo({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCache:u,previousEntries:m,directorySignatures:S,state:C,minimumIndexedItems:N}),a&&await no({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingBodyCache:p,previousBodies:_,state:C}),s&&await ro({pmRoot:e,contextFingerprint:c,sourceCursor:z,existingCollectionsCache:h,previousCollections:g,state:C}),co(C)}async function zt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function Xt(e,i,t,o,n){return(await xe(e,i,t,o,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function fo(e,i){let t=e.trim().toLowerCase();if(t.length===0)return;let o=Math.floor(t.length/3);return i.map(n=>({candidate:n,distance:ae(t,n.toLowerCase(),o)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function Yt(e){return["pm",...e].map(i=>/^[A-Za-z0-9_./:@=-]+$/u.test(i)?i:JSON.stringify(i)).join(" ")}function $n(e){let i=e.command_path.trim().replaceAll(/\s+/gu," "),t=e.token.trim(),o=t.length===0?"<empty>":t,n=[...new Set(e.allowed.map(p=>p.trim()))].filter(Boolean).sort((p,h)=>p.localeCompare(h));if(i.length===0||o.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=i.split(" "),a=e.trailing_args??[],s=e.display_name??`pm ${i}`,l=e.token_kind??"subcommand",c=e.retry_command?void 0:fo(o,n),d=Yt([...r,o,...a]),u=e.retry_command??(c?Yt([...r,c,...a]):void 0);return new f(`Unknown ${s} ${l} "${o}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??y.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:o,examples:[...u?[u]:[],...e.examples??[],`pm ${i} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:d,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}import po from"node:fs/promises";import yo from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="1d746e4d-ff6c-54ec-a94f-4ec4cb8f77b5")}catch{}})();function ho(e){return[...new Set(e.filter(i=>i.trim().length>0))].sort((i,t)=>i.localeCompare(t))}function go(e,i){return new f(`Missing history stream for ${e}. ${i} requires history streams when settings.history.missing_stream is strict_error.`,y.NOT_FOUND)}async function _o(e,i){return await ot(yo.dirname(e)),await(await po.open(e,"a")).close(),L({path:e,scope:"project",op:`${i}:history:auto_create`})}async function Je(e){return wo({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function wo(e){let i=ho(e.itemIds),t=[],o=[];for(let n of i){let r=R(e.pmRoot,n);if(!await X(r)){if(e.settings.history.missing_stream==="strict_error")throw go(n,e.commandLabel);o.push(...await _o(r,e.commandLabel)),o.push(`history_stream_auto_created:${n}`),t.push(n)}}return{auto_created_ids:t,warnings:o}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function re(e,i=!1){let t=e[0];if(t?.op!=="history_compact_baseline")return 0;let o=t.context?.history_compaction,n=typeof o=="object"&&o!==null&&"version_offset"in o?o.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(i)return null;throw new f("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",y.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="ddc5bb8f-83bc-5121-a628-a501e7ed5a73")}catch{}})();function bo(e,i){let t=-1;return e.forEach((o,n)=>{let r=Date.parse(o.ts);if(!Number.isFinite(r))throw new f(`History for this item contains invalid timestamp at entry ${n+1}.`,y.GENERIC_FAILURE);r<=i&&(t=n)}),t}function Eo(e,i){let t=e[0]?.ts??null,o=e.at(-1)?.ts??null,n={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:t,last_timestamp:o}};return o!==null&&(n.examples=[o],i!==null&&(n.examples.unshift(String(i+1),String(i+e.length)),n.valid_range.first_version=i+1,n.valid_range.last_version=i+e.length)),{guidance:n,lastTimestamp:o}}function Io(e,i){let t={};if(i instanceof Error&&i.message.trim().length>0&&(t.reason=i.message.trim()),typeof i!="object"||i===null)return t;let o=i;if(typeof o.index=="number"&&Number.isInteger(o.index)&&o.index>=0&&(t.patchIndex=o.index),typeof o.operation=="object"&&o.operation!==null){let n=o.operation;Object.assign(t,Object.fromEntries(["op","path","from"].flatMap(r=>{let a=n[r];return typeof a=="string"?[[r,a]]:[]})))}if(t.patchIndex!==void 0){let n=e[t.patchIndex];n&&(t.op??=n.op,t.path??=n.path,t.from??=n.from)}return t}function Gt(e,i,t={}){let o=e.trim(),n=t.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:a,lastTimestamp:s}=Eo(i,re(i,!0));if(!o)throw new f(`Missing ${n} target. Use a timestamp or version number.`,y.USAGE,a);if(/^\d+$/.test(o)){let d=re(i),u=Number(o);if(u>=1&&u<=d)throw new f(`History version ${u} was pruned by compaction.`,y.USAGE,{...a,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>d+i.length)throw new f(`${r} version must be between ${d+1} and ${d+i.length} for this item.`,y.USAGE,a);return{kind:"version",raw:o,historyIndex:u-d-1}}let l=Date.parse(o);if(!Number.isFinite(l))throw new f(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,y.USAGE,a);let c=bo(i,l);if(c<0||t.allowFutureTimestamp!==!0&&l>Date.parse(s))throw new f(n==="restore"?`No history entries exist at or before timestamp ${o}.`:`No history entry exists at timestamp ${o}.`,y.USAGE,a);return{kind:"timestamp",raw:o,historyIndex:c}}function Qe(e,i,t,o){let n=je(e,i);if(n.ok)return n.document;let r=Io(i,n.error),a=[`history_op=${o}`,r.patchIndex===void 0?null:`patch_index=${r.patchIndex}`,r.op?`op=${r.op}`:null,r.path?`path=${r.path}`:null,r.from?`from=${r.from}`:null].filter(s=>s!==null);throw new f(`Failed to apply history patch at entry ${t} (${a.join(", ")}). ${r.reason??String(n.error)}`,y.GENERIC_FAILURE)}function qt(e,i){let t=e[0];if(t&&t.op!=="create"&&t.op!=="history_compact_baseline"){let a=je(K,t.patch);if(!a.ok||typeof a.document.metadata.id!="string")throw new f("History starts without a reconstructable item baseline.",y.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let o=e.slice(0,i+1),n=me([...o]),r=structuredClone(K);for(let a=0;a<=i;a+=1){let s=e[a];if(!s)throw new f(`History target entry ${a+1} does not exist.`,y.USAGE);r=Qe(r,s.patch,a+1,s.op)}if(!n.ok)throw new f(`History cannot be replayed: ${n.errors.join(", ")}.`,y.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:n.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return r}function ir(e,i){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new f("History has no complete item baseline for this target.",y.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new f(`History target ${i.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,y.USAGE)}import j from"node:fs/promises";import{statSync as vo}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Co(e,i){let t=-1,o=structuredClone(K);for(let[s,l]of e.entries()){if(o=Qe(o,l.patch,s+1,l.op),o.metadata.id!==void 0&&o.metadata.id!==i)throw new f(`History belongs to item ${String(o.metadata.id)}, expected ${i}.`,y.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===i&&Array.isArray(o.metadata.tags)&&(t=s)}let n=re(e,!0),r=t<0||n===null?null:n+t+1,a=r===null?void 0:String(r);if(t>=0&&a===void 0){let s=e[t].ts;Gt(s,e).historyIndex===t&&(a=s)}return{version:r,target:a}}async function Kt(e,i,t){let o=new Set([J(i,t),V(i)]);for(let n of o){let r=R(e,n);if(!vo(r,{throwIfNoEntry:!1})?.isFile())continue;let a=await wt(r,n),s=-1;if(a.forEach((h,m)=>{h.op==="delete"&&(s=m)}),s<0)continue;let l=qt(a,a.length-1);if(Object.keys(l.metadata).length!==0)continue;let{version:c,target:d}=Co(a,n),u=d===void 0?["history",n,"--verify"]:["get",n,"--at",d],p=G(u);return new f(`Item ${n} was deleted at ${a[s].ts}; its history is retained.`,y.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:n,tombstone:{deleted:!0,deleted_at:a[s].ts,recoverable:d!==void 0,last_materialized_version:c},nextSteps:[p,...d===void 0?["Recover the pre-compaction history from version control."]:[G(["restore",n,d])]],recovery:{suggested_retry:p,suggested_retry_args:u}})}}import{AsyncLocalStorage as To}from"node:async_hooks";import So from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="53df109f-bd64-5879-96a6-39f70334910e")}catch{}})();var xo=new To;function Vt(e,i){for(let t of xo.getStore()??[])t.pmRoot===So.resolve(e)&&t.id===i.metadata.id&&t.validate(i)}import{AsyncLocalStorage as Ro}from"node:async_hooks";import Jt from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();var Qt=new Ro;function br(e,i){return Qt.run({...e,pmRoot:Jt.resolve(e.pmRoot)},i)}function Zt(e,i){let t=Qt.getStore();return t?.pmRoot===Jt.resolve(e)&&t.itemId===i?{bulk_checkpoint:t.checkpointId}:void 0}import Ze from"node:path";import{isUtf8 as No}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},i=new e.Error().stack;i&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[i]="3a19f8b4-d2d8-5133-b320-281980d64da6")}catch{}})();async function ko(e){try{return await j.access(e),!0}catch{return!1}}function Do(e,i){e&&(e.includes(i)||e.push(i))}function ei(e){return e??se(Y())}function Oo(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function ti(e,i,t="pm-",o,n=F){let r=i.trim(),a=r.startsWith("#")?r.slice(1):r;if(a.length===0)return null;let s=J(i,t),l=V(i),c=[...new Set([a,s,l])].filter(p=>p.length>0),d=Object.entries(n),u=Oo(o);for(let p of c){let h=new Map;for(let[m]of d)for(let _ of u){let g=Re(e,m,p,_,n);await ko(g)&&h.set(g,h.get(g)??{id:p,type:m,itemPath:g,item_format:_})}if(h.size>1){let m=[...h.keys()].map(_=>Ze.relative(e,_).split(Ze.sep).join("/")).sort();throw new f(`Item ${p} has ambiguous identity across ${m.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,y.CONFLICT,{code:"item_identity_ambiguous",item_id:p,paths:m})}for(let m of h.values())return m}return null}async function ii(e,i={}){let t=await Mo(e,i);if(t.error!==null)throw t.error;return{raw:t.raw,document:t.document}}async function Mo(e,i={}){let t=await j.readFile(e.itemPath);if(!No(t))throw new f("Item contains invalid UTF-8; preserve a binary backup before recovering it.",y.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:!1});let o=t.toString("utf8");await le({path:e.itemPath,scope:"project"});let n;try{n=ue(o,{format:e.item_format,requireSupportedFormat:!0,schema:i.schema,extensionFieldNames:ei(i.extensionFieldNames),onWarning:r=>Do(i.warnings,r)})}catch(r){if(r instanceof f&&r.code==="item_format_version_unsupported")throw new f(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof f&&r.code==="item_document_invalid")return{raw:o,document:null,error:new f(`Cannot read ${e.id} at ${e.itemPath}${t.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:t.length,empty:t.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw r}return{raw:o,document:n,error:null}}async function Fo(e,i,t=F,o,n){await fe(e);let r=await zt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Jr(e,i,t=F,o,n){await fe(e);let r=await Xt(e,i,t,o,n);return ye(r.length),r.map(a=>a.metadata)}async function Qr(e,i,t=F,o,n,r={}){await fe(e);let a=await xe(e,i,t,o,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return ye(a.length),a.map(s=>({...s.metadata,body:s.body}))}function oi(e){return{async get(i){let t=await ti(e.pmRoot,i,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return null;let{document:o}=await ii(t,{schema:e.settings.schema});return{item:o.metadata,body:o.body}},list:()=>Fo(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Ao(e,i){let t=new Set(Object.values(i)),o=[];return await Promise.all([...t].map(async n=>{try{let r=await j.readdir(Ze.join(e,n));for(let a of r)for(let s of ce)if(a.toLowerCase().endsWith(s)){o.push(a.slice(0,-s.length));break}}catch{}})),o}async function Lo(e,i,t,o){let n=J(i,t),r=await Ao(e,o);if(r.length===0)return[];let a=Math.max(3,Math.floor(n.length/2));return r.map(s=>({id:s,distance:ae(s,n,a)})).filter(s=>s.distance!==null).sort((s,l)=>s.distance-l.distance).slice(0,3).map(s=>s.id)}async function Po(e,i,t,o){let n=await Kt(e,i,t);if(n)return n;let r=await Lo(e,i,t,o),a=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return r.length>0&&a.unshift(`Did you mean one of: ${r.join(", ")}?`),new f(`Item ${i} not found`,y.NOT_FOUND,{nextSteps:a})}function jo(e,i){return e==="claim"||i===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function ni(e){let i=e.typeToFolder??at(e.settings,Y()).type_to_folder,t=await ti(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,i);if(!t)throw await Po(e.pmRoot,e.id,e.settings.id_prefix,i);let o=await pt(e.pmRoot,t.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),n=o.release;try{let r=[],{raw:a,document:s}=await ii(t,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:r}),l=s.metadata.assignee?.trim(),c=s.metadata.claim_principal?.trim()||l,d=_t(e.author),u=It(e.settings);if(l&&c!==d&&!e.force&&!jo(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new f(`Item ${t.id} is assigned to ${l}. Use --force to override.`,y.CONFLICT);u.ownership_enforcement==="warn"&&r.push(`ownership_warning:assignee_conflict:${t.id}:${l}`)}return{typeToFolder:i,located:t,originalRaw:a,document:s,warnings:r,releaseLock:n,lease:o}}catch(r){throw await n(),r}}async function ri(e,i,t,o){return e.fence(async()=>{let n;try{n=await j.readFile(i.itemPath,"utf8")}catch(r){if(!A(r))throw r;n=null}if(n!==t)throw new f(`Item ${i.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,y.CONFLICT,{code:"stale_revision",item_id:i.id,reason:n===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return o()})}function $o(e,i,t){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:i,effectiveSerializedAfter:t,skipItemWrite:!1};let o=e.result;return{effectiveTargetItemPath:typeof o.target_item_path=="string"&&o.target_item_path.trim().length>0?o.target_item_path:i,effectiveSerializedAfter:typeof o.contents=="string"?o.contents:t,skipItemWrite:o.skip_write===!0}}async function Ho(e){let i=await Me("item_store_delete",e),t=i.handled&&typeof i.result=="object"&&i.result!==null?i.result:{};return{effectiveItemPath:typeof t.item_path=="string"&&t.item_path.trim().length>0?t.item_path:e.item_path,skipDelete:t.skip_delete===!0,warnings:i.warnings}}async function Wo(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await D(e.originalItemPath,e.originalRaw),await j.rm(e.effectiveTargetItemPath,{force:!0});return}await D(e.originalItemPath,e.originalRaw)}}async function et(e){yt(e.op);let i=await ni({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:t,located:o,originalRaw:n,document:r,warnings:a,releaseLock:s,lease:l}=i;try{Vt(e.pmRoot,r);let c=q(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),d=q(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(d);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...a,...u.warnings??[]]};let p={...e.resolveHistoryContext?.(),...Zt(e.pmRoot,o.id)},h=Math.max(Ae(c.metadata),Ae(d.metadata));vt(st(e.pmRoot),h),h>ht(d.metadata)&&(d.metadata.pm_format_version=h,u.changedFields.push("pm_format_version")),d.metadata.updated_at=Fe();let m=q(d,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),_=await $e({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:c,after:m});await De({pm_root:e.pmRoot,operation:e.op,before:c,after:m,changed_fields:u.changedFields,sdk:oi({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t})});let g=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:o.id,commandLabel:e.op}),b="toon",T=gt(m,{format:b,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),$=Re(e.pmRoot,m.metadata.type,o.id,b,t),N=R(e.pmRoot,o.id),I=await ri(l,o,n,async()=>{let k=await Me("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:o.id,source_item_path:o.itemPath,target_item_path:$,history_path:N,item_format:b,before:c,after:m,contents:T}),{effectiveTargetItemPath:S,effectiveSerializedAfter:z,skipItemWrite:H}=$o(k,$,T),ai=await Ke(e.pmRoot,e.author),tt=[];try{H||await D(S,z),!H&&S!==o.itemPath&&await j.rm(o.itemPath);let si=Le({nowIso:m.metadata.updated_at,author:e.author,op:e.op,before:c,after:m,message:e.message,context:_.decisions.length===0?Object.keys(p).length===0?void 0:p:{...p,workflow_policies:_.decisions}});try{await Pe(N,si)}catch(ci){throw await Wo({skipItemWrite:H,effectiveTargetItemPath:S,originalItemPath:o.itemPath,originalRaw:n}),ci}H||(tt=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t,schema:e.settings.schema,itemPath:S,previousItemPath:o.itemPath,document:m}))}finally{await ai()}return{derivedIndexWarnings:tt,effectiveTargetItemPath:S,overrideWarnings:k.warnings}}),{derivedIndexWarnings:M,effectiveTargetItemPath:C}=I,B=[...await L({path:C,scope:"project",op:e.op,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields}),...await L({path:N,scope:"project",op:`${e.op}:history`,item_id:m.metadata.id,item_type:m.metadata.type,before:c,after:m,changed_fields:u.changedFields})];return ke({id:m.metadata.id,op:e.op,item_type:m.metadata.type,previous_status:c.metadata.status,status:m.metadata.status,previous:de(c.metadata,u.changedFields),current:de(m.metadata,u.changedFields),changed_fields:u.changedFields}),{item:m.metadata,body:m.body,changedFields:u.changedFields,warnings:[...a,...u.warnings??[],..._.warnings,...g.warnings,...I.overrideWarnings,...M,...B]}}finally{await s()}}async function Zr(e){let{historyContext:i,...t}=e;return et({...t,resolveHistoryContext:()=>i})}async function ea(e){return et(e)}async function ta(e){return et(e)}async function ia(e){let i=await ni({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:t,originalRaw:o,document:n,warnings:r,releaseLock:a,lease:s}=i;try{let l=ei(void 0),c=q(n,{schema:e.settings.schema,extensionFieldNames:l}),d=await $e({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:c,after:null,dryRun:e.dryRun});await De({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:oi({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:i.typeToFolder})});let u=await Je({pmRoot:e.pmRoot,settings:e.settings,itemId:t.id,commandLabel:"delete"}),p=Fe(),h=it,m=Le({nowIso:p,author:e.author,op:"delete",before:c,after:h,message:e.message,context:d.decisions.length===0?void 0:{workflow_policies:d.decisions}}),_=R(e.pmRoot,t.id),g=()=>Ho({op:"delete",pm_root:e.pmRoot,item_id:t.id,item_path:t.itemPath,history_path:_,before:c});if(e.dryRun===!0){let I=await g();return{item:c.metadata,changedFields:["deleted"],targetPath:I.effectiveItemPath,warnings:[...r,...d.warnings,...u.warnings,...I.warnings]}}let b=await ri(s,t,o,async()=>{let{effectiveItemPath:I,skipDelete:M,warnings:C}=await g(),B=await Ke(e.pmRoot,e.author),k=[];try{M||await j.rm(I);try{await Pe(_,m)}catch(S){throw M||await D(I,o),S}M||(k=await Ve({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:i.typeToFolder,schema:e.settings.schema,itemPath:I,document:null}))}finally{await B()}return{derivedIndexWarnings:k,effectiveItemPath:I,overrideWarnings:C}}),{derivedIndexWarnings:T,effectiveItemPath:$}=b,N=[...await L({path:$,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]}),...await L({path:_,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]})];return ke({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:de(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...r,...d.warnings,...u.warnings,...b.overrideWarnings,...T,...N]}}finally{await a()}}export{$n as a,Je as b,wo as c,Tt as d,V as e,J as f,Go as g,re as h,Gt as i,Qe as j,qt as k,ir as l,pi as m,hi as n,gi as o,_i as p,wi as q,$e as r,un as s,br as t,wn as u,bn as v,En as w,$t as x,Fi as y,Ke as z,Fn as A,Ve as B,xe as C,ti as D,ii as E,Mo as F,Fo as G,Jr as H,Qr as I,oi as J,Po as K,Zr as L,ea as M,ta as N,ia as O};
91
- //# sourceMappingURL=chunk-ZMWLV2CE.js.map
91
+ //# sourceMappingURL=chunk-QH5KMIYZ.js.map
@@ -1,4 +1,4 @@
1
- import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-NX7TVNUM.js";import{U as H,a as $,b as D}from"./chunk-SBJ2IKTH.js";import{c as u,f as M,g as z,i as q}from"./chunk-TAHSXKAT.js";import{Va as F,q as L,t as R}from"./chunk-GXAXDPD4.js";import{a as g,d as K}from"./chunk-JYXA4JIP.js";import{da as k,g as P}from"./chunk-7RQOFHMH.js";import{a as N,e as O,f as A,g as x,i as C}from"./chunk-BUZ2Z4P3.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ec1f825-59d1-5ce2-ac76-c628264bd8be")}catch{}})();var Ce=N,Pe=O,$e=C,De=A,Le=x;function G(e,t,n,r){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(a,i)=>i.toUpperCase()),o=n.has(s);return{long:t,...r?{short:r}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:o?"string":"boolean",...o?{value_name:e.value_name??"value"}:{}}}function Q(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),r=[];for(let s of L(e.map(o=>({...o})))){r.push(G(s,s.flag,n,s.short));for(let o of s.aliases??[])r.push(G(s,o,n))}return r}var Re=Q(R,$),Fe=Q(F,D);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59d16a38-d6df-5695-96e3-28b6e384f76b")}catch{}})();var _=["agile","ops","research"],I={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:w.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
1
+ import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-7DEZT4JN.js";import{U as H,a as $,b as D}from"./chunk-MT5TYMEU.js";import{c as u,f as M,g as z,i as q}from"./chunk-ZYCOMRFT.js";import{Va as F,q as L,t as R}from"./chunk-5LBZR6YW.js";import{a as g,d as K}from"./chunk-22727JYL.js";import{da as k,g as P}from"./chunk-NC5HUGHU.js";import{a as N,e as O,f as A,g as x,i as C}from"./chunk-46KDJH3K.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3ec1f825-59d1-5ce2-ac76-c628264bd8be")}catch{}})();var Ce=N,Pe=O,$e=C,De=A,Le=x;function G(e,t,n,r){let s=e.flag.slice(2).replace(/[-_]([a-z])/gu,(a,i)=>i.toUpperCase()),o=n.has(s);return{long:t,...r?{short:r}:{},description:e.description??`Standard pm ${e.flag} option.`,...e.required===!0?{required:!0}:{},...e.list===!0?{list:!0}:{},...e.repeatable===!0?{repeatable:!0}:{},value_type:o?"string":"boolean",...o?{value_name:e.value_name??"value"}:{}}}function Q(e,t=[]){let n=new Set(t.flatMap(s=>s.keys)),r=[];for(let s of L(e.map(o=>({...o})))){r.push(G(s,s.flag,n,s.short));for(let o of s.aliases??[])r.push(G(s,o,n))}return r}var Re=Q(R,$),Fe=Q(F,D);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59d16a38-d6df-5695-96e3-28b6e384f76b")}catch{}})();var _=["agile","ops","research"],I={agile:{name:"agile",title:"Agile delivery",summary:"Story/Spike delivery with a review stage, story points, and acceptance ownership.",types:w.agile,statuses:[{id:"review",roles:["active"],aliases:["in-review"],description:"Work is implementation-complete and awaiting peer review."}],fields:[{key:"story_points",type:"number",commands:["create","update","list"],description:"Relative estimation size for a story or spike.",aliases:["points"]},{key:"acceptance_owner",type:"string",commands:["create","update","list"],description:"Stakeholder accountable for accepting the delivered story.",aliases:["acceptor"]}],workflows:[{type:"Story",allowed_transitions:[["open","in_progress"],["in_progress","review"],["review","in_progress"],["review","closed"],["in_progress","blocked"],["blocked","in_progress"]]}],config:[{key:"search_provider",value:"bm25",summary:"Offline BM25 lexical search works without an embedding service."},{key:"search_max_results",value:"20",summary:"Sprint-sized result cap for quick triage."}],templates:[{name:"story",options:{type:"Story",priority:"2",tags:"story",acceptanceCriteria:"Story delivers the stated user outcome with tests and docs updated.",body:`## As a
2
2
 
3
3
  ## I want
4
4
 
@@ -23,4 +23,4 @@ import{f as w,i as y,j,k as B,l as U,o as f,p as X,q as W,r as Y}from"./chunk-NX
23
23
 
24
24
  ## Conclusion
25
25
  `}}],packages:[{spec:"search-advanced",reason:"Semantic retrieval over experiments and findings."},{spec:"templates",reason:"Consistent experiment and hypothesis scaffolds."},{spec:"beads",reason:"Import structured prior work into the tracker."}]}};function ne(e){if(e===void 0)return;let t=p(e);if(t.length===0)throw new Error("Profile name must not be empty.");if(_.includes(t))return t;throw new Error(`Invalid profile "${e}". Allowed: ${_.join(", ")}.`)}function qe(e){let t=ne(e);if(t===void 0)throw new Error(`Profile name is required. Allowed: ${_.join(", ")}.`);return I[t]}function je(){return _.map(e=>I[e])}function p(e){return e.trim().toLowerCase().replaceAll("-","_")}function J(e){return e.map(t=>t.definition.name).join(", ")}function re(e=[]){let t=_.map(o=>({definition:I[o],source:"builtin"})),n=new Set(_.map(o=>p(o))),r=new Set(n),s=[];for(let o of e){let a=p(o.profile.name);if(n.has(a)){s.push(`Extension "${o.name}" profile "${o.profile.name}" uses a name reserved by a built-in archetype and was ignored.`);continue}if(r.has(a)){s.push(`Profile "${o.profile.name}" from extension "${o.name}" duplicates an already-registered profile and was ignored.`);continue}r.add(a),t.push({definition:o.profile,source:"extension",package:o.name})}return{profiles:t,warnings:s}}function Be(e,t=[]){let{profiles:n,warnings:r}=re(t);if(typeof e!="string"||e.trim().length===0)throw new Error(`Profile name is required. Allowed: ${J(n)}.`);let s=p(e),o=n.find(a=>p(a.definition.name)===s);if(o===void 0)throw new Error(`Invalid profile "${e}". Allowed: ${J(n)}.`);return{resolved:o,warnings:r}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab26bcb3-fb2a-5f2f-96e7-7965787b924e")}catch{}})();function se(e){return{types:e.types.length,statuses:e.statuses.length,fields:e.fields.length,workflows:e.workflows.length,config:e.config.length,templates:e.templates.length,packages:e.packages.length}}function Ye(e){return{name:e.name,title:e.title,summary:e.summary,composition:se(e),types:e.types.map(t=>S(()=>u(t).name,()=>String(t.name??""))),statuses:e.statuses.map(t=>S(()=>f(t).id,()=>String(t.id??""))),fields:e.fields.map(t=>S(()=>y(t).key,()=>String(t.key??""))),workflows:e.workflows.map(t=>t.type),config:e.config.map(t=>`${t.key}=${t.value}`),templates:e.templates.map(t=>t.name),packages:e.packages.map(t=>({spec:t.spec,reason:t.reason}))}}function S(e,t){try{return e()}catch{return t()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d681ddfe-ad15-527b-90de-bfbe341c6a86")}catch{}})();var oe=[{key:"search_provider",path:"search.provider",kind:"string",summary:"Search embedding provider name (e.g. openai, ollama, or an extension provider)."},{key:"search_default_mode",path:"search.default_mode",kind:"string",choices:["auto","keyword","semantic","hybrid"],summary:"Mode a bare pm search runs in: auto (hybrid when semantic search is explicitly configured and runnable, else keyword), or a pinned keyword, semantic, or hybrid."},{key:"search_mutation_refresh_policy",path:"search.mutation_refresh_policy",kind:"string",choices:["cache_only","semantic_configured","semantic_auto"],summary:"Mutation-time search refresh policy: cache_only, semantic_configured, or semantic_auto."},{key:"search_query_expansion_enabled",path:"search.query_expansion.enabled",kind:"boolean",summary:"Enable or disable query expansion for semantic/hybrid search."},{key:"search_query_expansion_provider",path:"search.query_expansion.provider",kind:"string",summary:"Query expansion provider name (built-in openai/ollama or extension provider)."},{key:"search_rerank_enabled",path:"search.rerank.enabled",kind:"boolean",summary:"Enable or disable post-retrieval reranking for hybrid search."},{key:"search_rerank_model",path:"search.rerank.model",kind:"string",summary:"Rerank model name override used by built-in providers."},{key:"search_rerank_top_k",path:"search.rerank.top_k",kind:"integer",min:1,summary:"Number of top hybrid candidates to rerank when rerank is enabled."},{key:"search_embedding_model",path:"search.embedding_model",kind:"string",summary:"Default embedding model name (overrides provider-specific model when set)."},{key:"search_embedding_corpus_max_characters",path:"search.embedding_corpus_max_characters",kind:"integer",min:1,summary:"Maximum semantic corpus characters per item before truncation."},{key:"search_embedding_batch_size",path:"search.embedding_batch_size",kind:"integer",min:1,summary:"Number of items embedded per request batch."},{key:"search_embedding_timeout_ms",path:"search.embedding_timeout_ms",kind:"integer",min:1,summary:"Per-request embedding timeout in milliseconds."},{key:"search_score_threshold",path:"search.score_threshold",kind:"number",summary:"Minimum score for a hit to be returned (0 keeps all matches)."},{key:"search_hybrid_semantic_weight",path:"search.hybrid_semantic_weight",kind:"ratio",summary:"Hybrid mode semantic weight in [0, 1] (1-weight goes to keyword)."},{key:"search_max_results",path:"search.max_results",kind:"integer",min:1,summary:"Default upper bound on search hits when --limit is not supplied."},{key:"search_bm25_k1",path:"search.bm25.k1",kind:"number",min:0,summary:"Offline BM25 term-frequency saturation (k1); higher saturates repeated terms slower (default 1.2)."},{key:"search_bm25_b",path:"search.bm25.b",kind:"ratio",summary:"Offline BM25 document-length normalization (b) in [0, 1]; 0 disables, 1 fully normalizes (default 0.75)."},{key:"openai_base_url",path:"providers.openai.base_url",kind:"string",summary:"OpenAI-compatible API base URL (LM Studio/vLLM also use this)."},{key:"openai_api_key",path:"providers.openai.api_key",kind:"string",summary:"OpenAI-compatible API key."},{key:"openai_model",path:"providers.openai.model",kind:"string",summary:"OpenAI-compatible embedding model name."},{key:"ollama_base_url",path:"providers.ollama.base_url",kind:"string",summary:"Ollama API base URL (typically http://localhost:11434)."},{key:"ollama_model",path:"providers.ollama.model",kind:"string",summary:"Ollama embedding model name (e.g. nomic-embed-text)."},{key:"vector_store_adapter",path:"vector_store.adapter",kind:"string",summary:"Vector store adapter name (lancedb, qdrant, or an extension adapter)."},{key:"vector_store_collection_name",path:"vector_store.collection_name",kind:"string",non_empty:!0,summary:"Vector collection/table name shared by Qdrant and LanceDB adapters."},{key:"qdrant_url",path:"vector_store.qdrant.url",kind:"string",summary:"Qdrant HTTP API URL."},{key:"qdrant_api_key",path:"vector_store.qdrant.api_key",kind:"string",summary:"Qdrant API key (empty if running unauthenticated)."},{key:"lancedb_path",path:"vector_store.lancedb.path",kind:"string",summary:"LanceDB storage path (relative to pm root or absolute)."},{key:"id_prefix",path:"id_prefix",kind:"string",non_empty:!0,summary:'Prefix for generated item IDs (e.g. "pm" produces pm-xxxx).'},{key:"author_default",path:"author_default",kind:"string",non_empty:!0,summary:"Default author recorded on mutations when --author is not supplied."},{key:"agent_identity_probes_enabled",path:"agent_identity.probes_enabled",kind:"boolean",summary:"Allow privacy-bounded local harness provenance probes; no network or subprocess access is permitted."},{key:"mutation_guard_require_attributed_author",path:"mutation_guard.require_attributed_author",kind:"boolean",summary:"Reject mutations whose effective author resolves to unknown."},{key:"mutation_guard_secret_guard",path:"mutation_guard.secret_guard",kind:"string",choices:["off","advise","block"],summary:"Detect credential-shaped mutation content: off, advise, or block."},{key:"mutation_guard_stale_in_progress_hours",path:"mutation_guard.stale_in_progress_hours",kind:"integer",min:1,summary:"Age threshold for unclaimed in-progress work surfaced by health."},{key:"governance_duplicate_detection_mode",path:"governance.duplicate_detection_mode",kind:"string",choices:["off","advisory","strict"],summary:"Create/copy duplicate governance: off, advisory, or strict explicit-bypass enforcement."},{key:"governance_duplicate_detection_threshold",path:"governance.duplicate_detection_threshold",kind:"ratio",summary:"Minimum shared similarity score in [0, 1] for create/copy duplicate governance."},{key:"governance_duplicate_detection_limit",path:"governance.duplicate_detection_limit",kind:"integer",min:0,max:20,summary:"Maximum likely duplicates returned by create/copy governance (0-20)."},{key:"output_default_format",path:"output.default_format",kind:"string",choices:["toon","json"],summary:"Default output format for commands that support it: toon or json."},{key:"ux_deprecation_hints",path:"ux.deprecation_hints",kind:"boolean",summary:"Emit one stderr migration hint for deprecated command aliases."},{key:"locks_ttl_seconds",path:"locks.ttl_seconds",kind:"integer",min:1,summary:"Claim/lock time-to-live in seconds before a stale lock can be reclaimed."},{key:"locks_wait_ms",path:"locks.wait_ms",kind:"integer",min:0,summary:"Wait budget in milliseconds before a contended lock fails with lock_conflict; item-store mutations, restore and the hierarchy lock treat it as a no-progress window that each observed owner handoff restarts (120 s total cap), other locks as a fixed total; 0 fails fast. PM_LOCK_WAIT_MS overrides per invocation."},{key:"ids_token_length",path:"ids.token_length",kind:"integer",min:4,max:12,summary:"Random base36 token length for newly minted item ids (4-12, default 4). Raise it to shrink cross-branch id collision odds in concurrent multi-agent workflows (pm-pibw)."},{key:"checkpoints_retention_days",path:"checkpoints.retention_days",kind:"integer",min:1,summary:"Age in days above which pm gc --scope checkpoints prunes bulk-mutation rollback checkpoints."},{key:"schema_unknown_field_policy",path:"schema.unknown_field_policy",kind:"string",choices:["allow","warn","reject"],summary:"How item I/O handles metadata keys not in the field registry: allow, warn, or reject."},{key:"history_compact_policy_enabled",path:"history.compact_policy.enabled",kind:"boolean",summary:"Enable the history-compaction advisory: pm health warns on over-threshold streams."},{key:"history_compact_policy_max_entries",path:"history.compact_policy.max_entries",kind:"integer",min:1,summary:"Entry count above which a history stream is flagged (and the default pm history-compact --all-over threshold)."},{key:"history_compact_policy_trigger",path:"history.compact_policy.trigger",kind:"string",choices:["health_warn","auto"],summary:"History-compaction policy intent: health_warn (advisory only) or auto (scheduled sweeps expected)."}],ae=new Map(oe.flatMap(e=>[[e.key,e],[e.path.toLowerCase().replaceAll("-","_"),e]]));function b(e){if(typeof e!="string")return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length!==0)return ae.get(t)}function ie(e,t){let n=t.trim().toLowerCase();return n==="true"||n==="1"||n==="yes"||n==="on"?{ok:!0,parsed:{descriptor:e,value:!0}}:n==="false"||n==="0"||n==="no"||n==="off"?{ok:!0,parsed:{descriptor:e,value:!1}}:{ok:!1,error:{message:`Config set ${e.key} requires a boolean value (true|false), got "${t}"`}}}function le(e,t,n){return e.non_empty===!0&&n.length===0?{ok:!1,error:{message:`Config set ${e.key} requires a non-empty value`}}:e.choices&&!e.choices.includes(n)?{ok:!1,error:{message:`Config set ${e.key} must be one of ${e.choices.join("|")}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function de(e,t,n){if(n.length===0)return{ok:!1,error:{message:`Config set ${e.key} requires a non-empty value`}};let r=Number(n);return Number.isFinite(r)?{ok:!0,value:r}:{ok:!1,error:{message:`Config set ${e.key} requires a finite number, got "${t}"`}}}function ce(e,t,n){return!Number.isInteger(n)||n<0?{ok:!1,error:{message:`Config set ${e.key} requires a non-negative integer, got "${t}"`}}:e.min!==void 0&&n<e.min?{ok:!1,error:{message:`Config set ${e.key} requires an integer >= ${e.min}, got "${t}" (the runtime silently ignores 0 here and falls back to the default)`}}:e.max!==void 0&&n>e.max?{ok:!1,error:{message:`Config set ${e.key} requires an integer <= ${e.max}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function me(e,t,n){return n<0||n>1?{ok:!1,error:{message:`Config set ${e.key} requires a number in [0, 1], got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function pe(e,t,n){return e.min!==void 0&&n<e.min?{ok:!1,error:{message:`Config set ${e.key} requires a number >= ${e.min}, got "${t}"`}}:{ok:!0,parsed:{descriptor:e,value:n}}}function v(e,t){if(typeof t!="string")return{ok:!1,error:{message:`Config set ${e.key} requires a string value`}};let n=t.trim();if(e.kind==="boolean")return ie(e,t);if(e.kind==="string")return le(e,t,n);let r=de(e,t,n);return r.ok?e.kind==="integer"?ce(e,t,r.value):e.kind==="ratio"?me(e,t,r.value):pe(e,t,r.value):{ok:!1,error:r.error}}function V(e,t){let n=t.path.split("."),r=e;for(let s of n){if(typeof r!="object"||r===null)return null;let o=Object.getOwnPropertyDescriptor(r,s);if(!o||!Object.hasOwn(o,"value"))return null;r=o.value}return typeof r=="string"||typeof r=="number"||typeof r=="boolean"?r:null}function Ge(e,t,n){let r=t.path.split(".");if(r.some(a=>a.length===0||["__proto__","constructor","prototype"].includes(a)))throw new Error("Unsafe settings path");let s=e;for(let a=0;a<r.length-1;a+=1){let i=r[a],d=Object.getOwnPropertyDescriptor(s,i)?.value;if(typeof d!="object"||d===null||Array.isArray(d)){let c={};Object.defineProperty(s,i,{value:c,writable:!0,enumerable:!0,configurable:!0}),s=c}else s=d}let o=r[r.length-1];return Object.getOwnPropertyDescriptor(s,o)?.value===n?!1:(Object.defineProperty(s,o,{value:n,writable:!0,enumerable:!0,configurable:!0}),!0)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0b04624c-2096-55dc-9dde-b8c76ead72d6")}catch{}})();var it=["profile","types","statuses","fields","workflows","config","templates","packages"],lt=["profile_name_empty","profile_name_not_normalized","profile_title_empty","profile_summary_empty","type_invalid","type_duplicate","status_invalid","status_duplicate","field_invalid","field_duplicate","field_mcp_input_collision","workflow_type_empty","workflow_type_unknown","workflow_duplicate_type","workflow_transition_malformed","workflow_status_unknown","config_key_unknown","config_value_invalid","config_duplicate","template_type_unknown","package_spec_empty"],ue=new Set(K.flatMap(e=>[g(e.id),...(e.aliases??[]).map(t=>g(t))]).filter(e=>e.length>0)),Z=new Set(P.map(e=>e.toLowerCase()));function ye(e,t){e.name.trim().length===0?t.push({severity:"error",code:"profile_name_empty",dimension:"profile",message:"Profile name must not be empty; profile resolution requires a non-blank name."}):e.name!==p(e.name)&&t.push({severity:"warning",code:"profile_name_not_normalized",dimension:"profile",target:e.name,message:`Profile name "${e.name}" is not in canonical form; resolution folds it to "${p(e.name)}" (lowercase, hyphens as underscores).`}),e.title.trim().length===0&&t.push({severity:"warning",code:"profile_title_empty",dimension:"profile",message:"Profile title is empty; list and show surfaces will render a blank title."}),e.summary.trim().length===0&&t.push({severity:"warning",code:"profile_summary_empty",dimension:"profile",message:"Profile summary is empty; list and show surfaces will render a blank archetype description."})}function fe(e,t){let n=new Set,r=new Set;for(let[s,o]of e.types.entries()){let a;try{a=u(o).name}catch(d){t.push({severity:"error",code:"type_invalid",dimension:"types",target:typeof o.name=="string"?o.name:`#${s}`,message:k(d)});continue}let i=a.toLowerCase();if(r.has(i)){t.push({severity:"error",code:"type_duplicate",dimension:"types",target:a,message:`Item type "${a}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(i),n.add(i)}return n}function he(e,t){let n=new Set,r=new Set;for(let[s,o]of e.statuses.entries()){let a;try{a=f(o)}catch(i){t.push({severity:"error",code:"status_invalid",dimension:"statuses",target:typeof o.id=="string"?o.id:`#${s}`,message:k(i)});continue}if(r.has(a.id)){t.push({severity:"error",code:"status_duplicate",dimension:"statuses",target:a.id,message:`Status "${a.id}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}r.add(a.id),n.add(a.id);for(let i of a.aliases??[])n.add(g(i))}return n}function ge(e,t){let n=new Set;for(let[r,s]of e.fields.entries()){let o;try{o=y(s).key}catch(i){t.push({severity:"error",code:"field_invalid",dimension:"fields",target:typeof s.key=="string"?s.key:`#${r}`,message:k(i)});continue}if(n.has(o)){t.push({severity:"error",code:"field_duplicate",dimension:"fields",target:o,message:`Field "${o}" is declared more than once; the later definition silently overwrites the earlier upsert.`});continue}n.add(o);let a=H(o);a&&t.push({severity:"warning",code:"field_mcp_input_collision",dimension:"fields",target:o,message:`Field "${o}" collides with canonical MCP property "${a.property}" owned by ${a.owner}; callers must pass the custom value through ${a.nested_path}.`})}}function _e(e,t,n,r){let s=new Set;for(let[o,a]of e.workflows.entries()){let i=a.type.trim().toLowerCase();if(i.length===0){r.push({severity:"error",code:"workflow_type_empty",dimension:"workflows",target:`#${o}`,message:"Workflow has an empty type; the workflow resolver drops entries without a type."});continue}let d=s.has(i);s.add(i),d?r.push({severity:"warning",code:"workflow_duplicate_type",dimension:"workflows",target:a.type,message:`Workflow type "${a.type}" is declared more than once; the later transition set wins.`}):!Z.has(i)&&!t.has(i)&&r.push({severity:"warning",code:"workflow_type_unknown",dimension:"workflows",target:a.type,message:`Workflow governs type "${a.type}" which is neither a built-in type nor declared by this profile; it has no effect unless that type already exists.`});let c=new Set;for(let l of a.allowed_transitions){let m=g(l[0]),T=g(l[1]);if(m.length===0||T.length===0){r.push({severity:"error",code:"workflow_transition_malformed",dimension:"workflows",target:a.type,message:`Workflow "${a.type}" has a transition with an empty status; the workflow resolver silently drops it.`});continue}for(let h of[m,T])ue.has(h)||n.has(h)||c.has(h)||(c.add(h),r.push({severity:"warning",code:"workflow_status_unknown",dimension:"workflows",target:h,message:`Workflow "${a.type}" references status "${h}" which is neither a built-in status nor declared by this profile; transitions to or from it are unreachable.`}))}}}function ke(e,t){let n=new Set;for(let r of e.config){let s=b(r.key);if(s===void 0){t.push({severity:"error",code:"config_key_unknown",dimension:"config",target:r.key,message:`Config knob "${r.key}" is not a recognized setting; apply rejects it with a usage error.`});continue}n.has(s.key)?t.push({severity:"error",code:"config_duplicate",dimension:"config",target:s.key,message:`Config knob "${s.key}" is set more than once; the later value silently overwrites the earlier one.`}):n.add(s.key);let o=v(s,r.value);o.ok||t.push({severity:"error",code:"config_value_invalid",dimension:"config",target:r.key,message:o.error.message})}}function we(e,t,n){for(let r of e.templates){let s=r.options.type;if(typeof s!="string"||s.trim().length===0)continue;let o=s.trim().toLowerCase();!Z.has(o)&&!t.has(o)&&n.push({severity:"warning",code:"template_type_unknown",dimension:"templates",target:r.name,message:`Template "${r.name}" creates type "${s}" which is neither a built-in type nor declared by this profile.`})}}function be(e,t){for(let[n,r]of e.packages.entries())r.spec.trim().length===0&&t.push({severity:"warning",code:"package_spec_empty",dimension:"packages",target:`#${n}`,message:"Package recommendation has an empty spec; it cannot be surfaced as an install hint."})}function dt(e){let t=[];ye(e,t);let n=fe(e,t),r=he(e,t);ge(e,t),_e(e,n,r,t),ke(e,t),we(e,n,t),be(e,t);let s=t.filter(a=>a.severity==="error").length,o=t.length-s;return{profile:e.name,ok:s===0,findings:t,errorCount:s,warningCount: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]="be2b507d-2797-570c-b211-46d950edcbde")}catch{}})();function E(e,t,n,r,s){let o=e,a=[];for(let i of t){let d=r(o),c=s(o,i),l=r(c.file);o=c.file;let m=d===l?"unchanged":c.replaced?"update":"add";a.push({key:n(i),status:m})}return{file:o,changes:a,changed:a.some(i=>i.status!=="unchanged")}}function ee(e){return JSON.stringify(e.map(t=>t.join("\0")).sort())}function ve(e,t){let n=e.map(s=>({...s})),r=[];for(let s of t){let o=n.findIndex(i=>i.type===s.type),a={type:s.type,allowed_transitions:s.allowed_transitions};o<0?(n.push(a),r.push({type:s.type,status:"add"})):ee(n[o].allowed_transitions)===ee(s.allowed_transitions)?r.push({type:s.type,status:"unchanged"}):(n[o]=a,r.push({type:s.type,status:"update"}))}return{changes:r,result:n,changed:r.some(s=>s.status!=="unchanged")}}function Ie(e,t){let n=[];for(let r of e.config){let s=b(r.key);if(s===void 0)throw new Error(`Profile "${e.name}" references unknown config key "${r.key}".`);let o=v(s,r.value);if(!o.ok)throw new Error(`Profile "${e.name}" config ${r.key}: ${o.error.message}`);let a=V(t,s),i=a===null?"add":a===o.parsed.value?"unchanged":"update";n.push({key:s.key,path:s.path,value:o.parsed.value,status:i})}return{changes:n,changed:n.some(r=>r.status!=="unchanged")}}function te(e){let t=Object.entries(e).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(t)}function Se(e,t){let n=[];for(let r of e.templates){let s=t.get(r.name),o;s===void 0?o="add":te(s)===te(r.options)?o="unchanged":o="update",n.push({name:r.name,options:r.options,status:o})}return{changes:n,changed:n.some(r=>r.status!=="unchanged")}}function ft(e,t){let n=E(M(t.typesRaw),e.types,l=>u(l).name,q,(l,m)=>z(l,u(m))),r=E(X(t.statusesRaw),e.statuses,l=>f(l).id,W,(l,m)=>Y(l,f(m))),s=E(j(t.fieldsRaw),e.fields,l=>y(l).key,B,(l,m)=>U(l,y(m))),o=ve(t.workflows,e.workflows),a=Ie(e,t.settings),i=Se(e,t.templates),d=e.packages.map(l=>({spec:l.spec,reason:l.reason,status:t.installedPackages.has(l.spec)?"installed":"recommended"})),c=n.changed||r.changed||s.changed||o.changed||a.changed||i.changed;return{profile:{name:e.name,title:e.title,summary:e.summary},types:n,statuses:r,fields:s,workflows:o,config:a,templates:i,packages:d,changed:c}}export{Ce as a,Pe as b,$e as c,De as d,Le as e,Q as f,Re as g,Fe as h,_ as i,I as j,ne as k,qe as l,je as m,re as n,Be as o,se as p,Ye as q,oe as r,b as s,v as t,V as u,Ge as v,it as w,lt as x,dt as y,ft as z};
26
- //# sourceMappingURL=chunk-POLMFGPQ.js.map
26
+ //# sourceMappingURL=chunk-U6HXIF6G.js.map
@@ -1,2 +1,2 @@
1
- import{D as Ue,E as je,H as ze,f as Pe}from"./chunk-ZMWLV2CE.js";import{_a as $e,db as Ke,s as P,t as D}from"./chunk-IUAYTD2S.js";import{j as Ie}from"./chunk-JYXA4JIP.js";import{b as R,c as I}from"./chunk-AK2CI2GI.js";import{Dc as X,Fa as Ce,Oc as M,R as T,T as H,Uc as Te,W as ke,Zc as Re,cd as De,ee as Be,fe as Ne,gd as Se,ic as W,jc as xe,ka as be,nd as Le,od as Oe,pe as Me,qa as ve,sa as we,sd as Ae,wa as Ee,xc as ne}from"./chunk-7RQOFHMH.js";import{y as v,z as w}from"./chunk-BUZ2Z4P3.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a319e7d9-e248-573b-bf1f-35217ce49fd0")}catch{}})();function re(e,t){return(t===void 0?void 0:we(e,t))?.execution_role??be[e.trim().toLowerCase()]??"agent"}var ie="blocked_by",Fe="blocks",mt=Object.freeze([ie,Fe]),oe="no-active-blocker";function _(e){return e.trim().toLowerCase()}function q(e,t){return t?`external:${e}`:`local:${_(e)}`}function $(e){let t=new Map,o=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(o.length>0&&_(o)!==oe){let n=R(o);t.set(q(o,n),n?o:_(o))}for(let n of e.dependencies??[]){let r=typeof n.id=="string"?n.id.trim():"";if(H(n.kind)===ie&&r.length>0&&_(r)!==oe){let i=R(r)||I(n.source_kind);t.set(q(r,i),i?r:_(r))}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Y(e){let t=new Map;for(let o of e){let n=_(o.id);n.length!==0&&t.set(n,new Set($(o)))}for(let o of e){let n=_(o.id);if(n.length!==0)for(let r of o.dependencies??[]){let i=H(r.kind)===Fe&&typeof r.id=="string"?_(r.id):"";if(i.length===0||i===oe)continue;let s=t.get(i)??new Set;s.add(n),t.set(i,s)}}return new Map([...t].map(([o,n])=>[o,[...n].sort((r,i)=>r.localeCompare(i))]))}function Ge(e,t){let o=_(e.id);return o.length>0?Y(t).get(o)??$(e):$(e)}function se(e,t,o,n){let r=e,i=typeof r.id=="string"?n?.get(_(r.id))??Ge(r,[...t.values()]):$(e),s=new Set((e.dependencies??[]).filter(d=>H(d.kind)===ie&&I(d.source_kind)&&typeof d.id=="string"&&d.id.trim().length>0).map(d=>q(d.id.trim(),!0)));return i.map(d=>{if(R(d)||s.has(q(d,!0)))return{id:d,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};let c=t.get(_(d));return c?{id:d,title:c.title,status:c.status,resolved:D(c.status,o)}:{id:d,title:null,status:null,resolved:!1}})}function gt(e,t,o){return se(e,t,o)}function ht(e,t){let o=new Map(e.map(s=>[_(s.id),s])),n=Y(e),r=new Set([...He(t),...t.blocked_statuses]),i=new Set;for(let s of e){let d=P(s.status,t);r.has(d)&&(t.blocked_statuses.has(d)||se(s,o,t,n).some(c=>!c.resolved))&&i.add(_(s.id))}return i}function yt(e,t,o={},n){let r=[...e.ready,...e.decisions,...e.gates];o.includeContainers===!0&&r.push(...e.containers.filter(s=>s.open_blockers.length===0&&!t.blocked_statuses.has(P(s.item.status,t))));let i={ready:[],decisions:[],gates:[]};for(let s of r){let d=re(s.item.type,n);d==="human"&&o.includeDecisions!==!0?i.decisions.push(s):d==="gate"&&o.includeGates!==!0?i.gates.push(s):i.ready.push(s)}return i}function He(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function _t(e,t,o){let n=[_(e)],r=new Set;for(;n.length>0;){let i=n.pop();if(!r.has(i)){r.add(i);for(let s of t.get(i)??[]){if(!D(s.status,o))return!0;n.push(_(s.id))}}}return!1}function kt(e){let t=new Map,o=new Map,n=new Map,r=Y(e);for(let i of e){t.set(_(i.id),i);let s=typeof i.parent=="string"?i.parent.trim():"";if(s.length>0){let d=_(s),c=o.get(d)??[];c.push(i),o.set(d,c)}for(let d of r.get(_(i.id))){let c=_(d),l=n.get(c)??[];l.push(i.id),n.set(c,l)}}return{itemsById:t,childrenByParent:o,blockedByReverse:n,blockerIdsByItem:r}}function bt(e,t,o,n){let{itemsById:r,childrenByParent:i,blockedByReverse:s,blockerIdsByItem:d}=kt(t),c=new Set([...He(o),...o.blocked_statuses]),l=new Set(t.filter(m=>!D(m.status,o)).map(m=>_(m.id))),u=[],a=[],f=[],g=[],p=[],y=0;for(let m of e){if(!c.has(P(m.status,o)))continue;y+=1;let h=se(m,r,o,d).filter(E=>!E.resolved),b=(s.get(_(m.id))??[]).filter(E=>l.has(_(E))).sort((E,L)=>E.localeCompare(L)),k={item:m,open_blockers:h,unblocks:b};if(_t(m.id,i,o)){f.push(k);continue}let C=o.blocked_statuses.has(P(m.status,o));if(h.length===0&&!C){let E=re(m.type,n);E==="human"?g.push(k):E==="gate"?p.push(k):u.push(k)}else a.push(k)}return{ready:u,blocked:a,containers:f,decisions:g,gates:p,active_count:y,container_count:f.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae1c56b3-148d-502d-9450-e807fdfab4da")}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]="283dfa35-9a8e-524c-b6e2-d433d51215ca")}catch{}})();function x(){let e=T();for(let t of W()?.relationship_kinds??[])for(let o of t.definitions)e.register(o);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b57e560-4ac4-53b6-9fb1-eebb1f30562a")}catch{}})();function K(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function V(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function vt(e,t){let o=new Set,n=[];for(let r of[...e].sort()){if(o.has(r))continue;o.add(r);let i=[{nodeId:r,children:[...t.get(r)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),d=s.children[s.nextChild];d===void 0?(n.push(s.nodeId),i.pop()):(s.nextChild+=1,o.has(d)||(o.add(d),i.push({nodeId:d,children:[...t.get(d)??[]].sort(),nextChild:0})))}}return n}function wt(e,t){let o=[...e].sort(),n=vt(o,t),r=new Set,i=Et(o,t),s=[];for(let d of n.reverse()){if(r.has(d))continue;let c=Ct(d,i,r);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((d,c)=>d.join("\0").localeCompare(c.join("\0")))}function Et(e,t){let o=new Map(e.map(n=>[n,new Set]));for(let[n,r]of t)for(let i of r)o.get(i)?.add(n);return o}function Ct(e,t,o){let n=[],r=[e];for(o.add(e);r.length>0;){let i=r.pop();n.push(i);for(let s of[...t.get(i)].sort())o.has(s)||(o.add(s),r.push(s))}return n.sort()}function We(e){let t=new Map;for(let o of e){let n=K(o?.id);n&&!t.has(n)&&t.set(n,o)}return t}function It(e,t,o){let n=K(t.parent);if(!(!n||!o.has(n)))return{parent_id:n,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function xt(e,t,o,n){let r=K(t?.id),i=n.resolve(t?.kind);if(!r||!o.has(r)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:r,child_id:s?r:e,source:"dependency",kind:i.kind,holder_id:e,target_id:r,child_cardinality:s?i.incoming:i.outgoing}}function Xe(e,t){let o=new Map;for(let[n,r]of e){let i=It(n,r,e);i&&o.set(V(i),i);for(let s of r.dependencies??[]){let d=xt(n,s,e,t);d&&o.set(V(d),d)}}return[...o.values()].sort((n,r)=>V(n).localeCompare(V(r)))}function Fn(e,t=x()){return Xe(We(e),t)}function Tt(e,t,o){let n=new Set(e.filter(r=>r.child_cardinality==="one").map(r=>r.child_id));return[...t].filter(([r,i])=>i.length>1&&n.has(r)).map(([r,i])=>({child_id:r,parent_ids:[...i],legacy_terminal:o.has(r)&&i.every(s=>o.has(s))})).sort((r,i)=>r.child_id.localeCompare(i.child_id))}function Rt(e,t,o){let n=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=n.get(i.child_id)??new Set;s.add(i.parent_id),n.set(i.child_id,s)}let r=[];for(let[i,s]of e){let d=K(s.parent);if(!d||!e.has(d))continue;let c=[...n.get(i)??[]].filter(l=>l!==d).sort();c.length!==0&&r.push({child_id:i,scalar_parent_id:d,dependency_parent_ids:c,legacy_terminal:o.has(i)&&o.has(d)&&c.every(l=>o.has(l))})}return r.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function J(e,t=n=>n==="closed"||n==="canceled",o=x()){let n=We(e),r=Xe(n,o),i=Dt(r),s=new Set([...n].filter(([,c])=>t(c.status)).map(([c])=>c)),d=wt([...n.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:r,cycles:d,cardinality_violations:Tt(r,i.parents_by_child,s),divergences:Rt(n,r,s)}}function Gn(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function Dt(e){let t=new Map,o=new Map;for(let n of e){let r=t.get(n.child_id)??new Set;r.add(n.parent_id),t.set(n.child_id,r);let i=o.get(n.parent_id)??new Set;i.add(n.child_id),o.set(n.parent_id,i)}return{parents_by_child:new Map([...t].map(([n,r])=>[n,[...r].sort()])),children_by_parent:new Map([...o].map(([n,r])=>[n,[...r].sort()]))}}function de(e,t){let o=new Set(t);return e.every(n=>o.has(n))}function Hn(e,t,o,n,r){let i=K(o);if(!i)return;let s=J(e,n,r),d=J(t,n,r),c=d.divergences.find(a=>!s.divergences.some(f=>f.child_id===a.child_id&&f.scalar_parent_id===a.scalar_parent_id&&de(a.dependency_parent_ids,f.dependency_parent_ids)));if(c){let a=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new w(`Hierarchy mutation would assign ${c.child_id} to multiple parents: ${a.join(", ")}.`,v.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:i,target_id:c.child_id,verification_errors:a})}let l=d.cardinality_violations.find(a=>(a.child_id===i||a.parent_ids.includes(i))&&!s.cardinality_violations.some(f=>f.child_id===a.child_id&&de(a.parent_ids,f.parent_ids)));if(l)throw new w(`Hierarchy mutation would assign ${l.child_id} to multiple parents: ${l.parent_ids.join(", ")}.`,v.CONFLICT,{code:"hierarchy_cardinality_created",source_id:i,target_id:l.child_id,verification_errors:l.parent_ids});let u=d.cycles.find(a=>a.item_ids.includes(i)&&!s.cycles.some(f=>de(a.item_ids,f.item_ids)));if(u)throw new w(`Hierarchy mutation would create a cycle: ${u.item_ids.join(" -> ")}.`,v.CONFLICT,{code:"hierarchy_cycle_created",source_id:i,verification_errors:u.item_ids})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();var St="global";function Vn(e){let t=e?.trim();if(t)return I(t)?St:t}function Jn(e,t,o){return Lt(e,t,o)}function Lt(e,t,o){let n=e.trim();return I(o)||R(n)?n:Pe(n,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]="41f814be-ee87-5cae-b674-69c2e7f42655")}catch{}})();function B(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function U(e){let t=B(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function j(e,t,o=!0){let n=B(e);return o&&(I(t)||n!==void 0&&R(n))}function ce(e,t){return j(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function qe(e,t,o,n){return j(e,t)?n.get(e):o.get(e.toLowerCase())}function A(e,t){let o=e.toLowerCase(),n=t.toLowerCase();return o!==n?o<n?-1:1:e!==t?e<t?-1:1:0}function Ot(e){let t=new Map;for(let o of e.dependencies??[]){if(typeof o!="object"||o===null)continue;let n=o,r=B(n.id);if(!r)continue;let i=typeof n.kind=="string"?n.kind:"related",s=`${i}\0${ce(r,n.source_kind)}`,d=t.get(s);d?d.count+=1:t.set(s,{target_id:r,kind:i,count:1})}return t}function At(e,t=o=>o==="closed"||o==="canceled"){let o=[];for(let n of e)if(!(typeof n?.id!="string"||n.id.trim().length===0))for(let r of Ot(n).values())r.count<2||o.push({holder_id:n.id.trim(),target_id:r.target_id,kind:r.kind,occurrences:r.count,holder_status:n.status,legacy_terminal:t(n.status)});return o.sort((n,r)=>{let i=A(n.holder_id,r.holder_id);if(i!==0)return i;let s=A(n.target_id,r.target_id);return s!==0?s:A(n.kind,r.kind)})}function Bt(e,t,o,n,r){if(typeof o!="object"||o===null)return;let i=B(o.id);if(!i||ce(i,o.source_kind)!==ce(t))return;let s=r.resolve(typeof o.kind=="string"?o.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:i,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:n(e.status)}}function Nt(e,t=n=>n==="closed"||n==="canceled",o=x()){let n=new Map;for(let r of e){if(typeof r?.id!="string"||r.id.trim().length===0)continue;let i=B(r.blocked_by);if(i)for(let s of r.dependencies??[]){let d=Bt(r,i,s,t,o);d&&n.set(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`,d)}}return[...n.values()].sort((r,i)=>{let s=A(r.holder_id,i.holder_id);if(s!==0)return s;let d=A(r.target_id,i.target_id);return d!==0?d:A(r.dependency_kind,i.dependency_kind)})}function ae(e,t=o=>o==="closed"||o==="canceled"){let o=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),n=new Set(o.map(c=>c.id.trim().toLowerCase())),r=new Map,i=(c,l,u,a,f)=>{let g=B(l);if(!g||n.has(g.toLowerCase())||j(g,void 0,f))return;let p={holder_id:c.id.trim(),target_id:g,kind:u,source:a,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:g.toLowerCase()==="no-active-blocker"};r.set(`${p.holder_id}::${p.target_id}::${p.kind}::${p.source}`,p)};for(let c of o){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let u=l;I(u.source_kind)||i(c,u.id,typeof u.kind=="string"?u.kind:"related","dependency",!0)}}let s=[...r.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),d=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:d,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}function Mt(e){let t=new Map;for(let o of[...e.active,...e.legacy_terminal]){if(o.no_active_blocker_sentinel)continue;let n=o.target_id.trim(),r=n.toLowerCase();t.has(r)||t.set(r,n)}return[...t.values()].sort((o,n)=>o.localeCompare(n))}function Pt(e){let t=new Map;for(let o of e){let n=U(o.blocked_by);n&&j(n)&&!t.has(n)&&t.set(n,n);for(let r of o.dependencies??[]){if(typeof r!="object"||r===null||!j(r.id,r.source_kind))continue;let i=U(r.id);i&&!t.has(i)&&t.set(i,i)}}return[...t.values()].sort((o,n)=>o.localeCompare(n))}var Ye=new WeakMap;function ro(e){return e.hierarchyIntegrity??Ye.get(e)}function $t(e,t=x()){let o={};for(let n of e)for(let r of n.dependencies??[]){if(typeof r!="object"||r===null)continue;let i=r.kind;if(typeof i!="string")continue;let s=i.trim().toLowerCase().replaceAll("-","_"),d=t.resolve(i);d&&s!==d.kind&&(o[s]=(o[s]??0)+1)}return Object.fromEntries(Object.entries(o).sort(([n],[r])=>n.localeCompare(r)))}function le(e,t,o){let n=o??x(),r=e.filter(p=>typeof p?.id=="string"&&p.id.trim().length>0),i=new Map(r.map(p=>[p.id.trim().toLowerCase(),p.id.trim()])),s=ae(r,t),d=Mt(s);for(let p of d)i.set(p.toLowerCase(),p);let c=Pt(r),l=new Set(i.keys()),u=new Map;for(let p of c){let y=p;for(;l.has(y.toLowerCase());)y=`external:${y}`;u.set(p,y),l.add(y.toLowerCase())}let a=r.map(p=>{let y=U(p.parent),m=U(p.blocked_by),h=(p.dependencies??[]).flatMap(b=>{if(typeof b!="object"||b===null)return[];let k=b,C=U(k.id);return C?[{id:qe(C,k.source_kind,i,u),kind:typeof k.kind=="string"?k.kind:"related"}]:[]});return{id:p.id.trim(),...y?{parent:i.get(y.toLowerCase())}:{},...m?{blocked_by:qe(m,void 0,i,u)}:{},dependencies:h}}),f=J(r,t,n),g={graph:ke.fromItems([...a,...d.map(p=>({id:p})),...c.map(p=>({id:u.get(p)}))],n),details:[...r.map(p=>({id:p.id.trim(),title:p.title,status:p.status,...typeof p.type=="string"&&p.type.trim().length>0?{type:p.type.trim()}:{}})),...d.map(p=>({id:p,title:`[missing] ${p}`,status:"missing"})),...c.map(p=>({id:u.get(p),title:`[external] ${p}`,status:"external"}))],missingIdSet:new Set(d.map(p=>p.toLowerCase())),dangling:s,duplicateRows:At(r,t),orderingContradictions:Nt(r,t,n),legacyAliasCounts:$t(r,n),hierarchyIntegrity:f};return Ye.set(g,f),g}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf5a7b37-5b40-52b4-a19c-18b08de649c4")}catch{}})();function ue(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ao(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!ue(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return ue(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&ue(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var Kt="PmCliError";function lo(e){if(!jt(e)||e.code!=="item_already_exists"||e.exitCode!==v.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function Ut(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=v.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Ve(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let o=new w(e,Ut(t.exitCode??v.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(o,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),o}function jt(e){if(!(e instanceof Error)||e.name!==Kt)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{createHash as zt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e31ef0fb-e803-500b-b1e5-db9edfc880c4")}catch{}})();var Ft=64,Gt=8;function Ht(e,t){let o=(e.dependencies??[]).map(n=>{if(typeof n!="object"||n===null)return"";let r=n;return`${typeof r.kind=="string"?r.kind:"related"}:${typeof r.id=="string"?r.id:""}`}).sort().join(",");return[e.id,e.title,e.status,t(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",o].join("\0")}function Qe(e,t=n=>n==="closed"||n==="canceled",o=T()){let n=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0).map(i=>Ht(i,t)).sort(),r=o.list().map(i=>Ce(i)).sort();return zt("sha256").update(n.join("")).update("").update(r.join("")).digest("hex")}function Je(e,t,o){let n=t??o;if(!Number.isInteger(n)||n<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return n}var fe=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Je("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Ft),this.#n=Je("maxWorkspaces",t.maxWorkspaces,Gt)}lookup(t,o,n){let r=this.#e.get(t),i=!0;(r===void 0||r.fingerprint!==o)&&(r={fingerprint:o,assembly:n(),results:new Map},i=!1,!this.#e.has(t)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,r);let s=r,d=this.#t;return{assembly:s.assembly,assemblyReused:i,fingerprint:o,memoize(c,l){let u=s.results.get(c);if(u!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,u),{value:structuredClone(u),reused:!0};let a=l();return s.results.size>=d&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(a)),{value:a,reused:!1}}}}clear(){this.#e.clear()}},Ze=new fe;function et(){return Ze}function go(){Ze.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b494263-6359-57e9-8f34-b0bdcdeda93f")}catch{}})();var F=1200,Wt=["prerequisite","dependent","ancestor","descendant","provenance","related"],Xt=new TextEncoder;function pe(e,t,o){let n=e??t;if(!Number.isInteger(n)||n<1)throw new TypeError(`Relationship context ${o} must be positive`);return n}function z(e){return Math.max(1,Math.ceil(Xt.encode(JSON.stringify(e)).byteLength/4))}function Q(e,t,o){let n=o.resolve(e.kind);if(n?.ordering){let r=(n.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===r?"prerequisite":"dependent"}if(n?.hierarchy){let r=n.hierarchyDirection==="source_parent"?e.source:e.target;return t===r?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function qt(e,t,o,n){let r=e.filter(i=>i.source===t&&i.target===o||i.target===t&&i.source===o).map(i=>Q(i,o,n));return[...new Set(r)].sort()}function Yt(e){return Wt.find(t=>e.includes(t))}function Vt(e,t,o,n){let r=n.direction??"both",i=n.maxDepth??3;if(!Number.isInteger(i)||i<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([t]),d=[{id:t,distance:0}],c=[],l=0,u=!1;for(let a=0;a<d.length;a+=1){n.signal?.throwIfAborted();let f=d[a];if(f.distance>=i&&u)continue;let g=e.neighborEdges(f.id,{direction:r,kinds:n.kinds,signal:n.signal});if(l+=g.meta.inspectedEdges,f.distance>=i){g.value.some(p=>!s.has(p.id))&&(u=!0);continue}for(let{id:p,edge:y}of g.value){if(s.has(p))continue;s.add(p);let m={id:p,distance:f.distance+1,via:f.id,role:Q(y,p,o)};c.push(m),d.push(m)}}return{rows:c,visitedNodes:d.length,inspectedEdges:l,depthTruncated:u}}function Jt(e,t,o,n){let r={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},i=e.neighborEdges(t,{direction:n.direction??"both",kinds:n.kinds,signal:n.signal}).value;for(let{id:s,edge:d}of i)r[Q(d,s,o)]+=1;return{directEdges:r,directTotal:i.length,rootEdges:i.map(({edge:s})=>s)}}function Qt(e,t,o,n){let r=new Set;for(let i of t){let s=i.source===o?i.target:i.source,d=Q(i,s,n);(d==="prerequisite"||d==="ancestor")&&r.add(s)}return[...e].sort((i,s)=>Number(r.has(s.id))-Number(r.has(i.id))||i.distance-s.distance||i.id.localeCompare(s.id))}function Zt(e,t){let o=e.distance===1?qt(t.rootEdges,t.rootId,e.id,t.registry):[];return{...t.details.get(e.id)??{id:e.id},distance:e.distance,role:o.length>0?Yt(o):e.role,via:e.via,reasons:o.length>0?o:[`${e.role} via ${e.via} (depth ${e.distance})`]}}function en(e){let t=[],o=e.initialTokens,n=0;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=Zt(r,e),s=z(i);if(o+s>e.tokenBudget)break;let d=e.rootEdges.filter(c=>c.source===r.id||c.target===r.id).reduce((c,l)=>c+z(l),0);if(o+n+s+d>e.tokenBudget){if(t.length>0)break}else n+=d;t.push(i),o+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:o}}function tn(e){let t=e.options.kinds?new Set(e.options.kinds.map(i=>e.registry.require(i).kind)):void 0,o=e.graph.edges().filter(i=>{if(!e.included.has(i.source)||!e.included.has(i.target))return!1;if(t===void 0||t.has(i.kind))return!0;let s=e.registry.resolve(i.kind)?.inverse;return s!==void 0&&t.has(s)}).sort((i,s)=>+(s.source===e.rootId||s.target===e.rootId)-+(i.source===e.rootId||i.target===e.rootId)),n=[],r=e.initialTokens;for(let i of o){if(n.length>=e.edgeLimit)break;let s=z(i);r+s>e.tokenBudget||(n.push(i),r+=s)}return{edges:n,usedTokens:r,candidateCount:o.length}}function tt(e,t,o,n={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let r=pe(n.nodeLimit,20,"nodeLimit"),i=pe(n.edgeLimit,40,"edgeLimit"),s=pe(n.tokenBudget,F,"tokenBudget"),d=n.registry??T(),c=new Map(o.map(O=>[O.id,O])),l=c.get(t)??{id:t},{evidence:u=[],...a}=l,f=[...u],g=Vt(e,t,d,n),{rootEdges:p,...y}=Jt(e,t,d,n),m=Qt(g.rows,p,t,d),h=Le("relationship-context",{rootId:t,direction:n.direction??"both",kinds:[...n.kinds??[]].sort(),maxDepth:n.maxDepth??3,ordering:"required-root-evidence-first-v1"}),b=Ae(m,n.cursor,h,({id:O})=>O,"--cursor"),k=m.slice(b),C=z(a)+z(f);if(C>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let E=en({candidates:k,details:c,rootEdges:p,rootId:t,registry:d,nodeLimit:r,tokenBudget:s,initialTokens:C}),{nodes:L}=E,ut=new Set([t,...L.map(({id:O})=>O)]),he=tn({graph:e,rootId:t,included:ut,options:n,registry:d,edgeLimit:i,tokenBudget:s,initialTokens:E.usedTokens}),{edges:Z,usedTokens:ft}=he,G=b+L.length,ee=G<m.length,ye=L.at(-1),te=he.candidateCount-Z.length,_e=g.depthTruncated||ee||te>0,pt={rootId:t,...a.status===void 0?{}:{rootStatus:a.status},...y,discoveredNodes:m.length,returnedNodes:L.length,returnedEdges:Z.length,omittedNodes:m.length-G,omittedEdges:te,evidenceCount:f.length,hasMore:ee};return{root:a,summary:pt,nodes:L,edges:Z,evidence:f,meta:{exact:!0,truncated:_e,completeness:_e?"truncated":"complete",nodeLimit:r,edgeLimit:i,tokenBudget:s,usedTokens:ft,visitedNodes:g.visitedNodes,inspectedEdges:g.inspectedEdges,omittedNodes:m.length-G,omittedEdges:te,...ee&&ye?{nextCursor:Oe(h,ye.id,G-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]="196b7f2d-b09b-5432-b4ef-9cdf82e92731")}catch{}})();var nn=["tree","graph","context"],on=["none","repeated"],rn=["outgoing","incoming","both"],sn=32,dn=200,cn=400,an=16e3;function ln(e){let t=e?.trim().toLowerCase()??"tree";if(nn.includes(t))return t;throw new w(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,v.USAGE)}function N(e,t){if(e===void 0)return;let o=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(o)||o<1)throw new w(`Invalid --${t} value "${e}". Use a positive integer.`,v.USAGE);return o}function ot(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new w(`Invalid --max-depth value "${e}". Use a non-negative integer.`,v.USAGE);return t}function un(e){let t=e?.trim().toLowerCase()??"none";if(on.includes(t))return t;throw new w(`Invalid --collapse value "${e}". Use "none" or "repeated".`,v.USAGE)}function fn(e){let t=e?.trim().toLowerCase()??"both";if(rn.includes(t))return t;throw new w(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,v.USAGE)}function pn(e,t=T()){if(e===void 0)return;let o=(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(o.length===0)return;let n=new Set;for(let r of o){let i=t.resolve(r);if(!i){let s=t.list().map(d=>d.kind).join(", ");throw new w(`Invalid --kind value "${r}". Registered kinds: ${s}.`,v.USAGE)}n.add(i.kind)}return[...n].sort()}function mn(e){if(!e||e.length===0)return[];let t=e.map(({id:n,kind:r})=>({id:n.trim(),kind:r.trim().toLowerCase()})).sort((n,r)=>{let i=n.kind.localeCompare(r.kind);return i!==0?i:n.id.localeCompare(r.id)}),o=new Map;for(let n of t){let r=`${n.kind.toLowerCase()}::${n.id.toLowerCase()}`;o.has(r)||o.set(r,{id:n.id,kind:n.kind})}return[...o.values()]}function gn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:mn(e.dependencies)}}function hn(e){return M(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function yn(e,t,o,n,r,i,s,d,c){for(let l of t.dependencies){let u=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:l.id,kind:l.kind}).length/3));if(d.nodes>=d.nodeLimit){e.truncated=!0,d.reasons.add("node_limit");break}if(d.edges>=d.edgeLimit){e.truncated=!0,d.reasons.add("edge_limit");break}if(d.estimatedTokens+u>=d.tokenBudget){e.truncated=!0,d.reasons.add("token_budget");break}d.edges+=1,d.estimatedTokens+=u,e.dependencies.push(rt(l.id,o,n,r,i,s,d,c+1,l.kind))}}function _n(e,t,o,n,r,i,s,d){return s.estimatedTokens>=s.tokenBudget&&t?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!t||e.cycle?!0:n!==void 0&&d>=n?(t.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):r==="repeated"&&i.has(o)?(e.collapsed=!0,!0):!1}function rt(e,t,o,n,r,i,s,d=0,c){let l=e.trim().toLowerCase(),u=t.get(l),a={id:u?.id??e,title:u?.title,type:u?.type,status:u?.status,via:c,missing:!u,cycle:o.has(l),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=hn(a),_n(a,u,l,n,r,i,s,d))return a;r==="repeated"&&i.add(l);let f=new Set(o);return f.add(l),yn(a,u,t,f,n,r,i,s,d),a}function nt(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function kn(e){let t=new Map,o=new Map,n=[e];for(;n.length>0;){let d=n.pop();t.set(d.id,nt(t.get(d.id),{id:d.id,title:d.title,type:d.type,status:d.status,missing:d.missing}));for(let c of d.dependencies){t.set(c.id,nt(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let l=c.via??"related",u=`${d.id}::${c.id}::${l}`;o.has(u)||o.set(u,{from:d.id,to:c.id,kind:l}),c.cycle||n.push(c)}}let r=[...t.values()].sort((d,c)=>d.id.localeCompare(c.id)),i=[...o.values()].sort((d,c)=>{let l=d.from.localeCompare(c.from);if(l!==0)return l;let u=d.to.localeCompare(c.to);return u!==0?u:d.kind.localeCompare(c.kind)}),s=r.filter(d=>d.missing).map(d=>d.id);return{root_id:e.id,nodes:r,edges:i,missing_ids:s}}function it(e,t,o){let n=new Set,r=new Set,i=new Set,s=new Set,d=[{id:e,depth:0}],c=0;for(;c<d.length;){let l=d[c++],u=l.id.trim().toLowerCase();n.add(u);let a=t.get(u);if(!a){i.add(u);continue}if(!(o!==void 0&&l.depth>=o)&&!s.has(u)){s.add(u);for(let f of a.dependencies)r.add(`${u}::${f.id.trim().toLowerCase()}::${f.kind}`),d.push({id:f.id,depth:l.depth+1})}}return{node_count:n.size,edge_count:r.size,edge_basis:"deduplicated_directed",missing_count:i.size}}function bn(e,t=T()){let o=ot(e.maxDepth),n=N(e.nodeLimit,"node-limit"),r=N(e.edgeLimit,"edge-limit"),i=N(e.tokenBudget,"token-budget"),s=pn(e.kind,t);return{direction:fn(e.direction),...s===void 0?{}:{kinds:s},...o===void 0?{}:{maxDepth:o},...n===void 0?{}:{nodeLimit:n},...r===void 0?{}:{edgeLimit:r},...i===void 0?{}:{tokenBudget:i},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function vn(e,t,o,n){return tt(e.graph,t,e.details.map(r=>r.id===t&&n.length>0?{...r,evidence:n}:r),o)}function me(e,t,o,n){for(let r of o.slice(0,n)){let i=r?.trim();i&&e.push(`${t}:${i}`)}}async function wn(e,t,o,n){let r=await Ue(e,t,o.id_prefix,o.item_format,n);if(!r)return[];let{document:i}=await je(r,{schema:o.schema}),s=i.metadata,d=s.files??[],c=s.tests??[],l=s.docs??[],u=[["files",d.length],["tests",c.length],["docs",l.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(u.every(([,f])=>f===0))return[];let a=[`linked:${u.map(([f,g])=>`${f}=${g}`).join(",")}`];return me(a,"file",d.map(f=>f.path),3),me(a,"test",c.map(f=>f.command??f.path),2),me(a,"doc",l.map(f=>f.path),2),a}function En(e){let{canonicalId:t,context:o,missingCount:n,missingReferences:r,referenceLimit:i,summaryOnly:s}=e;return{id:t,format:"context",node_count:o.nodes.length+1,edge_count:o.edges.length,edge_basis:"deduplicated_directed",missing_count:n,missing_scope:"traversal",missing_reference_count:r.length,...s?{}:{missing_references:r.slice(0,i),context:o}}}function Cn(e){let{row:t,missingReachableSet:o,packetIds:n,filteredKinds:r,registry:i}=e;if(t.no_active_blocker_sentinel||!o.has(t.target_id.trim().toLowerCase())||!n.has(t.holder_id))return!1;if(r===void 0)return!0;let s=i.resolve(t.kind);return s!==void 0&&(r.has(s.kind)||s.inverse!==void 0&&r.has(s.inverse))}function st(e,t){let o=xe(),n=t.commandOptionsOverride??(o?.command==="deps"?o.options:t.commandOptions);return Be("deps",{...n,...t.global,resolvedOutputFormat:t.format},e)}function ge(e,t){let o=st(e,t),n=r=>Me(r,t.format,t.global.lean===!0);return n(t.global.tokenAccounting===!0?Ne(o,n):o)}function dt(e,t,o){let n;for(;;){let r=M(new TextEncoder().encode(ge(e,t)).byteLength);if(r===n)return r;o(r),n=r}}function ct(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function at(e){let{assembly:t,canonicalId:o,contextOptions:n,rootEvidence:r,summaryOnly:i,rendering:s,missingCount:d,missingReferences:c}=e,l=n.edgeLimit??40,u=Math.min(l,c.length),a=n.tokenBudget,f;for(;;){let g=vn(t,o,{...n,...a===void 0?{}:{tokenBudget:a}},r);f??=g.meta.tokenBudget,a??=f;let p=En({canonicalId:o,context:g,missingCount:d,missingReferences:c,referenceLimit:u,summaryOnly:i});if(i){if(M(new TextEncoder().encode(ge(S(p,!0,s.legacyAliasCounts),s)).byteLength)>f)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return p}if(g.meta.tokenBudget=f,g.meta.usedTokens=dt(S(p,!1,s.legacyAliasCounts),s,h=>{g.meta.usedTokens=h}),g.meta.usedTokens<=f)return p;if(u>0){u-=1;continue}let y=a,m=y*f/g.meta.usedTokens;a=Math.min(y-1,Math.max(1,Math.floor(m*.9)))}}function lt(e,t){let o=e.contextOptions,n={...e.rendering.global,outputFormat:e.rendering.format},r=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],i=r.length;r.push(String(t));let s=new Set(["--pm-path","--format","--output-format","--token-budget"]),d={format:"context",tokenBudget:t,kind:o.kinds},c=[["--max-depth","maxDepth",o.maxDepth],["--node-limit","nodeLimit",o.nodeLimit],["--edge-limit","edgeLimit",o.edgeLimit],["--direction","direction",o.direction],["--cursor","cursor",o.cursor],["--output-include","outputInclude",n.outputInclude],["--output-limit","outputLimit",n.outputLimit],["--output-budget","outputBudget",n.outputBudget],["--output-session","outputSession",n.outputSession],["--output-cursor","outputCursor",n.outputCursor]];for(let[a,f,g]of c)g!==void 0&&(r.push(a,String(g)),s.add(a),d[f]=g);for(let a of o.kinds??[])r.push("--kind",a),s.add("--kind");let l=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",n.json],["--lean","lean",n.lean],["--output-row-contract","outputRowContract",n.outputRowContract],["--token-accounting","tokenAccounting",n.tokenAccounting],["--no-extensions","noExtensions",n.noExtensions],["--no-pager","noPager",n.noPager]];for(let[a,f,g]of l)g===!0&&(r.push(a),s.add(a),d[f]=!0);let u=Re.find(a=>a.command==="deps");return Reflect.set(d,Te,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(u.dimensions).flatMap(a=>a.legacy_aliases.flatMap(f=>s.has(f.flag)?[f.flag]:[]))}),De("deps",d),ne(d.summary===!0,d.full===!0,"--summary"),n.outputInclude=d.outputInclude,{args:r,budgetIndex:i,summaryOnly:d.summary===!0,rendering:{...e.rendering,global:n,commandOptionsOverride:d}}}function In(e,t,o){let n={...t.rendering,commandOptionsOverride:{...t.rendering.commandOptionsOverride,tokenBudget:o}},r;try{r=at({...e,contextOptions:{...e.contextOptions,tokenBudget:o},summaryOnly:t.summaryOnly,rootEvidence:t.summaryOnly?[]:e.rootEvidence,rendering:n})}catch(s){if(!ct(s))throw s;return"native_floor"}let i=st(S(r,t.summaryOnly,n.legacyAliasCounts),n);return Se(i)?"output_constraints":"fits"}async function xn(e,t){let o=e.contextOptions.tokenBudget??F,n=lt(e,o),r=(n.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((a,f)=>a+f.id.length+f.title.length+f.status.length+(f.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(n.summaryOnly?[]:e.rootEvidence).reduce((a,f)=>a+f.length,0)),{findContextBudgetRecovery:i}=await import("./context-budget-recovery-5MKOCGY5.js"),s=i({requested:o,initialBudget:F,workUnits:r,probe:a=>In(e,n,a)}),d=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],c=X(d),l=s.feasible_tokens===null?d:[...n.args];s.feasible_tokens!==null&&(l[n.budgetIndex]=String(s.feasible_tokens));let u=X(l);return Ve("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:v.USAGE,cause:t,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(o),required:s.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+s.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[u,c],nextSteps:[u],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:s,suggested_retry_args:l,suggested_retry:u,next_best_command:c,fallback_candidates:[{source:"relationship_summary",command:c,reason:"Inspect bounded counts separately from context rows."}]}}})}async function Tn(e){let{pmRoot:t,assembly:o,canonicalId:n,options:r,rootEvidence:i,summaryOnly:s,rendering:d}=e,c=bn(r,o.graph.registry()),l=o.graph.closure(n,{direction:c.direction,...c.kinds===void 0?{}:{kinds:c.kinds},maxDepth:c.maxDepth??3}),u=l.value.filter(h=>o.missingIdSet.has(h.toLowerCase())),a=new Set(u.map(h=>h.toLowerCase())),f=o.graph.registry(),g=c.kinds?new Set(c.kinds.map(h=>f.require(h).kind)):void 0,p=new Set([n,...l.value]),y=[...o.dangling.active,...o.dangling.legacy_terminal].filter(h=>Cn({row:h,missingReachableSet:a,packetIds:p,filteredKinds:g,registry:f})),m={pmRoot:t,assembly:o,canonicalId:n,contextOptions:c,rootEvidence:i,summaryOnly:s,rendering:d,missingCount:u.length,missingReferences:y};try{return at(m)}catch(h){if(h instanceof w&&h.code==="invalid_query_cursor"){let b=lt({...m,contextOptions:{...c,cursor:void 0},rendering:{...d,global:{...d.global,outputCursor:void 0}}},c.tokenBudget??F),k=X(b.args);throw new w(h.message,h.exitCode,{...h.context,nextSteps:[...h.context.nextSteps,k],recovery:{suggested_retry:k,suggested_retry_args:b.args}})}throw ct(h)?await xn(m,h):h}}function Rn(e){let t=[e],o;for(;t.length>0;){let n=t.pop();n.dependencies.length>0&&(o=n,t.push(...n.dependencies))}return o?(o.dependencies.pop(),o.truncated=!0,!0):!1}function Dn(e,t,o,n,r,i,s){let d=r??sn,c=N(o.nodeLimit,"node-limit")??dn,l=N(o.edgeLimit,"edge-limit")??cn,u=N(o.tokenBudget,"token-budget")??an,a={nodeLimit:c,edgeLimit:l,tokenBudget:u,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=rt(e,n,new Set,d,t==="graph"?"repeated":i,new Set,a),g=it(e,n,void 0),p;for(;;){let y=kn(f),m=a.reasons.size===0?void 0:{reasons:[...a.reasons].sort(),limits:{max_depth:d,node_limit:c,edge_limit:l,token_budget:u},estimated_tokens:0,total_node_count:g.node_count,total_edge_count:g.edge_count,omitted_node_count:Math.max(0,g.node_count-y.nodes.length),omitted_edge_count:Math.max(0,g.edge_count-y.edges.length)},h={id:e,format:t,node_count:y.nodes.length,edge_count:y.edges.length,edge_basis:"deduplicated_directed",missing_count:y.missing_ids.length,...m?{truncation:m}:{}};if(p=t==="tree"?{...h,tree:f}:{...h,graph:y},(p.truncation===void 0?M(new TextEncoder().encode(ge(S(p,!1,s.legacyAliasCounts),s)).byteLength):dt(S(p,!1,s.legacyAliasCounts),s,b=>{p.truncation.estimated_tokens=b}))<=u)return p;if(!Rn(f))return a.reasons.add("token_budget"),p;a.reasons.add("token_budget")}}function S(e,t,o={}){let n={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},r=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:o,projection:{mode:t?"summary":"full",declared_field_groups:[n,...r],included_field_groups:t?[]:[n.name]}}}async function Fo(e,t,o){let n=Ee(process.cwd(),o.path);await Ke(n);let r=ln(t.format),i=ot(t.maxDepth),s=un(t.collapse);ne(t.summary===!0,t.full===!0,"--summary");let d=t.summary===!0,c=await $e(n),l=ve(c,W()),u=await ze(n,c.item_format,l.type_to_folder,void 0,c.schema),a=Ie(c.schema),f=new Map(u.map(m=>[m.id.trim().toLowerCase(),gn(m)])),g=ae(u,m=>D(m,a));for(let m of[...g.active,...g.legacy_terminal]){let h=f.get(m.holder_id.trim().toLowerCase()),b=m.kind.trim().toLowerCase();h&&!h.dependencies.some(k=>k.id.trim().toLowerCase()===m.target_id.trim().toLowerCase()&&k.kind===b)&&h.dependencies.push({id:m.target_id,kind:b})}if(!f.has(e.trim().toLowerCase()))throw new w(`Item ${e} not found`,v.NOT_FOUND);let p=o.outputFormat??(o.json===!0||o.json===void 0&&o.defaultOutputFormat==="json"?"json":"toon");if(r==="context"){let m=f.get(e.trim().toLowerCase()).id,h=d?[]:await wn(n,m,c,l.type_to_folder),b=E=>D(E,a),k=x(),C=et().lookup(n,Qe(u,b,k),()=>le(u,b,k));return S(await Tn({pmRoot:n,assembly:C.assembly,canonicalId:m,options:t,rootEvidence:h,summaryOnly:d,rendering:{format:p,global:o,commandOptions:t,legacyAliasCounts:C.assembly.legacyAliasCounts}}),d,C.assembly.legacyAliasCounts)}let y=Object.fromEntries(Object.entries(le(u,m=>D(m,a)).legacyAliasCounts));return d?S({id:e,format:r,...it(e,f,i)},!0,y):S(Dn(e,r,t,f,i,s,{format:p,global:o,commandOptions:t,legacyAliasCounts:y}),!1,y)}export{re as a,mt as b,$ as c,Y as d,Ge as e,gt as f,ht as g,yt as h,bt as i,Vn as j,Jn as k,Lt as l,x as m,Fn as n,J as o,Gn as p,Dt as q,Hn as r,U as s,At as t,Nt as u,ae as v,Mt as w,ro as x,le as y,ao as z,Kt as A,lo as B,Ve as C,jt as D,Qe as E,fe as F,et as G,go as H,F as I,tt as J,N as K,ot as L,fn as M,pn as N,Fo as O};
2
- //# sourceMappingURL=chunk-6HJCSHBG.js.map
1
+ import{D as Ue,E as je,H as ze,f as Pe}from"./chunk-QH5KMIYZ.js";import{_a as $e,db as Ke,s as P,t as D}from"./chunk-LWJ2X75I.js";import{j as Ie}from"./chunk-22727JYL.js";import{b as R,c as I}from"./chunk-AK2CI2GI.js";import{Dc as X,Fa as Ce,Oc as M,R as T,T as H,Uc as Te,W as ke,Zc as Re,cd as De,ee as Be,fe as Ne,gd as Se,ic as W,jc as xe,ka as be,nd as Le,od as Oe,pe as Me,qa as ve,sa as we,sd as Ae,wa as Ee,xc as ne}from"./chunk-NC5HUGHU.js";import{y as v,z as w}from"./chunk-46KDJH3K.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a319e7d9-e248-573b-bf1f-35217ce49fd0")}catch{}})();function re(e,t){return(t===void 0?void 0:we(e,t))?.execution_role??be[e.trim().toLowerCase()]??"agent"}var ie="blocked_by",Fe="blocks",mt=Object.freeze([ie,Fe]),oe="no-active-blocker";function _(e){return e.trim().toLowerCase()}function q(e,t){return t?`external:${e}`:`local:${_(e)}`}function $(e){let t=new Map,o=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(o.length>0&&_(o)!==oe){let n=R(o);t.set(q(o,n),n?o:_(o))}for(let n of e.dependencies??[]){let r=typeof n.id=="string"?n.id.trim():"";if(H(n.kind)===ie&&r.length>0&&_(r)!==oe){let i=R(r)||I(n.source_kind);t.set(q(r,i),i?r:_(r))}}return[...t.values()].sort((n,r)=>n.localeCompare(r))}function Y(e){let t=new Map;for(let o of e){let n=_(o.id);n.length!==0&&t.set(n,new Set($(o)))}for(let o of e){let n=_(o.id);if(n.length!==0)for(let r of o.dependencies??[]){let i=H(r.kind)===Fe&&typeof r.id=="string"?_(r.id):"";if(i.length===0||i===oe)continue;let s=t.get(i)??new Set;s.add(n),t.set(i,s)}}return new Map([...t].map(([o,n])=>[o,[...n].sort((r,i)=>r.localeCompare(i))]))}function Ge(e,t){let o=_(e.id);return o.length>0?Y(t).get(o)??$(e):$(e)}function se(e,t,o,n){let r=e,i=typeof r.id=="string"?n?.get(_(r.id))??Ge(r,[...t.values()]):$(e),s=new Set((e.dependencies??[]).filter(d=>H(d.kind)===ie&&I(d.source_kind)&&typeof d.id=="string"&&d.id.trim().length>0).map(d=>q(d.id.trim(),!0)));return i.map(d=>{if(R(d)||s.has(q(d,!0)))return{id:d,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};let c=t.get(_(d));return c?{id:d,title:c.title,status:c.status,resolved:D(c.status,o)}:{id:d,title:null,status:null,resolved:!1}})}function gt(e,t,o){return se(e,t,o)}function ht(e,t){let o=new Map(e.map(s=>[_(s.id),s])),n=Y(e),r=new Set([...He(t),...t.blocked_statuses]),i=new Set;for(let s of e){let d=P(s.status,t);r.has(d)&&(t.blocked_statuses.has(d)||se(s,o,t,n).some(c=>!c.resolved))&&i.add(_(s.id))}return i}function yt(e,t,o={},n){let r=[...e.ready,...e.decisions,...e.gates];o.includeContainers===!0&&r.push(...e.containers.filter(s=>s.open_blockers.length===0&&!t.blocked_statuses.has(P(s.item.status,t))));let i={ready:[],decisions:[],gates:[]};for(let s of r){let d=re(s.item.type,n);d==="human"&&o.includeDecisions!==!0?i.decisions.push(s):d==="gate"&&o.includeGates!==!0?i.gates.push(s):i.ready.push(s)}return i}function He(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function _t(e,t,o){let n=[_(e)],r=new Set;for(;n.length>0;){let i=n.pop();if(!r.has(i)){r.add(i);for(let s of t.get(i)??[]){if(!D(s.status,o))return!0;n.push(_(s.id))}}}return!1}function kt(e){let t=new Map,o=new Map,n=new Map,r=Y(e);for(let i of e){t.set(_(i.id),i);let s=typeof i.parent=="string"?i.parent.trim():"";if(s.length>0){let d=_(s),c=o.get(d)??[];c.push(i),o.set(d,c)}for(let d of r.get(_(i.id))){let c=_(d),l=n.get(c)??[];l.push(i.id),n.set(c,l)}}return{itemsById:t,childrenByParent:o,blockedByReverse:n,blockerIdsByItem:r}}function bt(e,t,o,n){let{itemsById:r,childrenByParent:i,blockedByReverse:s,blockerIdsByItem:d}=kt(t),c=new Set([...He(o),...o.blocked_statuses]),l=new Set(t.filter(m=>!D(m.status,o)).map(m=>_(m.id))),u=[],a=[],f=[],g=[],p=[],y=0;for(let m of e){if(!c.has(P(m.status,o)))continue;y+=1;let h=se(m,r,o,d).filter(E=>!E.resolved),b=(s.get(_(m.id))??[]).filter(E=>l.has(_(E))).sort((E,L)=>E.localeCompare(L)),k={item:m,open_blockers:h,unblocks:b};if(_t(m.id,i,o)){f.push(k);continue}let C=o.blocked_statuses.has(P(m.status,o));if(h.length===0&&!C){let E=re(m.type,n);E==="human"?g.push(k):E==="gate"?p.push(k):u.push(k)}else a.push(k)}return{ready:u,blocked:a,containers:f,decisions:g,gates:p,active_count:y,container_count:f.length}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ae1c56b3-148d-502d-9450-e807fdfab4da")}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]="283dfa35-9a8e-524c-b6e2-d433d51215ca")}catch{}})();function x(){let e=T();for(let t of W()?.relationship_kinds??[])for(let o of t.definitions)e.register(o);return e}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="8b57e560-4ac4-53b6-9fb1-eebb1f30562a")}catch{}})();function K(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return t.length>0?t:void 0}function V(e){return[e.parent_id,e.child_id,e.source,e.kind,e.holder_id,e.target_id??""].join("\0")}function vt(e,t){let o=new Set,n=[];for(let r of[...e].sort()){if(o.has(r))continue;o.add(r);let i=[{nodeId:r,children:[...t.get(r)??[]].sort(),nextChild:0}];for(;i.length>0;){let s=i.at(-1),d=s.children[s.nextChild];d===void 0?(n.push(s.nodeId),i.pop()):(s.nextChild+=1,o.has(d)||(o.add(d),i.push({nodeId:d,children:[...t.get(d)??[]].sort(),nextChild:0})))}}return n}function wt(e,t){let o=[...e].sort(),n=vt(o,t),r=new Set,i=Et(o,t),s=[];for(let d of n.reverse()){if(r.has(d))continue;let c=Ct(d,i,r);(c.length>1||t.get(c[0])?.has(c[0]))&&s.push(c)}return s.sort((d,c)=>d.join("\0").localeCompare(c.join("\0")))}function Et(e,t){let o=new Map(e.map(n=>[n,new Set]));for(let[n,r]of t)for(let i of r)o.get(i)?.add(n);return o}function Ct(e,t,o){let n=[],r=[e];for(o.add(e);r.length>0;){let i=r.pop();n.push(i);for(let s of[...t.get(i)].sort())o.has(s)||(o.add(s),r.push(s))}return n.sort()}function We(e){let t=new Map;for(let o of e){let n=K(o?.id);n&&!t.has(n)&&t.set(n,o)}return t}function It(e,t,o){let n=K(t.parent);if(!(!n||!o.has(n)))return{parent_id:n,child_id:e,source:"scalar_parent",kind:"parent",holder_id:e,child_cardinality:"one"}}function xt(e,t,o,n){let r=K(t?.id),i=n.resolve(t?.kind);if(!r||!o.has(r)||!i?.hierarchy)return;let s=i.hierarchyDirection==="source_parent";return{parent_id:s?e:r,child_id:s?r:e,source:"dependency",kind:i.kind,holder_id:e,target_id:r,child_cardinality:s?i.incoming:i.outgoing}}function Xe(e,t){let o=new Map;for(let[n,r]of e){let i=It(n,r,e);i&&o.set(V(i),i);for(let s of r.dependencies??[]){let d=xt(n,s,e,t);d&&o.set(V(d),d)}}return[...o.values()].sort((n,r)=>V(n).localeCompare(V(r)))}function Fn(e,t=x()){return Xe(We(e),t)}function Tt(e,t,o){let n=new Set(e.filter(r=>r.child_cardinality==="one").map(r=>r.child_id));return[...t].filter(([r,i])=>i.length>1&&n.has(r)).map(([r,i])=>({child_id:r,parent_ids:[...i],legacy_terminal:o.has(r)&&i.every(s=>o.has(s))})).sort((r,i)=>r.child_id.localeCompare(i.child_id))}function Rt(e,t,o){let n=new Map;for(let i of t){if(i.source!=="dependency")continue;let s=n.get(i.child_id)??new Set;s.add(i.parent_id),n.set(i.child_id,s)}let r=[];for(let[i,s]of e){let d=K(s.parent);if(!d||!e.has(d))continue;let c=[...n.get(i)??[]].filter(l=>l!==d).sort();c.length!==0&&r.push({child_id:i,scalar_parent_id:d,dependency_parent_ids:c,legacy_terminal:o.has(i)&&o.has(d)&&c.every(l=>o.has(l))})}return r.sort((i,s)=>i.child_id.localeCompare(s.child_id))}function J(e,t=n=>n==="closed"||n==="canceled",o=x()){let n=We(e),r=Xe(n,o),i=Dt(r),s=new Set([...n].filter(([,c])=>t(c.status)).map(([c])=>c)),d=wt([...n.keys()],new Map([...i.children_by_parent].map(([c,l])=>[c,new Set(l)]))).map(c=>({item_ids:c,legacy_terminal:c.every(l=>s.has(l))}));return{relations:r,cycles:d,cardinality_violations:Tt(r,i.parents_by_child,s),divergences:Rt(n,r,s)}}function Gn(e){return e.source==="scalar_parent"?`${e.parent_id} -> ${e.child_id} (scalar parent on ${e.holder_id})`:`${e.parent_id} -> ${e.child_id} (${e.kind} dependency on ${e.holder_id})`}function Dt(e){let t=new Map,o=new Map;for(let n of e){let r=t.get(n.child_id)??new Set;r.add(n.parent_id),t.set(n.child_id,r);let i=o.get(n.parent_id)??new Set;i.add(n.child_id),o.set(n.parent_id,i)}return{parents_by_child:new Map([...t].map(([n,r])=>[n,[...r].sort()])),children_by_parent:new Map([...o].map(([n,r])=>[n,[...r].sort()]))}}function de(e,t){let o=new Set(t);return e.every(n=>o.has(n))}function Hn(e,t,o,n,r){let i=K(o);if(!i)return;let s=J(e,n,r),d=J(t,n,r),c=d.divergences.find(a=>!s.divergences.some(f=>f.child_id===a.child_id&&f.scalar_parent_id===a.scalar_parent_id&&de(a.dependency_parent_ids,f.dependency_parent_ids)));if(c){let a=[c.scalar_parent_id,...c.dependency_parent_ids].sort();throw new w(`Hierarchy mutation would assign ${c.child_id} to multiple parents: ${a.join(", ")}.`,v.CONFLICT,{code:"hierarchy_parent_divergence_created",source_id:i,target_id:c.child_id,verification_errors:a})}let l=d.cardinality_violations.find(a=>(a.child_id===i||a.parent_ids.includes(i))&&!s.cardinality_violations.some(f=>f.child_id===a.child_id&&de(a.parent_ids,f.parent_ids)));if(l)throw new w(`Hierarchy mutation would assign ${l.child_id} to multiple parents: ${l.parent_ids.join(", ")}.`,v.CONFLICT,{code:"hierarchy_cardinality_created",source_id:i,target_id:l.child_id,verification_errors:l.parent_ids});let u=d.cycles.find(a=>a.item_ids.includes(i)&&!s.cycles.some(f=>de(a.item_ids,f.item_ids)));if(u)throw new w(`Hierarchy mutation would create a cycle: ${u.item_ids.join(" -> ")}.`,v.CONFLICT,{code:"hierarchy_cycle_created",source_id:i,verification_errors:u.item_ids})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();var St="global";function Vn(e){let t=e?.trim();if(t)return I(t)?St:t}function Jn(e,t,o){return Lt(e,t,o)}function Lt(e,t,o){let n=e.trim();return I(o)||R(n)?n:Pe(n,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]="41f814be-ee87-5cae-b674-69c2e7f42655")}catch{}})();function B(e){if(typeof e!="string")return;let t=e.trim();if(!(!t||["none","null","n/a","na"].includes(t.toLowerCase())))return t}function U(e){let t=B(e);return t?.toLowerCase()==="no-active-blocker"?void 0:t}function j(e,t,o=!0){let n=B(e);return o&&(I(t)||n!==void 0&&R(n))}function ce(e,t){return j(e,t)?`external\0${e}`:`local\0${e.toLowerCase()}`}function qe(e,t,o,n){return j(e,t)?n.get(e):o.get(e.toLowerCase())}function A(e,t){let o=e.toLowerCase(),n=t.toLowerCase();return o!==n?o<n?-1:1:e!==t?e<t?-1:1:0}function Ot(e){let t=new Map;for(let o of e.dependencies??[]){if(typeof o!="object"||o===null)continue;let n=o,r=B(n.id);if(!r)continue;let i=typeof n.kind=="string"?n.kind:"related",s=`${i}\0${ce(r,n.source_kind)}`,d=t.get(s);d?d.count+=1:t.set(s,{target_id:r,kind:i,count:1})}return t}function At(e,t=o=>o==="closed"||o==="canceled"){let o=[];for(let n of e)if(!(typeof n?.id!="string"||n.id.trim().length===0))for(let r of Ot(n).values())r.count<2||o.push({holder_id:n.id.trim(),target_id:r.target_id,kind:r.kind,occurrences:r.count,holder_status:n.status,legacy_terminal:t(n.status)});return o.sort((n,r)=>{let i=A(n.holder_id,r.holder_id);if(i!==0)return i;let s=A(n.target_id,r.target_id);return s!==0?s:A(n.kind,r.kind)})}function Bt(e,t,o,n,r){if(typeof o!="object"||o===null)return;let i=B(o.id);if(!i||ce(i,o.source_kind)!==ce(t))return;let s=r.resolve(typeof o.kind=="string"?o.kind:"related");if(!(s?.ordering!==!0||(s.precedence??"source_before_target")!=="source_before_target"))return{holder_id:e.id.trim(),target_id:i,dependency_kind:s.kind,holder_status:e.status,legacy_terminal:n(e.status)}}function Nt(e,t=n=>n==="closed"||n==="canceled",o=x()){let n=new Map;for(let r of e){if(typeof r?.id!="string"||r.id.trim().length===0)continue;let i=B(r.blocked_by);if(i)for(let s of r.dependencies??[]){let d=Bt(r,i,s,t,o);d&&n.set(`${d.holder_id.toLowerCase()}\0${d.target_id.toLowerCase()}\0${d.dependency_kind}`,d)}}return[...n.values()].sort((r,i)=>{let s=A(r.holder_id,i.holder_id);if(s!==0)return s;let d=A(r.target_id,i.target_id);return d!==0?d:A(r.dependency_kind,i.dependency_kind)})}function ae(e,t=o=>o==="closed"||o==="canceled"){let o=e.filter(c=>typeof c?.id=="string"&&c.id.trim().length>0),n=new Set(o.map(c=>c.id.trim().toLowerCase())),r=new Map,i=(c,l,u,a,f)=>{let g=B(l);if(!g||n.has(g.toLowerCase())||j(g,void 0,f))return;let p={holder_id:c.id.trim(),target_id:g,kind:u,source:a,holder_status:c.status,legacy_terminal:t(c.status),no_active_blocker_sentinel:g.toLowerCase()==="no-active-blocker"};r.set(`${p.holder_id}::${p.target_id}::${p.kind}::${p.source}`,p)};for(let c of o){i(c,c.parent,"parent","parent",!1),i(c,c.blocked_by,"blocked_by","blocked_by",!0);for(let l of c.dependencies??[]){if(typeof l!="object"||l===null)continue;let u=l;I(u.source_kind)||i(c,u.id,typeof u.kind=="string"?u.kind:"related","dependency",!0)}}let s=[...r.values()].sort((c,l)=>c.holder_id.localeCompare(l.holder_id)||c.target_id.localeCompare(l.target_id)||c.kind.localeCompare(l.kind)||c.source.localeCompare(l.source)),d=s.filter(c=>c.legacy_terminal);return{active:s.filter(c=>!c.legacy_terminal),legacy_terminal:d,no_active_blocker_sentinels:s.filter(c=>c.no_active_blocker_sentinel)}}function Mt(e){let t=new Map;for(let o of[...e.active,...e.legacy_terminal]){if(o.no_active_blocker_sentinel)continue;let n=o.target_id.trim(),r=n.toLowerCase();t.has(r)||t.set(r,n)}return[...t.values()].sort((o,n)=>o.localeCompare(n))}function Pt(e){let t=new Map;for(let o of e){let n=U(o.blocked_by);n&&j(n)&&!t.has(n)&&t.set(n,n);for(let r of o.dependencies??[]){if(typeof r!="object"||r===null||!j(r.id,r.source_kind))continue;let i=U(r.id);i&&!t.has(i)&&t.set(i,i)}}return[...t.values()].sort((o,n)=>o.localeCompare(n))}var Ye=new WeakMap;function ro(e){return e.hierarchyIntegrity??Ye.get(e)}function $t(e,t=x()){let o={};for(let n of e)for(let r of n.dependencies??[]){if(typeof r!="object"||r===null)continue;let i=r.kind;if(typeof i!="string")continue;let s=i.trim().toLowerCase().replaceAll("-","_"),d=t.resolve(i);d&&s!==d.kind&&(o[s]=(o[s]??0)+1)}return Object.fromEntries(Object.entries(o).sort(([n],[r])=>n.localeCompare(r)))}function le(e,t,o){let n=o??x(),r=e.filter(p=>typeof p?.id=="string"&&p.id.trim().length>0),i=new Map(r.map(p=>[p.id.trim().toLowerCase(),p.id.trim()])),s=ae(r,t),d=Mt(s);for(let p of d)i.set(p.toLowerCase(),p);let c=Pt(r),l=new Set(i.keys()),u=new Map;for(let p of c){let y=p;for(;l.has(y.toLowerCase());)y=`external:${y}`;u.set(p,y),l.add(y.toLowerCase())}let a=r.map(p=>{let y=U(p.parent),m=U(p.blocked_by),h=(p.dependencies??[]).flatMap(b=>{if(typeof b!="object"||b===null)return[];let k=b,C=U(k.id);return C?[{id:qe(C,k.source_kind,i,u),kind:typeof k.kind=="string"?k.kind:"related"}]:[]});return{id:p.id.trim(),...y?{parent:i.get(y.toLowerCase())}:{},...m?{blocked_by:qe(m,void 0,i,u)}:{},dependencies:h}}),f=J(r,t,n),g={graph:ke.fromItems([...a,...d.map(p=>({id:p})),...c.map(p=>({id:u.get(p)}))],n),details:[...r.map(p=>({id:p.id.trim(),title:p.title,status:p.status,...typeof p.type=="string"&&p.type.trim().length>0?{type:p.type.trim()}:{}})),...d.map(p=>({id:p,title:`[missing] ${p}`,status:"missing"})),...c.map(p=>({id:u.get(p),title:`[external] ${p}`,status:"external"}))],missingIdSet:new Set(d.map(p=>p.toLowerCase())),dangling:s,duplicateRows:At(r,t),orderingContradictions:Nt(r,t,n),legacyAliasCounts:$t(r,n),hierarchyIntegrity:f};return Ye.set(g,f),g}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="cf5a7b37-5b40-52b4-a19c-18b08de649c4")}catch{}})();function ue(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function ao(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!ue(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return ue(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&ue(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var Kt="PmCliError";function lo(e){if(!jt(e)||e.code!=="item_already_exists"||e.exitCode!==v.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function Ut(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=v.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function Ve(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let o=new w(e,Ut(t.exitCode??v.USAGE),t.context??{});return"cause"in t&&Object.defineProperty(o,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),o}function jt(e){if(!(e instanceof Error)||e.name!==Kt)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)}import{createHash as zt}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e31ef0fb-e803-500b-b1e5-db9edfc880c4")}catch{}})();var Ft=64,Gt=8;function Ht(e,t){let o=(e.dependencies??[]).map(n=>{if(typeof n!="object"||n===null)return"";let r=n;return`${typeof r.kind=="string"?r.kind:"related"}:${typeof r.id=="string"?r.id:""}`}).sort().join(",");return[e.id,e.title,e.status,t(e.status)?"1":"0",typeof e.type=="string"?e.type.trim():"",e.parent??"",e.blocked_by??"",o].join("\0")}function Qe(e,t=n=>n==="closed"||n==="canceled",o=T()){let n=e.filter(i=>typeof i?.id=="string"&&i.id.trim().length>0).map(i=>Ht(i,t)).sort(),r=o.list().map(i=>Ce(i)).sort();return zt("sha256").update(n.join("")).update("").update(r.join("")).digest("hex")}function Je(e,t,o){let n=t??o;if(!Number.isInteger(n)||n<1)throw new TypeError(`Invalid ${e} bound: ${String(t)}`);return n}var fe=class{#e=new Map;#t;#n;constructor(t={}){this.#t=Je("maxResultsPerWorkspace",t.maxResultsPerWorkspace,Ft),this.#n=Je("maxWorkspaces",t.maxWorkspaces,Gt)}lookup(t,o,n){let r=this.#e.get(t),i=!0;(r===void 0||r.fingerprint!==o)&&(r={fingerprint:o,assembly:n(),results:new Map},i=!1,!this.#e.has(t)&&this.#e.size>=this.#n&&this.#e.delete(this.#e.keys().next().value)),this.#e.delete(t),this.#e.set(t,r);let s=r,d=this.#t;return{assembly:s.assembly,assemblyReused:i,fingerprint:o,memoize(c,l){let u=s.results.get(c);if(u!==void 0||s.results.has(c))return s.results.delete(c),s.results.set(c,u),{value:structuredClone(u),reused:!0};let a=l();return s.results.size>=d&&s.results.delete(s.results.keys().next().value),s.results.set(c,structuredClone(a)),{value:a,reused:!1}}}}clear(){this.#e.clear()}},Ze=new fe;function et(){return Ze}function go(){Ze.clear()}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3b494263-6359-57e9-8f34-b0bdcdeda93f")}catch{}})();var F=1200,Wt=["prerequisite","dependent","ancestor","descendant","provenance","related"],Xt=new TextEncoder;function pe(e,t,o){let n=e??t;if(!Number.isInteger(n)||n<1)throw new TypeError(`Relationship context ${o} must be positive`);return n}function z(e){return Math.max(1,Math.ceil(Xt.encode(JSON.stringify(e)).byteLength/4))}function Q(e,t,o){let n=o.resolve(e.kind);if(n?.ordering){let r=(n.precedence??"source_before_target")==="source_before_target"?e.source:e.target;return t===r?"prerequisite":"dependent"}if(n?.hierarchy){let r=n.hierarchyDirection==="source_parent"?e.source:e.target;return t===r?"ancestor":"descendant"}return e.kind==="discovered_from"||e.kind==="incident_from"?"provenance":"related"}function qt(e,t,o,n){let r=e.filter(i=>i.source===t&&i.target===o||i.target===t&&i.source===o).map(i=>Q(i,o,n));return[...new Set(r)].sort()}function Yt(e){return Wt.find(t=>e.includes(t))}function Vt(e,t,o,n){let r=n.direction??"both",i=n.maxDepth??3;if(!Number.isInteger(i)||i<0)throw new TypeError("Relationship context maxDepth must be non-negative");let s=new Set([t]),d=[{id:t,distance:0}],c=[],l=0,u=!1;for(let a=0;a<d.length;a+=1){n.signal?.throwIfAborted();let f=d[a];if(f.distance>=i&&u)continue;let g=e.neighborEdges(f.id,{direction:r,kinds:n.kinds,signal:n.signal});if(l+=g.meta.inspectedEdges,f.distance>=i){g.value.some(p=>!s.has(p.id))&&(u=!0);continue}for(let{id:p,edge:y}of g.value){if(s.has(p))continue;s.add(p);let m={id:p,distance:f.distance+1,via:f.id,role:Q(y,p,o)};c.push(m),d.push(m)}}return{rows:c,visitedNodes:d.length,inspectedEdges:l,depthTruncated:u}}function Jt(e,t,o,n){let r={prerequisite:0,dependent:0,ancestor:0,descendant:0,provenance:0,related:0},i=e.neighborEdges(t,{direction:n.direction??"both",kinds:n.kinds,signal:n.signal}).value;for(let{id:s,edge:d}of i)r[Q(d,s,o)]+=1;return{directEdges:r,directTotal:i.length,rootEdges:i.map(({edge:s})=>s)}}function Qt(e,t,o,n){let r=new Set;for(let i of t){let s=i.source===o?i.target:i.source,d=Q(i,s,n);(d==="prerequisite"||d==="ancestor")&&r.add(s)}return[...e].sort((i,s)=>Number(r.has(s.id))-Number(r.has(i.id))||i.distance-s.distance||i.id.localeCompare(s.id))}function Zt(e,t){let o=e.distance===1?qt(t.rootEdges,t.rootId,e.id,t.registry):[];return{...t.details.get(e.id)??{id:e.id},distance:e.distance,role:o.length>0?Yt(o):e.role,via:e.via,reasons:o.length>0?o:[`${e.role} via ${e.via} (depth ${e.distance})`]}}function en(e){let t=[],o=e.initialTokens,n=0;for(let r of e.candidates){if(t.length>=e.nodeLimit)break;let i=Zt(r,e),s=z(i);if(o+s>e.tokenBudget)break;let d=e.rootEdges.filter(c=>c.source===r.id||c.target===r.id).reduce((c,l)=>c+z(l),0);if(o+n+s+d>e.tokenBudget){if(t.length>0)break}else n+=d;t.push(i),o+=s}if(e.candidates.length>0&&t.length===0)throw new TypeError("Relationship context tokenBudget cannot fit one node");return{nodes:t,usedTokens:o}}function tn(e){let t=e.options.kinds?new Set(e.options.kinds.map(i=>e.registry.require(i).kind)):void 0,o=e.graph.edges().filter(i=>{if(!e.included.has(i.source)||!e.included.has(i.target))return!1;if(t===void 0||t.has(i.kind))return!0;let s=e.registry.resolve(i.kind)?.inverse;return s!==void 0&&t.has(s)}).sort((i,s)=>+(s.source===e.rootId||s.target===e.rootId)-+(i.source===e.rootId||i.target===e.rootId)),n=[],r=e.initialTokens;for(let i of o){if(n.length>=e.edgeLimit)break;let s=z(i);r+s>e.tokenBudget||(n.push(i),r+=s)}return{edges:n,usedTokens:r,candidateCount:o.length}}function tt(e,t,o,n={}){if(!e.nodes().includes(t))throw new TypeError(`Relationship node not found: ${t}`);let r=pe(n.nodeLimit,20,"nodeLimit"),i=pe(n.edgeLimit,40,"edgeLimit"),s=pe(n.tokenBudget,F,"tokenBudget"),d=n.registry??T(),c=new Map(o.map(O=>[O.id,O])),l=c.get(t)??{id:t},{evidence:u=[],...a}=l,f=[...u],g=Vt(e,t,d,n),{rootEdges:p,...y}=Jt(e,t,d,n),m=Qt(g.rows,p,t,d),h=Le("relationship-context",{rootId:t,direction:n.direction??"both",kinds:[...n.kinds??[]].sort(),maxDepth:n.maxDepth??3,ordering:"required-root-evidence-first-v1"}),b=Ae(m,n.cursor,h,({id:O})=>O,"--cursor"),k=m.slice(b),C=z(a)+z(f);if(C>s)throw new TypeError("Relationship context tokenBudget cannot fit root and evidence");let E=en({candidates:k,details:c,rootEdges:p,rootId:t,registry:d,nodeLimit:r,tokenBudget:s,initialTokens:C}),{nodes:L}=E,ut=new Set([t,...L.map(({id:O})=>O)]),he=tn({graph:e,rootId:t,included:ut,options:n,registry:d,edgeLimit:i,tokenBudget:s,initialTokens:E.usedTokens}),{edges:Z,usedTokens:ft}=he,G=b+L.length,ee=G<m.length,ye=L.at(-1),te=he.candidateCount-Z.length,_e=g.depthTruncated||ee||te>0,pt={rootId:t,...a.status===void 0?{}:{rootStatus:a.status},...y,discoveredNodes:m.length,returnedNodes:L.length,returnedEdges:Z.length,omittedNodes:m.length-G,omittedEdges:te,evidenceCount:f.length,hasMore:ee};return{root:a,summary:pt,nodes:L,edges:Z,evidence:f,meta:{exact:!0,truncated:_e,completeness:_e?"truncated":"complete",nodeLimit:r,edgeLimit:i,tokenBudget:s,usedTokens:ft,visitedNodes:g.visitedNodes,inspectedEdges:g.inspectedEdges,omittedNodes:m.length-G,omittedEdges:te,...ee&&ye?{nextCursor:Oe(h,ye.id,G-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]="196b7f2d-b09b-5432-b4ef-9cdf82e92731")}catch{}})();var nn=["tree","graph","context"],on=["none","repeated"],rn=["outgoing","incoming","both"],sn=32,dn=200,cn=400,an=16e3;function ln(e){let t=e?.trim().toLowerCase()??"tree";if(nn.includes(t))return t;throw new w(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,v.USAGE)}function N(e,t){if(e===void 0)return;let o=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(o)||o<1)throw new w(`Invalid --${t} value "${e}". Use a positive integer.`,v.USAGE);return o}function ot(e){if(e===void 0)return;let t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new w(`Invalid --max-depth value "${e}". Use a non-negative integer.`,v.USAGE);return t}function un(e){let t=e?.trim().toLowerCase()??"none";if(on.includes(t))return t;throw new w(`Invalid --collapse value "${e}". Use "none" or "repeated".`,v.USAGE)}function fn(e){let t=e?.trim().toLowerCase()??"both";if(rn.includes(t))return t;throw new w(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,v.USAGE)}function pn(e,t=T()){if(e===void 0)return;let o=(Array.isArray(e)?e:[e]).flatMap(r=>r.split(",")).map(r=>r.trim()).filter(r=>r.length>0);if(o.length===0)return;let n=new Set;for(let r of o){let i=t.resolve(r);if(!i){let s=t.list().map(d=>d.kind).join(", ");throw new w(`Invalid --kind value "${r}". Registered kinds: ${s}.`,v.USAGE)}n.add(i.kind)}return[...n].sort()}function mn(e){if(!e||e.length===0)return[];let t=e.map(({id:n,kind:r})=>({id:n.trim(),kind:r.trim().toLowerCase()})).sort((n,r)=>{let i=n.kind.localeCompare(r.kind);return i!==0?i:n.id.localeCompare(r.id)}),o=new Map;for(let n of t){let r=`${n.kind.toLowerCase()}::${n.id.toLowerCase()}`;o.has(r)||o.set(r,{id:n.id,kind:n.kind})}return[...o.values()]}function gn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:mn(e.dependencies)}}function hn(e){return M(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function yn(e,t,o,n,r,i,s,d,c){for(let l of t.dependencies){let u=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:l.id,kind:l.kind}).length/3));if(d.nodes>=d.nodeLimit){e.truncated=!0,d.reasons.add("node_limit");break}if(d.edges>=d.edgeLimit){e.truncated=!0,d.reasons.add("edge_limit");break}if(d.estimatedTokens+u>=d.tokenBudget){e.truncated=!0,d.reasons.add("token_budget");break}d.edges+=1,d.estimatedTokens+=u,e.dependencies.push(rt(l.id,o,n,r,i,s,d,c+1,l.kind))}}function _n(e,t,o,n,r,i,s,d){return s.estimatedTokens>=s.tokenBudget&&t?.dependencies.length?(e.truncated=!0,s.reasons.add("token_budget"),!0):!t||e.cycle?!0:n!==void 0&&d>=n?(t.dependencies.length>0&&(e.truncated=!0,s.reasons.add("max_depth")),!0):r==="repeated"&&i.has(o)?(e.collapsed=!0,!0):!1}function rt(e,t,o,n,r,i,s,d=0,c){let l=e.trim().toLowerCase(),u=t.get(l),a={id:u?.id??e,title:u?.title,type:u?.type,status:u?.status,via:c,missing:!u,cycle:o.has(l),dependencies:[]};if(s.nodes+=1,s.estimatedTokens+=hn(a),_n(a,u,l,n,r,i,s,d))return a;r==="repeated"&&i.add(l);let f=new Set(o);return f.add(l),yn(a,u,t,f,n,r,i,s,d),a}function nt(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function kn(e){let t=new Map,o=new Map,n=[e];for(;n.length>0;){let d=n.pop();t.set(d.id,nt(t.get(d.id),{id:d.id,title:d.title,type:d.type,status:d.status,missing:d.missing}));for(let c of d.dependencies){t.set(c.id,nt(t.get(c.id),{id:c.id,title:c.title,type:c.type,status:c.status,missing:c.missing}));let l=c.via??"related",u=`${d.id}::${c.id}::${l}`;o.has(u)||o.set(u,{from:d.id,to:c.id,kind:l}),c.cycle||n.push(c)}}let r=[...t.values()].sort((d,c)=>d.id.localeCompare(c.id)),i=[...o.values()].sort((d,c)=>{let l=d.from.localeCompare(c.from);if(l!==0)return l;let u=d.to.localeCompare(c.to);return u!==0?u:d.kind.localeCompare(c.kind)}),s=r.filter(d=>d.missing).map(d=>d.id);return{root_id:e.id,nodes:r,edges:i,missing_ids:s}}function it(e,t,o){let n=new Set,r=new Set,i=new Set,s=new Set,d=[{id:e,depth:0}],c=0;for(;c<d.length;){let l=d[c++],u=l.id.trim().toLowerCase();n.add(u);let a=t.get(u);if(!a){i.add(u);continue}if(!(o!==void 0&&l.depth>=o)&&!s.has(u)){s.add(u);for(let f of a.dependencies)r.add(`${u}::${f.id.trim().toLowerCase()}::${f.kind}`),d.push({id:f.id,depth:l.depth+1})}}return{node_count:n.size,edge_count:r.size,edge_basis:"deduplicated_directed",missing_count:i.size}}function bn(e,t=T()){let o=ot(e.maxDepth),n=N(e.nodeLimit,"node-limit"),r=N(e.edgeLimit,"edge-limit"),i=N(e.tokenBudget,"token-budget"),s=pn(e.kind,t);return{direction:fn(e.direction),...s===void 0?{}:{kinds:s},...o===void 0?{}:{maxDepth:o},...n===void 0?{}:{nodeLimit:n},...r===void 0?{}:{edgeLimit:r},...i===void 0?{}:{tokenBudget:i},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function vn(e,t,o,n){return tt(e.graph,t,e.details.map(r=>r.id===t&&n.length>0?{...r,evidence:n}:r),o)}function me(e,t,o,n){for(let r of o.slice(0,n)){let i=r?.trim();i&&e.push(`${t}:${i}`)}}async function wn(e,t,o,n){let r=await Ue(e,t,o.id_prefix,o.item_format,n);if(!r)return[];let{document:i}=await je(r,{schema:o.schema}),s=i.metadata,d=s.files??[],c=s.tests??[],l=s.docs??[],u=[["files",d.length],["tests",c.length],["docs",l.length],["comments",(s.comments??[]).length],["notes",(s.notes??[]).length],["learnings",(s.learnings??[]).length]];if(u.every(([,f])=>f===0))return[];let a=[`linked:${u.map(([f,g])=>`${f}=${g}`).join(",")}`];return me(a,"file",d.map(f=>f.path),3),me(a,"test",c.map(f=>f.command??f.path),2),me(a,"doc",l.map(f=>f.path),2),a}function En(e){let{canonicalId:t,context:o,missingCount:n,missingReferences:r,referenceLimit:i,summaryOnly:s}=e;return{id:t,format:"context",node_count:o.nodes.length+1,edge_count:o.edges.length,edge_basis:"deduplicated_directed",missing_count:n,missing_scope:"traversal",missing_reference_count:r.length,...s?{}:{missing_references:r.slice(0,i),context:o}}}function Cn(e){let{row:t,missingReachableSet:o,packetIds:n,filteredKinds:r,registry:i}=e;if(t.no_active_blocker_sentinel||!o.has(t.target_id.trim().toLowerCase())||!n.has(t.holder_id))return!1;if(r===void 0)return!0;let s=i.resolve(t.kind);return s!==void 0&&(r.has(s.kind)||s.inverse!==void 0&&r.has(s.inverse))}function st(e,t){let o=xe(),n=t.commandOptionsOverride??(o?.command==="deps"?o.options:t.commandOptions);return Be("deps",{...n,...t.global,resolvedOutputFormat:t.format},e)}function ge(e,t){let o=st(e,t),n=r=>Me(r,t.format,t.global.lean===!0);return n(t.global.tokenAccounting===!0?Ne(o,n):o)}function dt(e,t,o){let n;for(;;){let r=M(new TextEncoder().encode(ge(e,t)).byteLength);if(r===n)return r;o(r),n=r}}function ct(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function at(e){let{assembly:t,canonicalId:o,contextOptions:n,rootEvidence:r,summaryOnly:i,rendering:s,missingCount:d,missingReferences:c}=e,l=n.edgeLimit??40,u=Math.min(l,c.length),a=n.tokenBudget,f;for(;;){let g=vn(t,o,{...n,...a===void 0?{}:{tokenBudget:a}},r);f??=g.meta.tokenBudget,a??=f;let p=En({canonicalId:o,context:g,missingCount:d,missingReferences:c,referenceLimit:u,summaryOnly:i});if(i){if(M(new TextEncoder().encode(ge(S(p,!0,s.legacyAliasCounts),s)).byteLength)>f)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return p}if(g.meta.tokenBudget=f,g.meta.usedTokens=dt(S(p,!1,s.legacyAliasCounts),s,h=>{g.meta.usedTokens=h}),g.meta.usedTokens<=f)return p;if(u>0){u-=1;continue}let y=a,m=y*f/g.meta.usedTokens;a=Math.min(y-1,Math.max(1,Math.floor(m*.9)))}}function lt(e,t){let o=e.contextOptions,n={...e.rendering.global,outputFormat:e.rendering.format},r=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],i=r.length;r.push(String(t));let s=new Set(["--pm-path","--format","--output-format","--token-budget"]),d={format:"context",tokenBudget:t,kind:o.kinds},c=[["--max-depth","maxDepth",o.maxDepth],["--node-limit","nodeLimit",o.nodeLimit],["--edge-limit","edgeLimit",o.edgeLimit],["--direction","direction",o.direction],["--cursor","cursor",o.cursor],["--output-include","outputInclude",n.outputInclude],["--output-limit","outputLimit",n.outputLimit],["--output-budget","outputBudget",n.outputBudget],["--output-session","outputSession",n.outputSession],["--output-cursor","outputCursor",n.outputCursor]];for(let[a,f,g]of c)g!==void 0&&(r.push(a,String(g)),s.add(a),d[f]=g);for(let a of o.kinds??[])r.push("--kind",a),s.add("--kind");let l=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",n.json],["--lean","lean",n.lean],["--output-row-contract","outputRowContract",n.outputRowContract],["--token-accounting","tokenAccounting",n.tokenAccounting],["--no-extensions","noExtensions",n.noExtensions],["--no-pager","noPager",n.noPager]];for(let[a,f,g]of l)g===!0&&(r.push(a),s.add(a),d[f]=!0);let u=Re.find(a=>a.command==="deps");return Reflect.set(d,Te,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(u.dimensions).flatMap(a=>a.legacy_aliases.flatMap(f=>s.has(f.flag)?[f.flag]:[]))}),De("deps",d),ne(d.summary===!0,d.full===!0,"--summary"),n.outputInclude=d.outputInclude,{args:r,budgetIndex:i,summaryOnly:d.summary===!0,rendering:{...e.rendering,global:n,commandOptionsOverride:d}}}function In(e,t,o){let n={...t.rendering,commandOptionsOverride:{...t.rendering.commandOptionsOverride,tokenBudget:o}},r;try{r=at({...e,contextOptions:{...e.contextOptions,tokenBudget:o},summaryOnly:t.summaryOnly,rootEvidence:t.summaryOnly?[]:e.rootEvidence,rendering:n})}catch(s){if(!ct(s))throw s;return"native_floor"}let i=st(S(r,t.summaryOnly,n.legacyAliasCounts),n);return Se(i)?"output_constraints":"fits"}async function xn(e,t){let o=e.contextOptions.tokenBudget??F,n=lt(e,o),r=(n.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((a,f)=>a+f.id.length+f.title.length+f.status.length+(f.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(n.summaryOnly?[]:e.rootEvidence).reduce((a,f)=>a+f.length,0)),{findContextBudgetRecovery:i}=await import("./context-budget-recovery-5MKOCGY5.js"),s=i({requested:o,initialBudget:F,workUnits:r,probe:a=>In(e,n,a)}),d=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],c=X(d),l=s.feasible_tokens===null?d:[...n.args];s.feasible_tokens!==null&&(l[n.budgetIndex]=String(s.feasible_tokens));let u=X(l);return Ve("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:v.USAGE,cause:t,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(o),required:s.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+s.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[u,c],nextSteps:[u],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:s,suggested_retry_args:l,suggested_retry:u,next_best_command:c,fallback_candidates:[{source:"relationship_summary",command:c,reason:"Inspect bounded counts separately from context rows."}]}}})}async function Tn(e){let{pmRoot:t,assembly:o,canonicalId:n,options:r,rootEvidence:i,summaryOnly:s,rendering:d}=e,c=bn(r,o.graph.registry()),l=o.graph.closure(n,{direction:c.direction,...c.kinds===void 0?{}:{kinds:c.kinds},maxDepth:c.maxDepth??3}),u=l.value.filter(h=>o.missingIdSet.has(h.toLowerCase())),a=new Set(u.map(h=>h.toLowerCase())),f=o.graph.registry(),g=c.kinds?new Set(c.kinds.map(h=>f.require(h).kind)):void 0,p=new Set([n,...l.value]),y=[...o.dangling.active,...o.dangling.legacy_terminal].filter(h=>Cn({row:h,missingReachableSet:a,packetIds:p,filteredKinds:g,registry:f})),m={pmRoot:t,assembly:o,canonicalId:n,contextOptions:c,rootEvidence:i,summaryOnly:s,rendering:d,missingCount:u.length,missingReferences:y};try{return at(m)}catch(h){if(h instanceof w&&h.code==="invalid_query_cursor"){let b=lt({...m,contextOptions:{...c,cursor:void 0},rendering:{...d,global:{...d.global,outputCursor:void 0}}},c.tokenBudget??F),k=X(b.args);throw new w(h.message,h.exitCode,{...h.context,nextSteps:[...h.context.nextSteps,k],recovery:{suggested_retry:k,suggested_retry_args:b.args}})}throw ct(h)?await xn(m,h):h}}function Rn(e){let t=[e],o;for(;t.length>0;){let n=t.pop();n.dependencies.length>0&&(o=n,t.push(...n.dependencies))}return o?(o.dependencies.pop(),o.truncated=!0,!0):!1}function Dn(e,t,o,n,r,i,s){let d=r??sn,c=N(o.nodeLimit,"node-limit")??dn,l=N(o.edgeLimit,"edge-limit")??cn,u=N(o.tokenBudget,"token-budget")??an,a={nodeLimit:c,edgeLimit:l,tokenBudget:u,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},f=rt(e,n,new Set,d,t==="graph"?"repeated":i,new Set,a),g=it(e,n,void 0),p;for(;;){let y=kn(f),m=a.reasons.size===0?void 0:{reasons:[...a.reasons].sort(),limits:{max_depth:d,node_limit:c,edge_limit:l,token_budget:u},estimated_tokens:0,total_node_count:g.node_count,total_edge_count:g.edge_count,omitted_node_count:Math.max(0,g.node_count-y.nodes.length),omitted_edge_count:Math.max(0,g.edge_count-y.edges.length)},h={id:e,format:t,node_count:y.nodes.length,edge_count:y.edges.length,edge_basis:"deduplicated_directed",missing_count:y.missing_ids.length,...m?{truncation:m}:{}};if(p=t==="tree"?{...h,tree:f}:{...h,graph:y},(p.truncation===void 0?M(new TextEncoder().encode(ge(S(p,!1,s.legacyAliasCounts),s)).byteLength):dt(S(p,!1,s.legacyAliasCounts),s,b=>{p.truncation.estimated_tokens=b}))<=u)return p;if(!Rn(f))return a.reasons.add("token_budget"),p;a.reasons.add("token_budget")}}function S(e,t,o={}){let n={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},r=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:o,projection:{mode:t?"summary":"full",declared_field_groups:[n,...r],included_field_groups:t?[]:[n.name]}}}async function Fo(e,t,o){let n=Ee(process.cwd(),o.path);await Ke(n);let r=ln(t.format),i=ot(t.maxDepth),s=un(t.collapse);ne(t.summary===!0,t.full===!0,"--summary");let d=t.summary===!0,c=await $e(n),l=ve(c,W()),u=await ze(n,c.item_format,l.type_to_folder,void 0,c.schema),a=Ie(c.schema),f=new Map(u.map(m=>[m.id.trim().toLowerCase(),gn(m)])),g=ae(u,m=>D(m,a));for(let m of[...g.active,...g.legacy_terminal]){let h=f.get(m.holder_id.trim().toLowerCase()),b=m.kind.trim().toLowerCase();h&&!h.dependencies.some(k=>k.id.trim().toLowerCase()===m.target_id.trim().toLowerCase()&&k.kind===b)&&h.dependencies.push({id:m.target_id,kind:b})}if(!f.has(e.trim().toLowerCase()))throw new w(`Item ${e} not found`,v.NOT_FOUND);let p=o.outputFormat??(o.json===!0||o.json===void 0&&o.defaultOutputFormat==="json"?"json":"toon");if(r==="context"){let m=f.get(e.trim().toLowerCase()).id,h=d?[]:await wn(n,m,c,l.type_to_folder),b=E=>D(E,a),k=x(),C=et().lookup(n,Qe(u,b,k),()=>le(u,b,k));return S(await Tn({pmRoot:n,assembly:C.assembly,canonicalId:m,options:t,rootEvidence:h,summaryOnly:d,rendering:{format:p,global:o,commandOptions:t,legacyAliasCounts:C.assembly.legacyAliasCounts}}),d,C.assembly.legacyAliasCounts)}let y=Object.fromEntries(Object.entries(le(u,m=>D(m,a)).legacyAliasCounts));return d?S({id:e,format:r,...it(e,f,i)},!0,y):S(Dn(e,r,t,f,i,s,{format:p,global:o,commandOptions:t,legacyAliasCounts:y}),!1,y)}export{re as a,mt as b,$ as c,Y as d,Ge as e,gt as f,ht as g,yt as h,bt as i,Vn as j,Jn as k,Lt as l,x as m,Fn as n,J as o,Gn as p,Dt as q,Hn as r,U as s,At as t,Nt as u,ae as v,Mt as w,ro as x,le as y,ao as z,Kt as A,lo as B,Ve as C,jt as D,Qe as E,fe as F,et as G,go as H,F as I,tt as J,N as K,ot as L,fn as M,pn as N,Fo as O};
2
+ //# sourceMappingURL=chunk-URWYYJ7K.js.map
@@ -1,2 +1,2 @@
1
- import{Y as R}from"./chunk-SBJ2IKTH.js";import{ab as S}from"./chunk-GXAXDPD4.js";import{Xc as r,Yc as N,_c as E,rb as n}from"./chunk-7RQOFHMH.js";(function(){try{var T=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new T.Error().stack;e&&(T._sentryDebugIds=T._sentryDebugIds||{},T._sentryDebugIds[e]="6dff1fa2-fd7a-5a94-b49e-dd8a2fd804b9")}catch{}})();var u=new Set(["--author","--follow","--help","--lean","--token-accounting","--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor","--output-row-contract","--no-changed-fields","--no-extensions","--no-pager","--pm-path","--profile","--quiet","--interval-ms"]),p=new Set([...r,...N]),I=new Set(["--brief","--format","--full","--full-changed-fields","--id-only","--no-truncate","--stream"]),d=new Set(["--body-file","--file","--stdin-json"]),m=new Set(["--global","--local","--project"]),P=new Set(["--activity-limit","--default-depth","--section-activity","--section-blockers","--section-files","--section-hierarchy","--section-progress","--section-staleness","--section-tests","--section-workload","--stale-threshold-days"]),f=new Set(["action","fullChangedFields","idOnly","path","pmExecutable","timeoutMs"]),M=new Set(["configAction","id","name","query","reason","subcommand","target","text"]),G={assurance:{id:"<id>",kind:"<kind>",preset:"[kind]|[id]",subcommand:"<action>"},event:{title:"<title>"},files:{lookupPath:"lookup <path...>"},meet:{title:"<title>"},"item-reopen":{id:"<id>",reason:"<reason>"},merge:{subcommand:"<subcommand>"},remind:{title:"<title>"},workspace:{name:"<name>",subcommand:"snapshot",snapshotAction:"<snapshot-action>",target:"<target>"}},F={append:{"--text":"body"},assurance:{"--tree":"treeId","--owner":"owner","--apply":"apply","--enforcement":"enforcement"},init:{"--id-prefix":"idPrefix","--no-merge-fence":"mergeFence","--workspace":"workspace"},create:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},update:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},"update-many":{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},files:{"--note":"addNote"},docs:{"--note":"addNote"},comments:{"--full-history":"full"},notes:{"--file":"text","--full-history":"full"},learnings:{"--file":"text","--full-history":"full"},gc:{"--scope":"gcScope"},contracts:{"--action":"contractAction"},schema:{"--no-allow-unset":"allowUnset","--type":"fieldTypeScope"},"history-author-acknowledge":{"--event":"historyEvent","--all-actionable":"allActionable"},"extension-init":{"--capability":"capability"},"package-init":{"--capability":"capability"},"extension-install":{"--gh":"github"},"package-install":{"--gh":"github"},"extension-adopt":{"--gh":"github"},"package-adopt":{"--gh":"github"},extension:{"--gh":"github","--scaffold":"init"},package:{"--gh":"github","--scaffold":"init"},install:{"--gh":"github"}},D={"--pm-path":"path"},c={stats:{"--analytics":["measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]}};function g(T){return T.startsWith("extension-")?`extension ${T.slice(10)}`:T.startsWith("package-")?`package ${T.slice(8)}`:T.startsWith("item-")?`item ${T.slice(5)}`:T}function l(T,e){let t=F[T]?.[e]??D[e];return t!==void 0?t:e.replace(/^--/,"").replaceAll("_","-").replace(/-([a-z])/g,(O,_)=>_.toUpperCase())}function h(T){let e=new Set;return T.filter(({flag:t})=>!t.startsWith("--")||e.has(t)?!1:(e.add(t),!0))}function y(T,e){return e.find(({aliases:t})=>t?.includes(T))?.flag}function b(T,e,t,O){let _=c[T]?.[e.flag];if(_!==void 0&&_.every(A=>O.has(A)))return{surface:"cli",input:e.flag,counterpart:_[0],disposition:"shared",reason:"The validated CLI JSON object fans out across strict SDK parameters."};let i=l(T,e.flag);if(O.has(i))return{surface:"cli",input:e.flag,counterpart:i,disposition:"shared",reason:"The CLI flag maps directly to a strict SDK action parameter."};let C=y(e.flag,t);if(C!==void 0){let A=l(T,C);if(O.has(A))return{surface:"cli",input:e.flag,counterpart:A,disposition:"compatibility_alias",reason:`Compatibility spelling for ${C}.`}}return u.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_transport",reason:"CLI process transport is supplied by the in-process SDK host."}:I.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_presentation",reason:"CLI rendering or mutation projection does not alter the SDK result envelope."}:d.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_adapter",reason:"Local file or stdin adaptation is a CLI boundary concern."}:P.has(e.flag)?{surface:"cli",input:e.flag,counterpart:"key",disposition:"compatibility_alias",reason:"CLI config shorthand normalizes to the SDK configAction/key/value contract."}:m.has(e.flag)?{surface:"cli",input:e.flag,counterpart:"scope",disposition:"cli_scope_selector",reason:"Mutually exclusive CLI scope switches normalize to the SDK scope parameter."}:{surface:"cli",input:e.flag,counterpart:i,disposition:"unclassified",reason:"The CLI flag has no strict SDK parameter or approved boundary classification."}}function U(T,e,t){let O=Object.entries(c[T]??{}).find(([C,A])=>A.includes(e)&&t.some(({input:o,disposition:s})=>o===C&&s==="shared"));if(O!==void 0)return{surface:"sdk",input:e,counterpart:O[0],disposition:"shared",reason:"The strict SDK parameter is reachable through the validated CLI JSON object."};let _=t.find(({counterpart:C,disposition:A})=>C===e&&(A==="shared"||A==="compatibility_alias"||A==="cli_scope_selector"));if(_!==void 0)return{surface:"sdk",input:e,counterpart:_.input,disposition:"shared",reason:"The strict SDK parameter is reachable from the CLI contract."};let i=G[T]?.[e];return i!==void 0?{surface:"sdk",input:e,counterpart:i,disposition:"shared",reason:"The strict SDK parameter maps to a canonical CLI positional argument."}:f.has(e)?{surface:"sdk",input:e,disposition:"sdk_transport",reason:"The SDK host supplies in-process transport and workspace selection."}:M.has(e)?{surface:"sdk",input:e,disposition:"cli_positional",reason:"The CLI accepts this SDK parameter as a positional command argument."}:{surface:"sdk",input:e,disposition:"sdk_native",reason:"The typed SDK exposes this structured input without a canonical CLI long flag."}}function v(T={}){let e=T.actions??n,t=T.resolveFlags??S,O=T.resolveParameters??R;return e.map(_=>{let i=g(_),C=h(t(i)).filter(({flag:a})=>E(_)!==void 0||!p.has(a)),A=new Set(O(_)??[]),o=C.map(a=>b(_,a,C,A)),s=[...A].sort((a,L)=>a.localeCompare(L)).map(a=>U(_,a,o));return{action:_,command:i,cli:o,sdk:s,unclassified:[...o,...s].filter(({disposition:a})=>a==="unclassified")}})}(function(){try{var T=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new T.Error().stack;e&&(T._sentryDebugIds=T._sentryDebugIds||{},T._sentryDebugIds[e]="92c17dbe-3868-5fa5-a873-0744d3e7ca8e")}catch{}})();export{v as a};
2
- //# sourceMappingURL=chunk-5MKNVJCM.js.map
1
+ import{Y as R}from"./chunk-MT5TYMEU.js";import{ab as S}from"./chunk-5LBZR6YW.js";import{Xc as r,Yc as N,_c as E,rb as n}from"./chunk-NC5HUGHU.js";(function(){try{var T=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new T.Error().stack;e&&(T._sentryDebugIds=T._sentryDebugIds||{},T._sentryDebugIds[e]="6dff1fa2-fd7a-5a94-b49e-dd8a2fd804b9")}catch{}})();var u=new Set(["--author","--follow","--help","--lean","--token-accounting","--output-include","--output-limit","--output-budget","--output-format","--output-session","--output-cursor","--output-row-contract","--no-changed-fields","--no-extensions","--no-pager","--pm-path","--profile","--quiet","--interval-ms"]),p=new Set([...r,...N]),I=new Set(["--brief","--format","--full","--full-changed-fields","--id-only","--no-truncate","--stream"]),d=new Set(["--body-file","--file","--stdin-json"]),m=new Set(["--global","--local","--project"]),P=new Set(["--activity-limit","--default-depth","--section-activity","--section-blockers","--section-files","--section-hierarchy","--section-progress","--section-staleness","--section-tests","--section-workload","--stale-threshold-days"]),f=new Set(["action","fullChangedFields","idOnly","path","pmExecutable","timeoutMs"]),M=new Set(["configAction","id","name","query","reason","subcommand","target","text"]),G={assurance:{id:"<id>",kind:"<kind>",preset:"[kind]|[id]",subcommand:"<action>"},event:{title:"<title>"},files:{lookupPath:"lookup <path...>"},meet:{title:"<title>"},"item-reopen":{id:"<id>",reason:"<reason>"},merge:{subcommand:"<subcommand>"},remind:{title:"<title>"},workspace:{name:"<name>",subcommand:"snapshot",snapshotAction:"<snapshot-action>",target:"<target>"}},F={append:{"--text":"body"},assurance:{"--tree":"treeId","--owner":"owner","--apply":"apply","--enforcement":"enforcement"},init:{"--id-prefix":"idPrefix","--no-merge-fence":"mergeFence","--workspace":"workspace"},create:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},update:{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},"update-many":{"--ac":"acceptanceCriteria","--estimated-minutes":"estimate","--file":"linkedFile","--test":"linkedTest","--expected":"expectedResult","--actual":"actualResult"},files:{"--note":"addNote"},docs:{"--note":"addNote"},comments:{"--full-history":"full"},notes:{"--file":"text","--full-history":"full"},learnings:{"--file":"text","--full-history":"full"},gc:{"--scope":"gcScope"},contracts:{"--action":"contractAction"},schema:{"--no-allow-unset":"allowUnset","--type":"fieldTypeScope"},"history-author-acknowledge":{"--event":"historyEvent","--all-actionable":"allActionable"},"extension-init":{"--capability":"capability"},"package-init":{"--capability":"capability"},"extension-install":{"--gh":"github"},"package-install":{"--gh":"github"},"extension-adopt":{"--gh":"github"},"package-adopt":{"--gh":"github"},extension:{"--gh":"github","--scaffold":"init"},package:{"--gh":"github","--scaffold":"init"},install:{"--gh":"github"}},D={"--pm-path":"path"},c={stats:{"--analytics":["measurements","metric","measurementLimit","observe","improvementDirection","measurementSource","measurementItem","measurementRevision","author","message","provenanceCoverage","fleetAttribution","since","eventLimit","minimumSample"]}};function g(T){return T.startsWith("extension-")?`extension ${T.slice(10)}`:T.startsWith("package-")?`package ${T.slice(8)}`:T.startsWith("item-")?`item ${T.slice(5)}`:T}function l(T,e){let t=F[T]?.[e]??D[e];return t!==void 0?t:e.replace(/^--/,"").replaceAll("_","-").replace(/-([a-z])/g,(O,_)=>_.toUpperCase())}function h(T){let e=new Set;return T.filter(({flag:t})=>!t.startsWith("--")||e.has(t)?!1:(e.add(t),!0))}function y(T,e){return e.find(({aliases:t})=>t?.includes(T))?.flag}function b(T,e,t,O){let _=c[T]?.[e.flag];if(_!==void 0&&_.every(A=>O.has(A)))return{surface:"cli",input:e.flag,counterpart:_[0],disposition:"shared",reason:"The validated CLI JSON object fans out across strict SDK parameters."};let i=l(T,e.flag);if(O.has(i))return{surface:"cli",input:e.flag,counterpart:i,disposition:"shared",reason:"The CLI flag maps directly to a strict SDK action parameter."};let C=y(e.flag,t);if(C!==void 0){let A=l(T,C);if(O.has(A))return{surface:"cli",input:e.flag,counterpart:A,disposition:"compatibility_alias",reason:`Compatibility spelling for ${C}.`}}return u.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_transport",reason:"CLI process transport is supplied by the in-process SDK host."}:I.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_presentation",reason:"CLI rendering or mutation projection does not alter the SDK result envelope."}:d.has(e.flag)?{surface:"cli",input:e.flag,disposition:"cli_adapter",reason:"Local file or stdin adaptation is a CLI boundary concern."}:P.has(e.flag)?{surface:"cli",input:e.flag,counterpart:"key",disposition:"compatibility_alias",reason:"CLI config shorthand normalizes to the SDK configAction/key/value contract."}:m.has(e.flag)?{surface:"cli",input:e.flag,counterpart:"scope",disposition:"cli_scope_selector",reason:"Mutually exclusive CLI scope switches normalize to the SDK scope parameter."}:{surface:"cli",input:e.flag,counterpart:i,disposition:"unclassified",reason:"The CLI flag has no strict SDK parameter or approved boundary classification."}}function U(T,e,t){let O=Object.entries(c[T]??{}).find(([C,A])=>A.includes(e)&&t.some(({input:o,disposition:s})=>o===C&&s==="shared"));if(O!==void 0)return{surface:"sdk",input:e,counterpart:O[0],disposition:"shared",reason:"The strict SDK parameter is reachable through the validated CLI JSON object."};let _=t.find(({counterpart:C,disposition:A})=>C===e&&(A==="shared"||A==="compatibility_alias"||A==="cli_scope_selector"));if(_!==void 0)return{surface:"sdk",input:e,counterpart:_.input,disposition:"shared",reason:"The strict SDK parameter is reachable from the CLI contract."};let i=G[T]?.[e];return i!==void 0?{surface:"sdk",input:e,counterpart:i,disposition:"shared",reason:"The strict SDK parameter maps to a canonical CLI positional argument."}:f.has(e)?{surface:"sdk",input:e,disposition:"sdk_transport",reason:"The SDK host supplies in-process transport and workspace selection."}:M.has(e)?{surface:"sdk",input:e,disposition:"cli_positional",reason:"The CLI accepts this SDK parameter as a positional command argument."}:{surface:"sdk",input:e,disposition:"sdk_native",reason:"The typed SDK exposes this structured input without a canonical CLI long flag."}}function v(T={}){let e=T.actions??n,t=T.resolveFlags??S,O=T.resolveParameters??R;return e.map(_=>{let i=g(_),C=h(t(i)).filter(({flag:a})=>E(_)!==void 0||!p.has(a)),A=new Set(O(_)??[]),o=C.map(a=>b(_,a,C,A)),s=[...A].sort((a,L)=>a.localeCompare(L)).map(a=>U(_,a,o));return{action:_,command:i,cli:o,sdk:s,unclassified:[...o,...s].filter(({disposition:a})=>a==="unclassified")}})}(function(){try{var T=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new T.Error().stack;e&&(T._sentryDebugIds=T._sentryDebugIds||{},T._sentryDebugIds[e]="92c17dbe-3868-5fa5-a873-0744d3e7ca8e")}catch{}})();export{v as a};
2
+ //# sourceMappingURL=chunk-W7MCCFYV.js.map