@unbrained/pm-cli 2026.8.13 → 2026.8.14

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 (136) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +141 -112
  3. package/dist/cli/main.js +39 -3
  4. package/dist/cli-bundle/bundle-manifest.json +144 -176
  5. package/dist/cli-bundle/chunks/{chunk-DEDU3DG7.js → chunk-BBOFSVAK.js} +66 -65
  6. package/dist/cli-bundle/chunks/chunk-BFALV3YP.js +5 -0
  7. package/dist/cli-bundle/chunks/{chunk-Q47C67TQ.js → chunk-FIW4P64F.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-QGTUPEU5.js → chunk-G5JUB66K.js} +41 -41
  9. package/dist/cli-bundle/chunks/{chunk-3ZMOWAFM.js → chunk-SBRKH6OR.js} +2 -2
  10. package/dist/cli-bundle/chunks/chunk-TMJ7URWS.js +13 -0
  11. package/dist/cli-bundle/chunks/{chunk-F7FJYGK3.js → chunk-TXMEUUUY.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-YLBAPY22.js → chunk-XAVMOK6B.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-TF3TPKPR.js → chunk-YAMTJL6Y.js} +33 -33
  14. package/dist/cli-bundle/chunks/{chunk-IMGIN7R6.js → chunk-YSVSMJ2B.js} +2 -2
  15. package/dist/cli-bundle/chunks/{register-list-query-4HIZ7EA3.js → register-list-query-T3EHHNNV.js} +2 -2
  16. package/dist/cli-bundle/chunks/{register-mutation-W64FZ5HN.js → register-mutation-E27WCLSZ.js} +2 -2
  17. package/dist/cli-bundle/chunks/{register-operations-C44ET7R5.js → register-operations-4R6I7CPY.js} +2 -2
  18. package/dist/cli-bundle/chunks/{register-setup-634MFRXU.js → register-setup-3YXZ444E.js} +2 -2
  19. package/dist/cli-bundle/focused-chunks/{chunk-OOYYKQWX.js → chunk-4DQ2YERC.js} +2 -2
  20. package/dist/cli-bundle/focused-chunks/chunk-F43TT2QQ.js +8 -0
  21. package/dist/cli-bundle/focused-chunks/{chunk-2RI2FESN.js → chunk-K7RWWOAG.js} +2 -2
  22. package/dist/cli-bundle/focused-chunks/chunk-KFSZ3BP6.js +16 -0
  23. package/dist/cli-bundle/focused-chunks/{chunk-3DJSGWVB.js → chunk-KSEDUWVZ.js} +2 -2
  24. package/dist/cli-bundle/focused-chunks/{chunk-NFHFZH2Z.js → chunk-KYUQGTSB.js} +2 -2
  25. package/dist/cli-bundle/focused-chunks/{chunk-IIS2FRKL.js → chunk-LZ4MV3RH.js} +2 -2
  26. package/dist/cli-bundle/focused-chunks/chunk-PGXJQLCT.js +155 -0
  27. package/dist/cli-bundle/focused-chunks/{chunk-E3AVJ655.js → chunk-PPFGQDSI.js} +2 -2
  28. package/dist/cli-bundle/focused-chunks/chunk-Q4YY3XNF.js +2 -0
  29. package/dist/cli-bundle/focused-chunks/chunk-QK753U3U.js +46 -0
  30. package/dist/cli-bundle/focused-chunks/{chunk-QDZUABWL.js → chunk-QUMB2J27.js} +2 -2
  31. package/dist/cli-bundle/focused-chunks/chunk-SM7MTG27.js +2 -0
  32. package/dist/cli-bundle/focused-chunks/{chunk-I75MANL7.js → chunk-WCVE2NIG.js} +2 -2
  33. package/dist/cli-bundle/focused-chunks/chunk-XDNAW5OI.js +18 -0
  34. package/dist/cli-bundle/focused-chunks/{chunk-2JP7W7GO.js → chunk-YOOI3UZX.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-ZM6TZVHC.js +2 -0
  36. package/dist/cli-bundle/main.js +13 -13
  37. package/dist/cli-bundle/sdk-authoring.js +1 -1
  38. package/dist/cli-bundle/sdk-contracts.js +1 -1
  39. package/dist/cli-bundle/sdk-core.js +44 -41
  40. package/dist/cli-bundle/sdk-governance.js +1 -1
  41. package/dist/cli-bundle/sdk-graph.js +1 -1
  42. package/dist/cli-bundle/sdk-merge.js +109 -1
  43. package/dist/cli-bundle/sdk-query.js +1 -1
  44. package/dist/cli-bundle/sdk-runtime.js +1 -1
  45. package/dist/cli-bundle/sdk-testing.js +1 -1
  46. package/dist/cli-bundle/sdk.js +2 -2
  47. package/dist/core/history/drift-scan.d.ts +6 -0
  48. package/dist/core/history/drift-scan.js +74 -50
  49. package/dist/core/history/workspace-history.d.ts +59 -0
  50. package/dist/core/history/workspace-history.js +197 -10
  51. package/dist/core/output/output.js +12 -4
  52. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -1
  53. package/dist/sdk/cli-contracts/runtime-contracts.js +155 -60
  54. package/dist/sdk/cli-program.js +3 -3
  55. package/dist/sdk/context-relevance.js +12 -4
  56. package/dist/sdk/governance/assurance.js +4 -4
  57. package/dist/sdk/governance/health.js +15 -3
  58. package/dist/sdk/governance/validate-history-drift.d.ts +7 -0
  59. package/dist/sdk/governance/validate-history-drift.js +68 -0
  60. package/dist/sdk/governance/validate.js +4 -46
  61. package/dist/sdk/graph/assembly.d.ts +23 -0
  62. package/dist/sdk/graph/assembly.js +54 -2
  63. package/dist/sdk/graph/durable-cache.js +50 -20
  64. package/dist/sdk/graph/governance-contracts.d.ts +1 -1
  65. package/dist/sdk/graph/governance-contracts.js +4 -2
  66. package/dist/sdk/graph/governance.d.ts +21 -1
  67. package/dist/sdk/graph/governance.js +94 -32
  68. package/dist/sdk/graph/index.d.ts +2 -2
  69. package/dist/sdk/graph/index.js +4 -4
  70. package/dist/sdk/graph/mutation-advisory.js +15 -7
  71. package/dist/sdk/graph/remediation.js +12 -2
  72. package/dist/sdk/history-read.d.ts +8 -0
  73. package/dist/sdk/history-read.js +2 -2
  74. package/dist/sdk/index.d.ts +1 -1
  75. package/dist/sdk/index.js +3 -3
  76. package/dist/sdk/query/history.js +20 -3
  77. package/dist/sdk/read-output-budget.d.ts +2 -0
  78. package/dist/sdk/read-output-budget.js +12 -5
  79. package/dist/sdk/read-output-contracts.d.ts +61 -5
  80. package/dist/sdk/read-output-contracts.js +210 -28
  81. package/dist/sdk/read-output-rows.d.ts +11 -0
  82. package/dist/sdk/read-output-rows.js +47 -2
  83. package/dist/sdk/runtime-primitives.d.ts +1 -1
  84. package/dist/sdk/runtime-primitives.js +3 -3
  85. package/dist/sdk/runtime.js +5 -3
  86. package/docs/ASSURANCE.md +10 -1
  87. package/docs/COMMANDS.md +31 -2
  88. package/docs/READ_OUTPUT_CONTRACTS.md +44 -8
  89. package/docs/RELATIONSHIP_GRAPH.md +20 -5
  90. package/docs/SDK.md +12 -5
  91. package/docs/SDK_CONTEXT_INTEGRITY.md +32 -1
  92. package/docs/TESTING.md +23 -1
  93. package/docs/performance/sdk-entrypoint-import-costs.md +20 -13
  94. package/marketplace.json +2 -2
  95. package/package.json +6 -6
  96. package/packages/pm-beads/extensions/beads/index.ts +1 -0
  97. package/packages/pm-beads/package.json +1 -1
  98. package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
  99. package/packages/pm-calendar/package.json +1 -1
  100. package/packages/pm-command-kit/package.json +1 -1
  101. package/packages/pm-digital-twin/extensions/digital-twin/index.ts +7 -0
  102. package/packages/pm-digital-twin/package.json +1 -1
  103. package/packages/pm-governance-audit/extensions/governance-audit/index.ts +4 -0
  104. package/packages/pm-governance-audit/package.json +1 -1
  105. package/packages/pm-guide-shell/extensions/guide-shell/index.ts +5 -0
  106. package/packages/pm-guide-shell/package.json +1 -1
  107. package/packages/pm-kanban/package.json +1 -1
  108. package/packages/pm-lifecycle-hooks/package.json +1 -1
  109. package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/index.ts +6 -0
  110. package/packages/pm-linked-test-adapters/package.json +1 -1
  111. package/packages/pm-search-advanced/extensions/search-advanced/index.ts +2 -0
  112. package/packages/pm-search-advanced/package.json +1 -1
  113. package/packages/pm-templates/extensions/templates/index.ts +4 -0
  114. package/packages/pm-templates/package.json +1 -1
  115. package/packages/pm-todos/extensions/todos/index.ts +2 -0
  116. package/packages/pm-todos/package.json +1 -1
  117. package/packages/pm-vcs/extensions/vcs/index.ts +7 -0
  118. package/packages/pm-vcs/package.json +1 -1
  119. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  120. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  121. package/scripts/bundle-cli.mjs +17 -4
  122. package/sdk/public-surface.json +209 -29
  123. package/dist/cli-bundle/chunks/chunk-DL5M5J3V.js +0 -13
  124. package/dist/cli-bundle/chunks/chunk-HIUZVCMN.js +0 -5
  125. package/dist/cli-bundle/focused-chunks/chunk-27N23W6M.js +0 -31
  126. package/dist/cli-bundle/focused-chunks/chunk-3BNVU6LC.js +0 -8
  127. package/dist/cli-bundle/focused-chunks/chunk-6MLIRBLV.js +0 -5
  128. package/dist/cli-bundle/focused-chunks/chunk-6XYLENDV.js +0 -155
  129. package/dist/cli-bundle/focused-chunks/chunk-CP4K4WFS.js +0 -2
  130. package/dist/cli-bundle/focused-chunks/chunk-EBTNSFYE.js +0 -2
  131. package/dist/cli-bundle/focused-chunks/chunk-HC2OL2H2.js +0 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-OGC4XSBC.js +0 -17
  133. package/dist/cli-bundle/focused-chunks/chunk-PKPOZXLL.js +0 -2
  134. package/dist/cli-bundle/focused-chunks/chunk-QQX5TDFT.js +0 -16
  135. package/dist/cli-bundle/focused-chunks/chunk-TEZIXMTH.js +0 -2
  136. package/dist/cli-bundle/focused-chunks/chunk-WEH6NSL6.js +0 -18
@@ -1,17 +0,0 @@
1
- import{f as Ce,g as rt}from"./chunk-I75MANL7.js";import{a as Qt,g as it,i as en}from"./chunk-NFHFZH2Z.js";import{g as Rn,i as Sn}from"./chunk-HC2OL2H2.js";import{t as ye,u as kn,v as we,va as vn,w as bn}from"./chunk-WEH6NSL6.js";import{La as mn,Pa as Q,Qa as fn,Sa as pn,U as ue,V as Z,Va as hn,Wa as _n,Ya as N,Z as on,da as sn,ea as an,fb as gn,ha as cn,ia as ln,kb as yn,l as X,la as ot,na as dn,nb as Ie,ob as Te,pb as Oe,r as rn,rb as wn,ub as De,xa as st,za as un}from"./chunk-6XYLENDV.js";import{F as K,K as Yt,L as B,M as ge,O as U,R as Jt,Ra as tn,V as L,aa as Xt,da as et,h as Ht,o as Ze,p as M,q as Wt,r as V,s as Vt,t as ce,w as Qe,x as Kt}from"./chunk-2RI2FESN.js";import{j as nn}from"./chunk-EBTNSFYE.js";import{N as Gt,U as qt,V as Ee,Y as _,Z as g,aa as tt,ba as Zt,ca as nt,t as Xe}from"./chunk-CP4K4WFS.js";import Me from"node:fs/promises";import Le from"node:path";import{Option as uc}from"commander";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="daefefd1-3b0b-513d-8b8c-ab17f90b995a")}catch{}})();function Dr(e,t){let n=[],i=new Set;for(let r of t.keys){if(!Object.hasOwn(e,r))continue;let o=e[r];if(o!=null){if(typeof o=="string"){n.push(o);continue}if(!Array.isArray(o)||!o.every(s=>typeof s=="string"))return;i.has(o)||(i.add(o),n.push(...o))}}return n.length>0?n.join("; "):void 0}function Fe(e,t){return e.find(i=>i.target===t)??{target:t,keys:[t]}}function w(e,t){return e[t]===!0?!0:void 0}function ee(e,t){return e[t]===!1?!0:void 0}function xn(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function An(e,t){for(let[n,i]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=i)}function En(e){let t=r=>it(e,Fe(Ce,r)),n=r=>en(e,Fe(rt,r)),i={title:t("title"),description:t("description"),body:t("body"),status:t("status"),closeReason:t("closeReason"),priority:t("priority"),type:t("type"),tags:t("tags"),addTags:n("addTags"),removeTags:n("removeTags"),deadline:t("deadline"),estimatedMinutes:t("estimatedMinutes"),acceptanceCriteria:Dr(e,Fe(rt,"acceptanceCriteria")),addAc:n("addAc"),removeAc:n("removeAc"),definitionOfReady:t("definitionOfReady"),order:t("order"),rank:t("rank"),goal:t("goal"),objective:t("objective"),value:t("value"),impact:t("impact"),outcome:t("outcome"),whyNow:t("whyNow"),author:t("author"),message:t("message"),force:!!e.force,ownershipMetadataBypass:e.ownershipMetadataBypass===!0?!0:void 0,ownershipDependencyBypass:e.ownershipDependencyBypass===!0?!0:void 0,assignee:t("assignee"),parent:t("parent"),allowUnresolvedDeps:xn(e,["allowUnresolvedDeps","allow_unresolved_deps"])===!0,reviewer:t("reviewer"),risk:t("risk"),confidence:t("confidence"),sprint:t("sprint"),release:t("release"),blockedBy:t("blockedBy"),blockedReason:t("blockedReason"),unblockNote:t("unblockNote"),reporter:t("reporter"),severity:t("severity"),environment:t("environment"),reproSteps:t("reproSteps"),resolution:t("resolution"),expectedResult:t("expectedResult"),actualResult:t("actualResult"),affectedVersion:t("affectedVersion"),fixedVersion:t("fixedVersion"),component:t("component"),regression:e.regression===!0?"true":t("regression"),customerImpact:t("customerImpact"),dep:n("dep"),depRemove:n("depRemove"),replaceDeps:w(e,"replaceDeps"),replaceTests:w(e,"replaceTests"),replaceFiles:w(e,"replaceFiles"),replaceDocs:w(e,"replaceDocs"),comment:n("comment"),note:n("note"),learning:n("learning"),file:n("file"),test:n("test"),doc:n("doc"),reminder:n("reminder"),event:n("event"),typeOption:n("typeOption"),field:n("field"),unset:n("unset"),clearDeps:w(e,"clearDeps"),clearComments:w(e,"clearComments"),clearNotes:w(e,"clearNotes"),clearLearnings:w(e,"clearLearnings"),clearFiles:w(e,"clearFiles"),clearTests:w(e,"clearTests"),clearDocs:w(e,"clearDocs"),clearReminders:w(e,"clearReminders"),clearEvents:w(e,"clearEvents"),clearTypeOptions:w(e,"clearTypeOptions")};return An(i,e),i}function C(e,t){let n=Fe(Qt,t),i=it(e,n);if(i!==void 0)return i;for(let r of n.keys){let o=e[r];if(Array.isArray(o)){let s=o.filter(a=>typeof a=="string");if(s.length>0)return s.join(",")}if(t==="ids"&&typeof o=="string")return o;if(typeof o=="number"&&Number.isFinite(o))return String(o)}}function Fr(e){let t=w(e,"filterFilesMissing"),n=w(e,"filterDocsMissing");return{filterReviewerMissing:w(e,"filterReviewerMissing"),filterRiskMissing:w(e,"filterRiskMissing"),filterConfidenceMissing:w(e,"filterConfidenceMissing"),filterSprintMissing:w(e,"filterSprintMissing"),filterReleaseMissing:w(e,"filterReleaseMissing"),hasNotes:w(e,"hasNotes"),hasLearnings:w(e,"hasLearnings"),hasFiles:w(e,"hasFiles"),hasDocs:w(e,"hasDocs"),hasTests:w(e,"hasTests"),hasComments:w(e,"hasComments"),hasDeps:w(e,"hasDeps"),hasBody:w(e,"hasBody"),hasLinkedCommand:w(e,"hasLinkedCommand"),noNotes:ee(e,"notes"),noLearnings:ee(e,"learnings"),noFiles:ee(e,"files")??t,filterFilesMissing:t,noDocs:ee(e,"docs")??n,filterDocsMissing:n,noTests:ee(e,"tests"),noComments:ee(e,"comments"),noDeps:ee(e,"deps"),emptyBody:w(e,"emptyBody"),noLinkedCommand:ee(e,"linkedCommand")}}function at(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:w(e,"today"),recent:w(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:ee(e,"truncate"),includeBody:w(e,"includeBody"),strictRead:w(e,"strictRead"),compact:w(e,"compact"),brief:w(e,"brief"),full:w(e,"full"),fields:C(e,"fields"),sort:C(e,"sort"),order:C(e,"order"),tree:w(e,"tree"),treeDepth:C(e,"treeDepth"),filterAcMissing:w(e,"filterAcMissing"),filterEstimatesMissing:xn(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:w(e,"filterResolutionMissing"),filterMetadataMissing:w(e,"filterMetadataMissing"),...Fr(e)};return An(t,e),t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bcda2578-3b01-5e64-9d53-cd32c0f927b8")}catch{}})();function R(e,t){let n=e[t];return typeof n=="string"&&n.trim().length>0?n:void 0}function T(e,t){let n=e[t];return typeof n=="string"?n.trim().length>0?n:void 0:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function Pr(e,t){let n=e[t];return typeof n=="string"?n:typeof n=="number"&&Number.isFinite(n)?String(n):void 0}function ke(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kc(e,t){if(typeof e=="number"){if(!Number.isInteger(e))throw new g(`${t} must be a finite integer.`,_.USAGE);return e}if(typeof e=="string"&&e.trim().length>0){let n=Number(e);if(!Number.isInteger(n))throw new g(`${t} must be a finite integer.`,_.USAGE);return n}}function bc(e,t){return typeof e.limit=="number"&&Number.isFinite(e.limit)?e.limit:typeof t.limit=="number"&&Number.isFinite(t.limit)?t.limit:R(e,"limit")??R(t,"limit")}function vc(e){let t=R(e,"outputFormat");return{json:!0,quiet:!0,author:R(e,"author"),path:R(e,"path"),noExtensions:e.noExtensions===!0||e.no_extensions===!0,noPager:!0,outputInclude:R(e,"outputInclude"),outputLimit:T(e,"outputLimit"),outputBudget:T(e,"outputBudget"),outputSession:R(e,"outputSession"),outputFormat:t==="json"||t==="toon"?t:void 0}}var Mr=new Set(["tags","blockedBy","blocked_by","skills","fields"]),Lr=new Set(["comment","note","learning","reminder","event","dep","depRemove","dep_remove","file","doc","test","unset","addGlob","add_glob","migrate","envSet","env_set","envClear","env_clear"]),Nr=new Set(["files","files-discover","docs","test","test-all"]),$r=new Set(["claim","release","start-task","pause-task","close-task"]),jr={list:["status","type","tag","priority","limit","offset"],search:["mode","status","type","tag","priority","limit"],create:["title","type","status","description","body","priority","tags","parent","createMode","create_mode","allowMissingParent","allowDuplicate"],update:["parent","allowMissingParent","completedAt"],copy:["allowDuplicate"],close:["duplicateOf","completedAt"],append:["body"]},Br=["outputInclude","outputLimit","outputBudget","outputFormat","outputSession"];function In(e,t){let n={},i=t!==void 0&&Nr.has(t),r=t==="files"||t==="files-discover"||t==="docs";for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Mr.has(o)){n[o]=s.join(",");continue}if(o==="note"&&r){n[o]=s;continue}if(typeof s=="string"&&Lr.has(o)){n[o]=[s];continue}if(typeof s=="string"&&i&&(o==="add"||o==="remove")){n[o]=[s];continue}n[o]=s}return n}function Rc(e,t){let n=Xt(e.options),i={},r=c=>{n[c]!==void 0||e[c]===void 0||(i[c]=e[c])};for(let c of jr[t??""]??[])r(c);for(let c of Br)r(c);let o=In({...i,...n},t),s=R(e,"author"),a=t!==void 0&&$r.has(t)?R(e,"assignee")??R(o,"assignee"):void 0;return s&&o.author===void 0?{...o,author:s}:a&&o.author===void 0?{...o,author:a}:o}function Sc(e){if(e.addNote===void 0)return e;let t={...e};return t.note===void 0&&typeof t.addNote=="string"&&(t.note=t.addNote),delete t.addNote,t}function xc(e){let t={...e};return t.discoveryNote!==void 0&&t.note===void 0&&typeof t.discoveryNote=="string"&&(t.note=t.discoveryNote),delete t.discover,delete t.discoveryNote,t}function Ac(e){let t=[],n=!0;for(let i of e.trim().toLowerCase()){if(i>="a"&&i<="z"||i>="0"&&i<="9"){t.push(i),n=!1;continue}n||(t.push("-"),n=!0)}return t.at(-1)==="-"&&t.pop(),t.join("")}function Ec(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function dt(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function Cc(e,t){let n=new Set(["action","args","author","cwd","fullChangedFields","id","options","path","query","reason","target"]),i={};for(let[o,s]of Object.entries(e))n.has(o)||(i[o]=s);let r={...i,...t};return delete r.args,r}function Ic(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function lt(e){return{type:T(e,"filterType"),tag:T(e,"filterTag"),priority:T(e,"filterPriority"),deadlineBefore:T(e,"filterDeadlineBefore"),deadlineAfter:T(e,"filterDeadlineAfter"),updatedAfter:T(e,"filterUpdatedAfter"),updatedBefore:T(e,"filterUpdatedBefore"),createdAfter:T(e,"filterCreatedAfter"),createdBefore:T(e,"filterCreatedBefore"),ids:Pr(e,"ids"),assignee:T(e,"filterAssignee"),assigneeFilter:T(e,"filterAssigneeFilter")??T(e,"filterAssignee_filter"),parent:T(e,"filterParent"),sprint:T(e,"filterSprint"),release:T(e,"filterRelease"),limit:T(e,"limit"),offset:T(e,"offset")}}function ct(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return dt(e)}function Pe(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Tc(e){let t=ct(e.kind),n=ct(e.exemptIsolate),i=ct(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:Pe(e.maxDepth),limit:Pe(e.limit),after:R(e,"after"),direction:R(e,"direction"),maxPaths:Pe(e.maxPaths),sample:Pe(e.sample),...n===void 0?{}:{exemptIsolate:n},...i===void 0?{}:{exemptIsolateType:i},saveBaseline:e.saveBaseline===!0,rebuild:e.rebuild===!0,clear:e.clear===!0,summary:e.summary===!0,...e.full===!0?{full:!0}:{}}}function Oc(e){return{status:R(e,"filterStatus"),list:ke(e.list)?at(e.list):lt(e),reason:R(e,"reason"),resolution:R(e,"resolution"),expectedResult:R(e,"expectedResult")??R(e,"expected_result")??R(e,"expected"),actualResult:R(e,"actualResult")??R(e,"actual_result")??R(e,"actual"),validateClose:R(e,"validateClose")??R(e,"validate_close"),author:R(e,"author"),message:R(e,"message"),force:e.force===!0?!0:void 0,dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}var Ur=new Set(["filterStatus","filterType","filterTag","filterPriority","filterDeadlineBefore","filterDeadlineAfter","filterUpdatedAfter","filterUpdatedBefore","filterCreatedAfter","filterCreatedBefore","filterAssignee","filterAssigneeFilter","filterAssignee_filter","filterParent","filterSprint","filterRelease","ids","list","update","limit","offset","dryRun","dry_run","rollback","checkpoint","noCheckpoint","no_checkpoint"]);function Cn(e){let t={};for(let[n,i]of Object.entries(e))Ur.has(n)||(t[n]=i);return Tn(t)}function Tn(e){let t=In(e,"update-many");for(let n of Ce)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return En(t)}function Dc(e){if(ke(e.list)||ke(e.update)){let t=ke(e.update)?e.update:Cn(e);return{status:T(e,"filterStatus"),list:ke(e.list)?at(e.list):lt(e),update:Tn(t),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}return{status:T(e,"filterStatus"),list:lt(e),update:Cn(e),dryRun:e.dryRun===!0||e.dry_run===!0?!0:void 0,rollback:R(e,"rollback"),checkpoint:e.checkpoint===!1||e.noCheckpoint===!0||e.no_checkpoint===!0?!1:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4fd16197-979e-5269-bed7-f2fb0e2038c2")}catch{}})();function te(e,t){throw new g(e,_.USAGE,t)}var zr="2026-07-15T06:22:12.276Z",Gr=Date.parse(zr),qr=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],On=e=>typeof e=="string"?e:"",Dn=e=>{let t=e??{},n=On(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(On(t.ts))>=Gr);return qr[i][r]};function Fn(e,t,n=20,i=new Set,r=!1){let o=[],s=[],a={legacy_unknown:0,actionable_unknown:0},c=Math.max(0,n),l=0,d=0,u=0;for(let[m,f]of t.split(/\r?\n/).entries()){let k;try{k=JSON.parse(f)}catch{continue}l+=1;let p=Dn(k);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&s.push({item_id:e,line:m+1}),o.length<c&&o.push({item_id:e,line:m+1})}}return{checked_events:l,unknown_event_count:d,legacy_unknown_event_count:a.legacy_unknown,actionable_unknown_event_count:a.actionable_unknown,acknowledged_actionable_event_count:u,samples:o,samples_truncated:a.legacy_unknown+a.actionable_unknown>o.length,actionable_events:s}}var Uc=(e,t,n=20,i=new Set)=>Fn(e,t,n,i);function Hr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let o=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof o!="object"||o===null||!Array.isArray(o.events)))for(let s of o.events)typeof s=="object"&&s!==null&&typeof s.item_id=="string"&&Number.isSafeInteger(s.line)&&t.add(`${s.item_id}:${String(s.line)}`)}return t}var ut=async(e,t=20,n=!1)=>{let i=Le.join(e,"history"),r;try{r=(await Me.readdir(i)).filter(y=>y.endsWith(".jsonl")).sort((y,v)=>y.localeCompare(v))}catch{r=[]}let o=new Set,s=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,k="_workspace.jsonl",p=new Set;if(r.includes(k))try{p=Hr(await Me.readFile(Le.join(i,k),"utf8"))}catch{p=new Set}for(let y of r){let v;try{v=await Me.readFile(Le.join(i,y),"utf8")}catch{continue}let x=y.slice(0,-6),S=Fn(x,v,t-s.length,p,n);c+=1,l+=S.checked_events,d+=S.unknown_event_count,u+=S.legacy_unknown_event_count,m+=S.actionable_unknown_event_count,f+=S.acknowledged_actionable_event_count,S.unknown_event_count>0&&o.add(x),s.push(...S.samples),n&&a.push(...S.actionable_events)}let h=u+m;return{checked_streams:c,checked_events:l,unknown_event_count:d,legacy_unknown_event_count:u,actionable_unknown_event_count:m,acknowledged_actionable_event_count:f,affected_item_ids:[...o].sort((y,v)=>y.localeCompare(v)),samples:s,samples_truncated:h>s.length,...n?{actionable_events:a}:{}}};function Wr(e,t){let n=e.length>0;return n&&t&&te("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_conflict",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),!n&&!t&&te("Specify exactly one selector: repeat --event or pass --all-actionable.",{code:"history_author_acknowledge_selector_required",required:"Exactly one of --event or --all-actionable",examples:['pm history-author-acknowledge --event pm-a1b2:4 --attributed-author agent --reviewer maintainer --reason "Verified provenance"','pm history-author-acknowledge --all-actionable --attributed-author import-agent --reviewer maintainer --reason "Reviewed the complete actionable set"']}),{events:Vr(e),all_actionable:t}}function Vr(e){return e.map(t=>{let n=t.lastIndexOf(":"),i=t.slice(0,n).trim(),r=Number(t.slice(n+1)),o=i===Q||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!o||!Number.isSafeInteger(r)||r<1)&&te(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function zc(e,t){let n=Wr(dt(t.historyEvent),t.allActionable===!0||t.all_actionable===!0);return Kr(e,{events:n.events,all_actionable:n.all_actionable,attributed_author:R(t,"attributedAuthor")??R(t,"attributed_author")??"",reviewer:R(t,"reviewer")??"",reason:R(t,"reason")??""})}async function Kr(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),o=t.events??[],s=+(t.all_actionable===!0)+ +(o.length>0);s===0&&te("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&te("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let a=t.all_actionable===!0?(await ut(e,0,!0)).actionable_events:o;[a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&te("Author acknowledgment requires events, reviewer, attributed_author, and reason.",{code:"history_author_acknowledge_required_values_missing"});let l=[...new Map(a.map(m=>[`${m.item_id}:${m.line}`,{item_id:m.item_id,line:m.line}])).values()].sort((m,f)=>m.item_id.localeCompare(f.item_id)||m.line-f.line);for(let m of l){[m.item_id===Q||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&te(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let k;try{let h=(await Me.readFile(Le.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];k=JSON.parse(h??"")}catch{te(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Dn(k)!=="actionable_unknown"&&te(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,{code:"history_author_acknowledge_target_not_actionable"})}let d=await N(e),u=await pn({pmRoot:e,op:"history:author-acknowledge",author:n,context:{author_acknowledgment:{events:l,attributed_author:i}},message:r,lockTtlSeconds:d.locks.ttl_seconds,lockWaitMs:d.locks.wait_ms});return{acknowledged:l.length,history_path:u.historyPath}}import{readFile as $e,realpath as ht,writeFile as to}from"node:fs/promises";import{execFile as no}from"node:child_process";import O from"node:path";import{promisify as io}from"node:util";import{readFile as Yr,writeFile as Jr}from"node:fs/promises";import be from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="89261a49-97e5-5ffc-a81c-2409f0b529cf")}catch{}})();var Mn="# pm-cli:runtime-cache:start",mt="# pm-cli:runtime-cache:end",Ln=".agents/pm",ft=["runtime/","search/","locks/","transactions/","checkpoints/"],Xr=["search/eval-queries.json"];async function Pn(e){try{return await e()}catch(t){throw t instanceof Error&&"code"in t&&typeof t.code=="string"&&["EACCES","EPERM","EROFS"].includes(t.code)?new g("The workspace .gitignore is not writable.",_.GENERIC_FAILURE,{code:"init_gitignore_unwritable",reason:t.code.toLowerCase(),required:"Grant the current user read and write access to the workspace .gitignore before initialization.",why:"pm init must publish its managed runtime-cache ignore fence without replacing unrelated entries.",nextSteps:["Grant read and write access to the workspace .gitignore and rerun pm init.","If the workspace is intentionally read-only, initialize pm in a writable workspace or clone."]}):t}}function Nn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function pt(e){let t=e.replaceAll("\\","/");return be.isAbsolute(e)||t===".."||t.startsWith("../")}function Zr(e=Ln){let t=Nn(e);return[Mn,...ft.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Xr.map(n=>`!${t}/${n}`),mt].join(`
2
- `)}async function Yc(e,t={}){let n=be.join(e,".gitignore"),i=Ln;if(t.pmRoot!==void 0){let d=Nn(be.relative(be.resolve(e),be.resolve(t.pmRoot)));if(pt(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Pn(()=>Yr(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&V(d)))throw d}let o=r.indexOf(Mn),s=r.indexOf(mt),c=(o>=0&&s>=o?`${r.slice(0,o)}${r.slice(s+mt.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
3
-
4
- `:""}${Zr(i)}
5
- `;return l===r?{path:n,changed:!1}:(await Pn(()=>Jr(n,l,"utf8")),{path:n,changed:!0})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f97516b2-f75c-5ce0-82dc-f850466284c7")}catch{}})();var Qr="PM_SOURCE_CONTEXT_ACCESS",eo="PM_ALLOW_SOURCE_CONTEXT_WRITES";function $n(e){let t=e[Qr],n=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",i=n==="read_only"&&e[eo]?.trim()==="1";return{access:n,write_override_applied:i,source_writes_allowed:n==="write"||i}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5e1810a5-04b8-5929-8eee-7a63f1684860")}catch{}})();var gt=io(no),Ne="# pm-cli:merge-drivers:start",zn="# pm-cli:merge-drivers:end",me="# pm-cli:merge-drivers:v2:start",_t="# pm-cli:merge-drivers:v2:end",ro="merge-fence";function jn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Gn(){let e=Kt(import.meta.url,["../../.."]);return`${jn(process.execPath)} ${jn(O.join(e,"dist","cli.js"))}`}var qn=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function oo(e){let t=e.explicitPath?.trim(),n=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),i=e.environment.PM_SOURCE_PM_PATH?.trim(),r=$n(e.environment),o=!!(n&&i),s=t===void 0&&o&&(e.dryRun||r.source_writes_allowed);if(t!==void 0){let a=B(e.cwd,t);return{pm_root:a,workspace_start:a,source_coordinates_available:o,source_context_selected:!1,source_policy:r}}return s?{pm_root:O.resolve(i),workspace_start:O.resolve(n),source_coordinates_available:!0,source_context_selected:!0,source_policy:r}:{pm_root:o?B(e.cwd,".agents/pm"):B(e.cwd),workspace_start:e.cwd,source_coordinates_available:o,source_context_selected:!1,source_policy:r}}async function ve(e){try{let{stdout:t}=await gt("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ht(t.trim())}catch{return null}}async function Hn(e){let t=await ve(e);if(t===null)throw new g("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function yt(e,t){return O.relative(e,t).replaceAll("\\","/")}function Y(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Bn(e,t){if(e[t]!=="'")return null;let n="";for(let i=t+1;i<e.length;i+=1){if(e.startsWith(`'"'"'`,i)){n+="'",i+=4;continue}if(e[i]==="'")return{value:n,nextOffset:i+1};n+=e[i]}return null}async function so(e,t){let n=Bn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=Bn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(O.basename(n.value))||O.basename(i.value)!=="cli.js"||O.basename(O.dirname(i.value))!=="dist"||!await M(n.value)||!await M(i.value))return!1;try{let r=O.dirname(O.dirname(i.value)),o=JSON.parse(await $e(O.join(r,"package.json"),"utf8")),s=typeof o.bin=="object"&&o.bin!==null&&"pm"in o.bin?o.bin.pm:void 0;return o.name==="@unbrained/pm-cli"&&(o.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function wt(e,t){let n=e.length>0?`${e}/`:"",i=[`${Y(`${n}**/*.toon`)} merge=pm-item-toon`,`${Y(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${Y(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${Y(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${Y(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${Y(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${Y(`${n}settings.json`)} merge=pm-json`),i.push(`${Y(`${n}**/*.json`)} merge=pm-json`),i.push(`${Y(`${n}extensions/**`)} -merge`),i.push(`${Y(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}function Un(e,t,n){let i=e.indexOf(t),r=e.indexOf(n);return i>=0&&r>i?`${e.slice(0,i)}${e.slice(r+n.length)}`:e.replace(t,"").replace(n,"")}async function Wn(e,t,n){let i=O.join(e,".gitattributes"),r="";try{r=await $e(i,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&V(l)))throw l}let o=[me,...t,_t].join(`
6
- `),a=Un(Un(r,me,_t),Ne,zn).trimEnd(),c=`${a.length>0?`${a}
7
-
8
- `:""}${o}
9
- `;return c===r?{path:i,changed:!1}:(n||await to(i,c,"utf8"),{path:i,changed:!0})}function je(e){let t=K(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function Vn(e,t){let n=O.resolve(e),i=null,r="",o=n;for(let v=0;v<8;v+=1){let x=O.join(o,".gitattributes");try{let A=await $e(x,"utf8");if(A.includes(me)||A.includes(Ne)){i=o,r=A;break}}catch{}let S=O.dirname(o);if(S===o)break;o=S}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=O.join(i,".gitattributes"),a=r.includes(me),c=a?me:Ne,l=a?_t:zn,d=r.indexOf(c),u=r.indexOf(l),m=u>d?r.slice(d+c.length,u).split(`
10
- `).map(v=>v.trim()).filter(v=>v.length>0):[],f=wt(yt(i,n),t),k=new Set(m),p=new Set(f),h=f.filter(v=>!k.has(v)),y=m.filter(v=>!p.has(v));return{status:h.length>0||y.length>0?"drift":"ok",path:s,missing_patterns:h,stale_patterns:y,schema_scope:"project"}}async function Kn(e){let t=Gn(),n=[],i=[];for(let r of qn){let o=`merge.${r.key}.driver`,s=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await gt("git",["config","--local","--get",o],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await so(l,s)&&i.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function hl(e){let t;try{t=await Hn(O.resolve(e))}catch{return{status:"no_git"}}let n=yt(t,O.resolve(e)),i=await N(e),r=ue(void 0,i.author_default),o=await on(e,ro,i.locks.ttl_seconds,r,!1,_n(i).force_required_for_stale_lock,i.locks.wait_ms);try{let s=O.join(t,".gitattributes"),a;try{a=await $e(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&V(u))return{status:"not_installed",path:s};throw u}if(!a.includes(me)&&!a.includes(Ne))return{status:"not_installed",path:s};let c=await N(e),l=je(c),d=await Wn(t,wt(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await o()}}async function _l(e,t){let n=oo({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),i=n.pm_root;if(!await M(U(i)))throw new g(`Tracker is not initialized at ${i}. Run pm init first.`,_.NOT_FOUND);let r=await Hn(n.workspace_start);return ao({pmRoot:i,workspaceRoot:r,dryRun:e.dryRun===!0})}async function ao(e){let t=O.resolve(e.pmRoot),n=O.resolve(e.workspaceRoot),i=e.dryRun===!0,r,o;try{[r,o]=await Promise.all([ht(t),ht(n)])}catch(f){throw new g(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,_.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=yt(o,r);if(pt(s))throw new g(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,_.USAGE);let a=await N(r),c=je(a),l=wt(s,c),d=[],u=Gn();for(let f of qn)d.push({key:`merge.${f.key}.name`,value:f.name}),d.push({key:`merge.${f.key}.driver`,value:`${u} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!i)try{for(let f of d)await gt("git",["config","--local",f.key,f.value],{cwd:o,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new g(`Cannot install repository-local merge drivers in ${o}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,_.DEPENDENCY_FAILED,{code:"merge_git_config_unwritable",why:"pm merge install must persist clone-local driver commands before publishing their shared .gitattributes mappings.",nextSteps:["Make the repository Git config writable or wait for the process holding its lock to finish.",'Retry "pm merge install"; the operation is idempotent.','Use "pm merge install --dry-run --json" when the workspace is intentionally read-only.']})}let m=await Wn(o,l,i);return{ok:!0,dry_run:i,workspace_root:o,pm_root:r,gitattributes:{path:m.path,changed:m.changed,patterns:l,schema_scope:"project"},git_config:d,guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:Z()}}import{execFile as co}from"node:child_process";import{randomUUID as lo}from"node:crypto";import{readdir as uo,readFile as Xn}from"node:fs/promises";import j from"node:path";import{promisify as mo}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7b87b458-164a-5332-8803-6b0695481644")}catch{}})();var fo=mo(co);async function kt(e){try{let{stdout:t}=await fo("git",["rev-parse","--path-format=absolute","--git-path","pm-merge-receipts"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()}catch{return null}}async function Zn(e,t){let n=j.dirname(j.resolve(e,t));for(let i=0;i<12;i+=1){if(await M(j.join(n,"settings.json")))return n;let r=j.dirname(n);if(r===n)break;n=r}return null}function bt(e){return j.join(e,"merge-receipts")}function Be(e){return`${e}.json`}function po(e){return{receipt_id:e.id,item_id:e.item_id,item_path:e.item_path,conflict_fields:e.decisions.map(t=>t.field),fields_from_theirs:e.fields_from_theirs,union_fields:e.union_fields,requested_preference:e.requested_preference??e.preferred??"ours",conflict_resolution:e.conflict_resolution,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Yn(t.retained)??nt(tt(t.retained)),discarded_hash:Yn(t.discarded)??nt(tt(t.discarded))}))}}function Yn(e){if(typeof e!="object"||e===null||Array.isArray(e)||!("pm_value_hash"in e))return;let t=e.pm_value_hash;return typeof t=="string"&&/^[a-f0-9]{64}$/u.test(t)?t:void 0}async function Al(e){let t=await kt(e.cwd);if(t===null)return null;let n=e.itemPath.trim(),i=n.length>=2&&(n.startsWith("'")&&n.endsWith("'")||n.startsWith('"')&&n.endsWith('"'))?n.slice(1,-1):n,r=j.basename(i,j.extname(i)),o={version:1,id:lo(),item_path:i.replaceAll("\\","/"),item_id:r,requested_preference:e.preferred,conflict_resolution:e.conflictResolution??"preferred_side",fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:Z(),value_availability:"clone_local"};await Ze(t),await ce(j.join(t,Be(o.id)),`${JSON.stringify(o,null,2)}
11
- `);let s=await Zn(e.cwd,o.item_path);if(s!==null){let a=bt(s),c=po(o),l={...o,decisions:c.decisions.map(d=>({field:d.field,base:null,ours:null,theirs:null,retained:{pm_value_hash:d.retained_hash},discarded:{pm_value_hash:d.discarded_hash}})),value_availability:"hash_only"};await Ze(a),await ce(j.join(a,Be(o.id)),`${JSON.stringify(l,null,2)}
12
- `)}return o}async function Jn(e,t){if(!await M(e))return[];let n;try{n=await uo(e)}catch{return[]}let i=[];for(let r of n.sort((o,s)=>o.localeCompare(s)))if(r.endsWith(".json"))try{let o=JSON.parse(await Xn(j.join(e,r),"utf8")),{preferred:s,...a}=o,c={...a,requested_preference:o.requested_preference??s??"ours",conflict_resolution:o.conflict_resolution??"preferred_side"};c.version===1&&(t.includeReconciled||c.state==="pending")&&(t.includeLossless!==!1||c.decisions.length>0)&&i.push(c)}catch{}return i}async function vt(e,t={}){let n=await kt(e),i=n===null?[]:await Jn(n,t),r=t.pmRoot??j.join(e,".agents","pm"),o=await Jn(bt(r),t),s=new Map(o.map(a=>[a.id,a]));for(let a of i)s.set(a.id,a);return[...s.values()].sort((a,c)=>a.created_at.localeCompare(c.created_at))}function Qn(e){let t=[],n=[];for(let i of e)(Array.isArray(i.decisions)&&i.decisions.length>0?t:n).push(i);return{pendingDecisions:t,lossless:n}}async function El(e,t){let n=await kt(e);if(n===null)return;await ce(j.join(n,Be(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:Z()},null,2)}
13
- `);let i=await Zn(e,t.item_path);if(i!==null){let r=j.join(bt(i),Be(t.id));if(await M(r)){let o=JSON.parse(await Xn(r,"utf8"));await ce(r,`${JSON.stringify({...o,state:"reconciled",reconciled_at:Z()},null,2)}
14
- `)}}}async function Cl(e){let t=await vt(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:Z()}}import fe from"node:fs/promises";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:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="59b566d5-1d4f-500b-98e3-004e6f57d2b4")}catch{}})();async function ho(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let o;try{o=await fe.readdir(pe.join(e,r))}catch{return}for(let s of o)for(let a of Yt)if(s.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${s}`,id:s.slice(0,-a.length)});break}})),i.sort((r,o)=>r.relativePath.localeCompare(o.relativePath))}function _o(e,t){let{id:n,relativePath:i,liveItemIds:r,out:o}=e,s=ot(t);if(s){o.conflictMarkers.push({id:n,path:i,line:s.line,detail:`unresolved merge conflict marker ${s.marker}`});return}let a=null,c=t.split(/\r?\n/).map((l,d)=>({content:l.trim(),number:d+1})).filter(l=>l.content.length>0);for(let l of c)try{let d=JSON.parse(l.content);if(typeof d!="object"||d===null||Array.isArray(d))throw new TypeError("history entry must be an object");a=d}catch{o.unparseable.push({id:n,path:i,line:l.number,detail:"history line is not a valid JSON object"});return}a!==null&&(a.op==="delete"&&r.has(n)&&o.resurrected.push({id:n,deleted_at:typeof a.ts=="string"?a.ts:"",deleted_by:typeof a.author=="string"?a.author:""}),a.op==="history_repair"&&Array.isArray(a.patch)&&a.patch.length>0&&(o.repairReconciliations+=1))}function Rt(e,t){let n=typeof t=="object"&&t!==null&&"code"in t&&typeof t.code=="string"?t.code:"UNKNOWN";return`${e} could not be read (error code: ${n})`}async function go(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await fe.readdir(pe.join(e,"history"))}catch{return n}for(let r of i.sort((o,s)=>o.localeCompare(s))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let o;try{o=await fe.readFile(pe.join(e,"history",r),"utf8")}catch(s){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Rt("history stream",s)});continue}_o({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},o)}return n}function ei(e){let t=ot(e);if(t)return`unresolved merge conflict marker ${t.marker} at line ${t.line}`;try{return JSON.parse(e),null}catch(n){return`invalid JSON (${String(n)})`}}async function yo(e){let t=[],n=0,i=null;try{i=await Vt(U(e))}catch(o){n+=1,t.push({path:"settings.json",detail:Rt("configuration file",o)})}if(i!==null){n+=1;let o=ei(i);o!==null&&t.push({path:"settings.json",detail:o})}let r;try{r=await fe.readdir(pe.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let o of r.sort((s,a)=>s.localeCompare(a))){if(!o.endsWith(".json"))continue;n+=1;let s;try{s=await fe.readFile(pe.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:Rt("configuration file",c)});continue}let a=ei(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function ti(e,t,n,i={}){let r=await ho(e,n),o=new Set(r.map(u=>u.id)),s=new Map;for(let u of r){let m=s.get(u.id);m===void 0?s.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...s.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,k)=>f.localeCompare(k))})).sort((u,m)=>u.id.localeCompare(m.id)),c=(await Promise.all(r.map(async u=>{if(!t.has(u.id))return{path:u.relativePath,id:u.id};try{let m=pe.join(e,u.relativePath);return dn(await fe.readFile(m,"utf8"),{format:m.toLowerCase().endsWith(".md")?"json_markdown":"toon",schema:i.schema,extensionFieldNames:i.extensionFieldNames}),null}catch{return{path:u.relativePath,id:u.id}}}))).filter(u=>u!==null),l=await go(e,o),d=await yo(e);return{item_files_on_disk:r.length,item_ids_on_disk:o.size,parsed_items:t.size,unreadable_item_files:c,duplicate_item_ids:a,history_streams_scanned:l.scanned,history_conflict_marker_streams:l.conflictMarkers,history_unparseable_streams:l.unparseable,resurrected_items:l.resurrected,history_repair_reconciliations:l.repairReconciliations,config_files_scanned:d.scanned,unparseable_config_files:d.unparseable}}import{execFile as wo}from"node:child_process";import ni from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b8b3f729-be32-5a77-b08f-f616ee068e0f")}catch{}})();function ii(e,t){return new Promise((n,i)=>{wo("git",[...t],{cwd:e,encoding:"utf8",maxBuffer:4*1024*1024},(r,o)=>{r?i(r):n(o)})})}function ri(e){if(e&&(!Number.isSafeInteger(e.start)||!Number.isSafeInteger(e.end)||e.start<1||e.end<e.start))throw new RangeError("Source line range must be inclusive positive integers with end >= start.")}function Bl(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(ri(n),!n)throw new RangeError("Source line range must use start:end.");return n}function ko(e){let t=new Map;for(let n of e.split(`
15
- `)){let i=/^([0-9a-f^]{40,64}) \d+ \d+(?: \d+)?$/u.exec(n)?.[1];i&&t.set(i,(t.get(i)??0)+1)}return t}function bo(e){let t=e.split("\0"),n=new Map;for(let i=0;i+1<t.length;i+=2){let r=t[i]?.trim();if(!r)continue;let o=[...new Set(t[i+1]?.match(/\bpm-[a-z0-9][a-z0-9-]{2,63}\b/gu)??[])].sort((s,a)=>s.localeCompare(a));n.set(r,o)}return n}async function vo(e){let t=ni.relative(e.workspaceRoot,ni.resolve(e.workspaceRoot,e.sourcePath)),n=await ii(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await ii(e.workspaceRoot,["log","-n","256","--format=%H%x00%B%x00","--",t]);return{commitLines:ko(n),commitItems:bo(i),available:!0}}function Ro(e){let t=e.current.nodes.at(-1),n=e.current.kinds.length+1,i;for(let r of e.graph.incidentEdges(t)){let o=r.source===t,s=o?r.target:r.source;if((e.visitedDepth.get(s)??Number.POSITIVE_INFINITY)<n)continue;e.visitedDepth.set(s,n);let a=e.graph.registry().require(r.kind),c={nodes:[...e.current.nodes,s],kinds:[...e.current.kinds,o?r.kind:a.inverse??r.kind]};e.details.get(s)?.type?.toLowerCase()==="decision"?(i=n,e.found.push(c)):e.queue.push(c)}return i}function So(e){let t=[{nodes:[e.itemId],kinds:[]}],n=new Map([[e.itemId,0]]),i=[],r;for(;t.length>0;){let o=t.shift(),s=o.kinds.length;r!==void 0&&s>=r||s>=e.maxDepth||(r=Ro({current:o,graph:e.graph,details:e.details,visitedDepth:n,queue:t,found:i})??r)}return i.sort((o,s)=>o.nodes.join("\0").localeCompare(s.nodes.join("\0"))),i}function xo(e,t,n){let i=Sn(t);if(!i.graph.hasNode(e))return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let r=So({itemId:e,maxDepth:n,graph:i.graph,details:new Map(i.details.map(a=>[a.id,a]))}),o=r[0];if(!o)return{status:"not_found",nodes:[],kinds:[],alternative_decision_ids:[]};let s=[...new Set(r.map(a=>a.nodes.at(-1)))];return{status:s.length===1?"found":"ambiguous",nodes:o.nodes,kinds:o.kinds,alternative_decision_ids:s.slice(1)}}async function Ao(e){if(!e.lineRange)return{commitLines:new Map,commitItems:new Map,available:!0};try{return await vo({workspaceRoot:e.workspaceRoot,sourcePath:e.paths[0],lineRange:e.lineRange})}catch{return{commitLines:new Map,commitItems:new Map,available:!1}}}function Eo(e){let t=[];return e.hasLineRange&&!e.attributionAvailable&&t.push("git_attribution_unavailable"),e.hasLineRange&&e.contributionLines===0&&t.push("line_attribution_unmapped"),e.decisionStatus==="ambiguous"&&t.push("multiple_governing_decisions"),e.decisionStatus==="not_found"&&t.push("governing_decision_not_found"),t}function Co(e){return[...e.commitLines.keys()].filter(t=>(e.commitItems.get(t)?.length??0)>0)}async function oi(e){ri(e.lineRange);let t=e.decisionDepth??8;if(!Number.isSafeInteger(t)||t<1||t>32)throw new RangeError("Decision path depth must be an integer from 1 to 32.");let n=await Ao(e),i=Co(n),r=new Map;for(let o of e.candidates){let s=[...n.commitLines.entries()].filter(([d])=>n.commitItems.get(d)?.includes(o.item.id)),a=s.reduce((d,[,u])=>d+u,0),c=xo(o.item.id,e.corpus,t),l=Eo({hasLineRange:e.lineRange!==void 0,attributionAvailable:n.available,contributionLines:a,decisionStatus:c.status});r.set(o.item.id,{score:a*100+o.files.length*10+Math.max(0,9-Math.floor((Date.now()-Date.parse(o.item.updated_at))/(720*60*60*1e3))),contribution_lines:a,evidence:[...o.files.map(d=>({kind:"linked_file",reference:d.path})),...s.map(([d,u])=>({kind:"git_commit",reference:d.slice(0,12),contribution_lines:u}))],rationale:{value:o.item.value?.trim()||null,why_now:o.item.why_now?.trim()||null,outcome:o.item.outcome?.trim()||null,objective:o.item.objective?.trim()||null},decision_path:c,ambiguities:l})}return{explanations:r,receipt:{line_range:e.lineRange??null,blamed_commit_count:n.commitLines.size,mapped_commit_count:i.length,unmapped_commit_count:n.commitLines.size-i.length,decision_depth:t}}}import Nt from"node:fs/promises";import{realpathSync as Ys}from"node:fs";import{execFile as Js}from"node:child_process";import $ from"node:path";import{promisify as Xs}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="31d625d8-44be-5298-ab64-c17508ed07d0")}catch{}})();var Io=Object.freeze([{code:"missing_directory",command:"pm init",summary:"Recreate missing tracker directories (pm init is idempotent and restores the scaffold)."},{code:"settings_read_fs_error",command:"pm config list --json",summary:"settings.json could not be read as a regular file and pm fell back to defaults; repair the reported path or permissions, then re-run."},{code:"settings_read_invalid_json",command:"pm config list --json",summary:"settings.json is not valid JSON and pm fell back to defaults; fix the syntax error in the reported path, then re-run."},{code:"settings_read_invalid_schema",command:"pm config list --json",summary:"settings.json failed schema validation and pm fell back to defaults; correct the reported key in the file, then re-run."},{code:"settings_read_merge_failed",command:"pm config list --json",summary:"Global/project settings could not be merged; reconcile the conflicting keys in the reported settings files."},{code:"settings:id_prefix_empty",command:"pm config list --json",summary:'id_prefix is empty; set a non-empty "id_prefix" in settings.json so generated item ids are well-formed.'},{code:"settings:locks_ttl_non_positive",command:"pm config list --json",summary:'locks.ttl_seconds must be positive; set a positive "locks.ttl_seconds" in settings.json.'},{code:"telemetry_state_invalid_json",command:"pm health --check-telemetry",summary:"Local telemetry state file is corrupt; pm recreates it on the next flush. Advisory only."},{code:"telemetry_queue_invalid_rows",command:"pm health --check-telemetry",summary:"The telemetry queue has unparseable rows; they are skipped on the next flush. Advisory only."},{code:"telemetry_queue_pending",command:"pm health --check-telemetry",summary:"Telemetry events are queued; they flush automatically on the next reachable command. Advisory only."},{code:"telemetry_queue_high_retries",command:"pm telemetry flush",summary:"Some queued telemetry events are near retry exhaustion; flush now and verify endpoint reachability before entries are dropped."},{code:"telemetry_endpoint_probe_failed",command:"pm health --check-telemetry",summary:"The telemetry endpoint is unreachable; events stay queued until it recovers. Advisory only."},{code:"telemetry_endpoint_probe_http_status",command:"pm health --check-telemetry",summary:"The telemetry endpoint returned a non-success status; events stay queued until it recovers. Advisory only."},{code:"telemetry_schema_version_behind",command:"pm health --check-telemetry",summary:"Client schema is behind server; upgrade pm-cli to emit the latest event shape."},{code:"telemetry_otel_export_failing",command:"pm health --check-telemetry",summary:"OTLP trace spans are queued but the traces endpoint export is failing; spans retry automatically on the next reachable command, or set PM_TELEMETRY_OTEL_DISABLED=1 to skip OTLP export. Advisory only."},{code:"integrity_item_unreadable",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file could not be read; restore or repair the file at the reported path."},{code:"integrity_item_parse_failed",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file failed to parse; fix the malformed item metadata at the reported path."},{code:"integrity_item_conflict_marker",command:"pm validate --check-files --verbose-diagnostics",summary:"An item file contains Git conflict markers; resolve the <<<<<<< / >>>>>>> markers at the reported line."},{code:"integrity_history_unreadable",command:"pm history-repair <id>",summary:"A history stream could not be read; re-anchor the affected item's history chain."},{code:"integrity_history_invalid_json",command:"pm history-repair <id>",summary:"A history stream contains invalid JSON; re-anchor the affected item's history chain."},{code:"integrity_history_conflict_marker",command:"pm history-repair <id>",summary:"A history stream contains Git conflict markers; resolve the markers, then re-anchor the chain."},{code:"validate_storage_unreadable_items",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"An on-disk item file cannot be parsed (for example a botched merge resolution with stale TOON count headers); repair or restore the file at the reported path \u2014 list commands silently skip it while pm get hard-errors."},{code:"validate_storage_duplicate_item_ids",command:"pm validate --check-storage-integrity --verbose-diagnostics",summary:"One item id is claimed by multiple item documents \u2014 usually two branches minting the same id for different items before merging (GH-600). Keep one document, recreate the other item under a fresh id (pm copy, then delete the colliding file), and consider raising ids.token_length for concurrent multi-agent work."},{code:"validate_storage_history_conflict_markers",command:"pm merge driver history <base> <ours> <theirs>",summary:"A history stream contains unresolved Git conflict markers; re-merge it with the pm history merge driver (or resolve the markers by hand), then run pm history-repair for the item."},{code:"validate_storage_unparseable_history",command:"pm history-repair <id>",summary:"A history stream's newest line is not valid JSONL; repair or restore the stream before further mutations."},{code:"validate_storage_resurrected_items",command:"pm delete <id>",summary:"A live item's newest history operation is a delete: a delete/modify merge silently resurrected it. Decide the winner \u2014 re-delete the item, or keep it and append a mutation documenting the revival."},{code:"validate_storage_unparseable_config",command:"pm merge driver json <base> <ours> <theirs>",summary:"settings.json or a schema file cannot be parsed, so pm silently falls back to defaults; re-merge it with the pm JSON merge driver or fix the file by hand, then rerun pm validate."},{code:"validate_merge_fence_drift",command:"pm merge install",summary:"The committed .gitattributes merge fence no longer matches the active schema's type folders or tracker JSONL stores; rerun pm merge install (and commit .gitattributes) so every tracker artifact keeps its field-aware merge driver."},{code:"validate_storage_tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command, commit the index-only removals and managed .gitignore fence, then rerun validation."},{code:"integrity_item_outdated_format_version",command:"pm validate --verbose-diagnostics",summary:"An item predates the current storage format version; a pm storage migration rewrites it. Use --verbose-diagnostics to list the affected items."},{code:"integrity_item_ahead_format_version",command:"npm install -g @unbrained/pm-cli@latest",summary:"An item was written by a newer pm format version than this runtime supports; upgrade pm to read and validate it safely."},{code:"tracked_runtime_cache_files",command:"git rm --cached -r -- <tracked-runtime-directories>",summary:"Clone-local tracker runtime artifacts are committed. Run the exact tracked_runtime_cache.remediation_command from the integrity check, commit the index-only removals, and keep the managed .gitignore fence."},{code:"merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts, re-apply any intended discarded values, then run pm merge reconcile; lossy receipts require explicit --force acceptance."},{code:"validate_merge_decisions_unreviewed",command:"pm merge reconcile --dry-run",summary:"Review the pending merge receipts before reconciliation; history-repair alone does not settle them, and lossy receipts require explicit --force acceptance."},{code:"history_drift_missing_stream",command:"pm history-repair <id>",summary:"The item has no history stream; re-anchor the chain to rebuild it (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_unreadable_stream",command:"pm history-repair <id>",summary:"The item's history stream is unreadable; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_hash_mismatch",command:"pm history-repair <id>",summary:"The item's content hash no longer matches its history; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_drift_chain_mismatch",command:"pm history-repair <id>",summary:"The item's history chain is broken; re-anchor the chain (pm history-repair --all repairs every drifted stream in one pass)."},{code:"history_stream_over_compact_threshold",command:"pm history-compact <id>",summary:"The history stream exceeds the configured compaction threshold; compact it (pm history-compact --all-streams sweeps every over-threshold stream in one pass)."},{code:"history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"validate_history_unknown_author_events",command:'pm history-author-acknowledge --all-actionable --attributed-author "<principal>" --reviewer "<reviewer>" --reason "<evidence>"',summary:"Review the actionable coordinates, then record an append-only attribution disposition for the complete current set."},{code:"locks_stale_count",command:"pm gc --scope locks",summary:"Stale item-claim locks (embedded ttl elapsed) can block mutations; sweep them \u2014 gc retains active and unparseable locks."},{code:"locks_unreadable",command:"pm gc --scope locks --dry-run",summary:"Some lock files could not be read; preview the sweep and inspect the unreadable files manually \u2014 gc never deletes what it cannot read."},{code:"extension_update_health_partial_coverage",command:"pm extension --adopt-all --project",summary:"Update-health coverage is partial because unmanaged extensions were skipped; adopt the existing installs into managed metadata so the update scan covers them (use --global for global-scope extensions, or pm package --adopt-all when working with packages)."},{code:"vectorization_stale_items_remaining",command:"pm health --refresh-vectors",summary:"Some items have stale embeddings; refresh vectors so semantic search results stay current."},{code:"vectorization_embedding_identity_changed",command:"pm reindex --mode semantic",summary:"Embedding provider/model changed since the last index; run a semantic reindex to rebuild vectors."},{code:"validate_metadata_missing_acceptance_criteria",command:'pm update <id> --acceptance-criteria "<criteria>"',summary:"Backfill the missing acceptance criteria on the reported item(s)."},{code:"validate_metadata_missing_estimate",command:'pm update <id> --estimate "<estimate>"',summary:"Backfill the missing estimate on the reported item(s)."},{code:"validate_metadata_missing_close_reason",command:'pm update <id> --close-reason "<reason>"',summary:"Backfill the missing close reason on the reported closed item(s)."},{code:"validate_metadata_missing_reviewer",command:'pm update <id> --reviewer "<name>"',summary:"Backfill the missing reviewer on the reported item(s)."},{code:"validate_metadata_missing_risk",command:'pm update <id> --risk "<level>"',summary:"Backfill the missing risk on the reported item(s)."},{code:"validate_metadata_missing_confidence",command:'pm update <id> --confidence "<level>"',summary:"Backfill the missing confidence on the reported item(s)."},{code:"validate_metadata_missing_sprint",command:'pm update <id> --sprint "<sprint>"',summary:"Backfill the missing sprint on the reported item(s)."},{code:"validate_metadata_missing_release",command:'pm update <id> --release "<release>"',summary:"Backfill the missing release on the reported item(s)."},{code:"validate_metadata_custom_profile_missing_required_fields",command:'pm config set metadata-required-fields --criterion "<field>"',summary:"Config-driven finding: the custom metadata profile has no required fields configured and falls back to core, so configure the fields rather than mutating items."},{code:"validate_metadata_duplicate_issue_codes",command:'pm update <id> --title "<distinct title>"',summary:"Two or more items share one logical issue code (GH-235); give each a distinct title so the derived code is unique, or close the redundant item with pm close <id> --duplicate-of <canonical-id> (closed-as-duplicate items are excluded from the check)."},{code:"validate_resolution_missing_fields",command:'pm update <id> --resolution "<how resolved>"',summary:"Backfill resolution / expected_result / actual_result on the reported closed item(s)."},{code:"validate_lifecycle_active_closure_like_metadata",command:"pm update <id> --unset <closure-like-field>",summary:"Clear the closure-like field the validator flags on this active item \u2014 the detail row names it (resolution / actual-result / blocked-reason) \u2014 or close the item if it is actually done."},{code:"validate_lifecycle_active_terminal_parent",command:"pm update <id> --parent <active-parent-id>",summary:"Reopen the terminal parent or move the active child under a non-terminal parent."},{code:"validate_lifecycle_stale_blockers",command:"pm update <id> --unset blocked-by --unset blocked-reason",summary:"Resolve the stale blocker the validator flags: clear blocked-by/blocked-reason when they linger on a non-blocked item or report a resolved blocker; if instead a blocked item is missing blocker context, add the context or move it out of a blocked status."},{code:"validate_lifecycle_dependency_cycles_error",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_lifecycle_dependency_cycles",command:"pm update <id> --dep-remove <dep-id>",summary:"Break the dependency cycle by removing one edge from the reported cycle."},{code:"validate_hierarchy_parent_cycle_error",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_hierarchy_parent_cycle",command:"pm update <id> --parent <other-id>",summary:"Break the parent-hierarchy cycle by reparenting one item in the reported cycle to a non-cyclic parent (or clear it with pm update <id> --unset parent)."},{code:"validate_files_missing_linked_paths",command:"pm <files|docs> <id> --remove <path>",summary:"The check spans both item.files and item.docs under one code: restore the missing linked artifact, or unlink it with pm files (linked file) or pm docs (linked doc)."},{code:"validate_files_orphaned_paths",command:"pm <files|docs> <id> --add <path>",summary:"Link the orphaned artifact with pm files (file) or pm docs (doc), or remove it from the workspace."},{code:"validate_files_tracked_all_strict_forces_pm_internals",command:"pm validate --check-files --include-pm-internals",summary:"tracked-all-strict scan flagged pm internals; re-run with --include-pm-internals or a softer --scan-mode."},{code:"validate_history_drift_missing_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items missing a history stream."},{code:"validate_history_drift_unreadable_streams",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with an unreadable history stream."},{code:"validate_history_drift_hash_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items whose content hash drifted."},{code:"validate_history_drift_chain_mismatches",command:"pm history-repair <id>",summary:"Re-anchor the history chains of the items with a broken history chain."},{code:"validate_command_references_stale_pm_ids",command:'pm update <id> --replace-tests --test "command=<corrected-command>" [--test ...]',summary:"Correct the stale pm-ID inside the item's linked test command (the check scans tests[].command, not the body). --replace-tests overwrites the entire tests list, so re-include the item's other linked tests in the same call."},{code:"validate_format_version_outdated_items",command:"pm validate --verbose-diagnostics",summary:"One or more items predate the current storage format version; a pm storage migration rewrites them. Use --verbose-diagnostics to list the affected items."},{code:"validate_format_version_ahead_items",command:"npm install -g @unbrained/pm-cli@latest",summary:"One or more items were written by a newer pm format version than this runtime supports; upgrade pm to read and validate them safely."}]);function To(e){if(typeof e!="string")return;let t=e.trim();for(let n of Io)if(t===n.code||t.startsWith(`${n.code}:`))return n}function Oo(e){let t={};for(let n of e){let i=To(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function si(e){return Object.values(Oo(e))}import he from"node:fs/promises";import{createHash as Do}from"node:crypto";import ci from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a6714da6-6e2b-5647-bfde-607a54d7e4cd")}catch{}})();var li=4,Fo="history-drift-cache.json";function di(e){return ci.join(e,"runtime",Fo)}async function Po(e){try{let t=await he.readFile(di(e),"utf8"),n=JSON.parse(t);return n.version!==li||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}async function Mo(e,t,n,i,r){let o=fn(e),s;try{s=await he.stat(o)}catch(l){return V(l)||r.unreadableStreams.push(Q),!1}let a=r.missingStreams.length,c=await mi({itemId:Q,historyPath:o,stat:s,cached:t[Q],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(Q),n[Q]={mtime_ms:s.mtimeMs,ctime_ms:s.ctimeMs,size:s.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk,item_hash_version:c.verification.itemHashVersion},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function ui(e){return Do("sha256").update(e).digest("hex")}async function Lo(e){let t=await he.readFile(e,"utf8");return ui(t)}async function No(e){let t=await he.readFile(e,"utf8"),n=ui(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let a=s.trim();if(a.length===0)continue;let c=JSON.parse(a);if(typeof c.after_hash!="string"||c.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(c),r=c.after_hash}if(!r)return null;let o=mn(i);return{latestAfterHash:r,chainOk:o.ok,contentHash:n,itemHashVersion:o.item_hash_version??st}}function $o(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function ai(e,t,n){try{let i=await No(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function mi(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!($o(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await ai(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await Lo(e.historyPath)}catch{return e.accumulator.unreadableStreams.push(e.itemId),{verification:null,cacheDirty:!1}}else i=t;return!e.verifyCacheHitByContent||i===t?{verification:{latestAfterHash:e.cached.latest_after_hash,chainOk:e.cached.chain_ok,contentHash:i,itemHashVersion:e.cached.item_hash_version??st},cacheDirty:!1}:{verification:await ai(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function fi(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},o=(await Po(e))?.entries??{},s={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Jt(e,u.id),f;try{f=await he.stat(m)}catch(x){V(x)?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let k=o[u.id],p=await mi({itemId:u.id,historyPath:m,stat:f,cached:k,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),s[u.id]={mtime_ms:f.mtimeMs,ctime_ms:f.ctimeMs,size:f.size,content_hash:p.verification.contentHash,latest_after_hash:p.verification.latestAfterHash,chain_ok:p.verification.chainOk,item_hash_version:p.verification.itemHashVersion};let{body:h,...y}=u;un({metadata:y,body:h},p.verification.itemHashVersion)!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await Mo(e,o,s,c,i);if(a||=l,a||Object.keys(o).length!==Object.keys(s).length){let u=di(e);try{await he.mkdir(ci.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:li,entries:s}))}catch{}}let d=[...new Set([...i.missingStreams,...i.unreadableStreams,...i.hashMismatches,...i.chainMismatches])].sort((u,m)=>u.localeCompare(m));return{...i,driftedItems:d}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="ab236f47-a866-5236-b8da-f7f23140b978")}catch{}})();var jo=["metadata","resolution"],St=["metadata","resolution","estimates","lifecycle"],Bo="completed";function xt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function pi(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function hi(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=pi(n.close_reason)??Bo;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${xt(i)}`,gate:"resolution"})}return t}function _i(e){let t=[];for(let n of e){let i=pi(n.resolution);i!==void 0&&t.push({item_id:n.id,check:"metadata",field:"close_reason",kind:"set_close_reason",value:i,command:`pm update ${n.id} --close-reason ${xt(i)}`,gate:"metadata"})}return t}function gi(e,t){return e.map(n=>{let i=hn(n.type,t);return{item_id:n.id,check:"metadata",field:"estimated_minutes",kind:"set_estimate",value:String(i),command:`pm update ${n.id} --estimate ${i}`,gate:"estimates"}})}function yi(e){return e.map(t=>t.grandparent_id!==void 0&&t.grandparent_active===!0?{item_id:t.id,check:"lifecycle",field:"parent",kind:"reparent",parent_id:t.grandparent_id,command:`pm update ${t.id} --parent ${t.grandparent_id}`,gate:"lifecycle"}:{item_id:t.id,check:"lifecycle",field:"parent",kind:"unset_parent",command:`pm update ${t.id} --unset parent`,gate:"lifecycle"})}function wi(e){let t=[];for(let n of e){if(n.classification!=="deleted")continue;let i=n.link_kind==="files"?"files":"docs";t.push({item_id:n.item_id,check:"files",field:n.link_kind,kind:n.link_kind==="files"?"prune_file_link":"prune_doc_link",path:n.path,command:`pm ${i} ${n.item_id} --remove ${xt(n.path)}`})}return t}function ki(e){let t=(e??[]).flatMap(i=>i.split(",")).map(i=>i.trim()).filter(i=>i.length>0);if(t.length===0){if(e!==void 0&&e.length>0)throw new g(`--fix-scope values must not be empty. Supported values: ${St.join(", ")}.`,_.USAGE);return new Set(jo)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(St.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${St.join(", ")}.`,_.USAGE)}return n}function bi(e,t){let n=[],i=[];for(let r of e)r.gate!==void 0&&!t.has(r.gate)?i.push(r):n.push(r);return{applicable:n,gated:i}}function Re(e){return{item_id:e.item_id,check:e.check,field:e.field,command:e.command,...e.gate!==void 0?{gate:e.gate}:{}}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="087bac58-e32d-5cb8-8fda-0e09075c3f35")}catch{}})();var Uo=/^([A-Z][A-Z0-9]*-\d+)\b/;function zo(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Uo.exec(t);return n?n[1]:null}function vi(e){return typeof e=="string"&&e.trim().length>0}function Ri(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||vi(i.duplicate_of))continue;let r=zo(i.title);if(r===null)continue;let o=t.get(r);o||(o=[],t.set(r,o)),o.some(s=>s.id===i.id)||o.push({id:i.id,title:i.title,parent:vi(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let o=new Set(r.map(c=>c.id.toLowerCase())),s=r.filter(c=>c.parent===null||!o.has(c.parent.toLowerCase()));if(s.length<2)continue;let a=[...s].sort((c,l)=>c.id.localeCompare(l.id));n.push({code:i,count:a.length,ids:a.map(c=>c.id),titles:a.map(c=>c.title)})}return n.sort((i,r)=>i.code.localeCompare(r.code))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1951b0f1-11fa-5728-b516-7458a55b1e29")}catch{}})();function Si(e){let t=new Map;for(let i of e){let r=t.get(i.item_type);r||(r=new Map,t.set(i.item_type,r)),r.set(i.field,(r.get(i.field)??0)+1)}let n={};for(let i of[...t.keys()].sort((r,o)=>r.localeCompare(o))){let r=t.get(i),o={};for(let s of[...r.keys()].sort((a,c)=>a.localeCompare(c)))o[s]=r.get(s);n[i]=o}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5a5b0bd8-d99b-52fb-82ae-52ba48c54c30")}catch{}})();var xi=3;function Ai(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Ei(e,t,n=xi){let i=Number.isFinite(n)&&n>=1?Math.floor(n):xi,r=new Map;for(let o of t){let s=Ai(o);if(s.length===0)continue;let a=r.get(s);a?a.push(o):r.set(s,[o])}return e.map(o=>{let s=(r.get(Ai(o))??[]).filter(a=>a!==o).sort((a,c)=>a.localeCompare(c));return s.length===0?{path:o,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:o,classification:"moved",candidates:s.slice(0,i),candidates_truncated:s.length>i}})}function Ci(e){return e.map(t=>t.classification==="moved"?`${t.path}:moved:${t.candidates[0]}`:`${t.path}:deleted`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2b9ba0a4-396f-5870-bc89-e7fc789bb49d")}catch{}})();var Go=/^[a-z][a-z0-9+.-]+:\/\//i;function Se(e){return Go.test(e.trim())}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e063d634-4306-5725-927a-5f2af1722458")}catch{}})();function qo(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Ii(e){return`${e.item_id} ${e.link_kind}`}function Ti(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=qo(r.classification,i.classification),r.owners.set(Ii(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Ii(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(o=>{let s=t(o.item_id);return{id:o.item_id,type:s?.type??"Unknown",title:s?.title??"",status:s?.status??"",field:o.link_kind}}).sort((o,s)=>{let a=o.id.localeCompare(s.id);return a!==0?a:o.field.localeCompare(s.field)})}))}function Ho(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Oi(e){let t=[];for(let n of e)for(let i of n.items)t.push(`${n.path}:${n.classification} owner=${i.id} status=${i.status} field=${i.field} title="${Ho(i.title)}"`);return t}import{execFile as Wo}from"node:child_process";import{realpath as Vo}from"node:fs/promises";import Di from"node:path";import{promisify as Ko}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d18b51d7-294a-52da-b1cf-a10f24aefbc9")}catch{}})();var Yo=Ko(Wo),Jo=32*1024*1024,Xo=1e4,Zo=["search/eval-queries.json"];function At(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Qo(e){return`'${e.replaceAll("'","'\\''")}'`}async function es(e,t=Vo){return t(e).catch(()=>Di.resolve(e))}async function Fi(e){let t=await ve(e);if(t===null)return{git_workspace_root:null,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let n=await es(e),i=At(Di.relative(t,n));if(i.length===0)return{git_workspace_root:t,tracker_relative_root:null,tracked_paths:[],tracked_path_count:0,remediation_command:null};let r=ft.map(o=>`${i}/${At(o)}`);try{let{stdout:o}=await Yo("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Jo,windowsHide:!0,timeout:Xo}),s=new Set(Zo.map(l=>`${i}/${l}`)),a=[...new Set(o.split("\0").filter(l=>l.length>0&&!s.has(At(l))))].sort((l,d)=>l.localeCompare(d)),c=r.filter(l=>a.some(d=>d===l||d.startsWith(`${l}/`)));return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:a,tracked_path_count:a.length,remediation_command:a.length===0?null:`git rm --cached -r -- ${c.map(l=>Qo(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import ts from"node:fs/promises";import z from"node:path";import ns from"fast-glob";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="585364aa-e5ff-56b6-8276-8f741fbd6be4")}catch{}})();var is=["path","scope","note"],rs=["pattern","glob","path","scope","note"],os=["path"],ss=["from","to"],as=new Set(["note","scope"]);function Mi(e){let t=e??"project";if(!Xe.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Xe.join(", ")} (default: project).`,_.USAGE);return t}function Li(e){return e.startsWith("```")||e.includes(`
16
- `)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:kn(e)}function cs(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Li(n)||!n.includes(",")?[t]:vn(n)})}function ls(e,t){return e?cs(e).map(n=>{let i=n.trim(),r=Li(i)?ye(n,"--add"):{path:i};if(we(r,"--add",is),!r.path)throw new g(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:r.path,scope:Mi(r.scope),note:r.note?.trim()||void 0}}):[]}function ds(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--add-glob requires a glob pattern value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=ye(n,"--add-glob");we(i,"--add-glob",rs);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new g("--add-glob key/value form requires pattern=<glob>",_.USAGE);return{pattern:r,scope:Mi(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function us(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new g("--remove requires a path value",_.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=ye(n,"--remove"),r=Object.keys(i).filter(o=>as.has(o.toLowerCase()));if(r.length>0)throw new g(`--remove identifies a linked artifact by path only and does not accept ${r.map(o=>`"${o}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,_.USAGE);if(we(i,"--remove",os),!i.path)throw new g("--remove key/value form requires path=<value>",_.USAGE);return i.path}return n}):[]}function ms(e){return e?e.map(t=>{let n=ye(t,"--migrate");we(n,"--migrate",ss);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new g("--migrate requires from=<value> and to=<value>",_.USAGE);return{from:i,to:r}}):[]}function xe(e,t){let n=e;for(let i of t)n.startsWith(i.from)&&(n=`${i.to}${n.slice(i.from.length)}`);return n}function fs(e,t,n=[]){if(e.length===0||t.length===0)return;let i=new Set(e.map(o=>xe(o.path,n))),r=[...new Set(t.map(o=>xe(o,n)).filter(o=>i.has(o)))].sort((o,s)=>o.localeCompare(s));if(r.length!==0)throw new g(`Linked artifact mutation cannot add and remove the same normalized path in one transaction: ${r.join(", ")}. Split the replacement into separate commands so each history event has one unambiguous intent.`,_.USAGE,{code:"linked_artifact_mutation_conflict",reason:"same_path_added_and_removed",required:"Use distinct normalized paths for --add and --remove in one invocation.",why:"Conflicting batch intent cannot be applied deterministically without silently discarding metadata or a removal.",nextSteps:["Run the removal and addition as separate commands with a --message describing each intent."]})}function ne(e){return e.split(z.sep).join("/")}function Et(e,t,n=process.cwd()){let i=e.trim();if(Se(i))return i;if(z.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return ne(i.replaceAll("\\",z.sep));let r=z.relative(t,n);return r.startsWith(`..${z.sep}`)||r===".."||z.isAbsolute(r)?ne(z.normalize(i)):ne(z.relative(t,z.resolve(n,i)))}async function ps(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let o=z.isAbsolute(r.pattern),s=await ns(r.pattern,{cwd:n,absolute:o,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(s.map(c=>Et(c,t,n)))].sort((c,l)=>c.localeCompare(l));for(let c of a)i.push({path:c,scope:r.scope,note:r.note})}return i}function hs(e,t,n){if(t===void 0)return e;if(!n)throw new g("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",_.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function _s(e){return`${e.path}::${e.scope}`}function Ct(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function It(e){return[...new Map(e.map(t=>[_s(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function gs(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],o=[],s=[];for(let a of n){if(Se(a)){s.push(a.trim());continue}let c=z.isAbsolute(a)?a:z.resolve(t,a);try{(await ts.stat(c)).isFile()?i.push(a):o.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&Wt(l)){r.push(a);continue}o.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:o,remote_references:s}}function ys(e,t,n,i){let r=0;for(let s=0;s<e.length;s+=1){let a=xe(e[s].path,i);a!==e[s].path&&(e[s]={...e[s],path:a},r+=1)}return{adds:t.map(s=>{let a=xe(s.path,i);return a!==s.path&&(r+=1),{...s,path:a}}),removes:n.map(s=>xe(s,i)),count:r}}function ws(e,t,n,i){for(let o of t)e.some(s=>s.path===o.path&&s.scope===o.scope)||e.push(o);if(n.length>0)for(let o=e.length-1;o>=0;o-=1)n.includes(e[o].path)&&e.splice(o,1);let r=It(e);return i?r:Ct(r)}async function Pi(e){let t=e.artifacts.map(n=>n.path);return{id:e.id,artifacts:e.artifacts,changed:e.changed,count:e.artifacts.length,migrations_applied:e.migrationsApplied&&e.migrationsApplied>0?e.migrationsApplied:void 0,validation:e.options.validatePaths?await gs(t,e.workspaceRoot):void 0}}async function Ue(e,t,n,i){let{metadataKey:r}=i,o=bn(),s=B(process.cwd(),n.path),a=ge(s),c=process.cwd();if(!await M(U(s)))throw new g(`Tracker is not initialized at ${s}. Run pm init first.`,_.NOT_FOUND);let l=await N(s),d=K(l,X()),u=await o.resolveList(t.add,"--add"),m=await o.resolveList(t.addGlob,"--add-glob"),f=await o.resolveList(t.remove,"--remove"),k=await o.resolveList(t.migrate,"--migrate"),p=ls(u,i.bareNoun).map(P=>({...P,path:Et(P.path,a,c)})),h=ds(m),y=await ps(h,a,c),v=hs([...p,...y],t.note,p.length>0||h.length>0),x=us(f).map(P=>Et(P,a,c)),S=ms(k);if(fs(v,x,S),!(v.length>0||x.length>0||S.length>0)){let P=await Ie(s,e,l.id_prefix,l.item_format,d.type_to_folder);if(!P)throw new g(`Item ${e} not found`,_.NOT_FOUND);let I=(await Te(P,{schema:l.schema})).document.metadata[r]??[];return Pi({id:P.id,artifacts:I,changed:!1,options:t,workspaceRoot:a})}let J=ue(t.author,l.author_default),H=await De({pmRoot:s,settings:l,id:e,op:i.op,author:J,message:t.message,force:t.force,skipNoop:!0,mutate(P){let b=P.metadata,I=b[r]??[],de=[...I],ae=ys(de,v,x,S),Je=ws(de,ae.adds,ae.removes,i.supportsAppendStable&&t.appendStable===!0);Je.length>0?b[r]=Je:delete b[r];let zt=!Zt(I,Je);return{changedFields:zt?[r]:[],warnings:zt&&ae.count>0?[`path_migrations_applied:${ae.count}`]:[]}}}),E=H.item[r]??[],F=H.warnings.find(P=>P.startsWith("path_migrations_applied:")),W=F?Number(F.slice(24)):0;return Pi({id:H.item.id,artifacts:E,changed:H.changedFields.includes(r),migrationsApplied:W,options:t,workspaceRoot:a})}function ze(e,t){let n={};for(let[i,r]of Object.entries(e))n[i==="artifacts"?t:i]=r;return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c4c82f8f-7890-5ed2-8f0f-a82ba42cf807")}catch{}})();async function Ni(e,t,n){let i=await Ue(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return ze(i,"docs")}import $i from"node:fs/promises";import G from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="515cd35c-8e0e-51d4-8ad9-1cea5be8a572")}catch{}})();var ks=32768;function Tt(e){return ne(G.normalize(e))}async function Ge(e){try{return await $i.realpath(e)}catch{return G.resolve(e)}}function _e(e,t){let n=G.isAbsolute(e.path)?G.resolve(e.path):G.resolve(t,e.path);return`${Tt(n)}::${e.scope}`}function qe(e,t,n){if(typeof e=="string"){let i=e.trim();i.length>0&&n.push({field:t,value:i});return}if(Array.isArray(e)){e.forEach((i,r)=>qe(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))qe(r,t?`${t}.${i}`:i,n)}function bs(e){let t=[];return qe(e.metadata,"metadata",t),qe(e.body,"body",t),t}function vs(e){let t=e.trim();return t=t.replace(/^[`"'<([{]+/u,""),t=t.replace(/[`"'>)\]},;!?]+$/u,""),t=t.replace(/[.]+$/u,""),t=t.replace(/:(?:\d+)(?::\d+)?$/u,""),t=t.replace(/[.]+$/u,""),t}function Rs(e){let t=[],n=/(?:[A-Za-z]:[\\/]|\/)[^\s"'`<>()[\]{},;]+/gu,i=/(?:\.{1,2}[\\/])?(?:(?:[A-Za-z0-9_.@-]+[\\/])+[A-Za-z0-9_.@-]+|[A-Za-z0-9_.@-]+\.[A-Za-z0-9][A-Za-z0-9._-]*)/gu;for(let r of e){let o=new Set,s=r.value.slice(0,ks);for(let[a,c]of[[n,r.value],[i,s]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=vs(l[0]);!d||o.has(d)||(o.add(d),t.push({field:r.field,value:d}))}}}return t}async function Ss(e,t,n=t){let i=G.isAbsolute(e)?G.resolve(e):G.resolve(n,e),r;try{r=await $i.stat(i)}catch{return}if(!r.isFile())return;let[o,s]=await Promise.all([Ge(t),Ge(i)]);if(Qe(o,s)){let a=G.relative(o,s);return!a||a.startsWith("..")||G.isAbsolute(a)?void 0:{path:Tt(a),scope:"project"}}return{path:Tt(i),scope:"global"}}async function xs(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>_e(c,t))),r=new Map,o=Rs(bs(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await Ss(c,t,n))}));let a=o.map(c=>({reference:c,resolved:s.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=_e(l,t),u=r.get(d)??{path:l.path,scope:l.scope,sourceFields:new Set,originalPaths:new Set,sourceCount:0};u.sourceFields.add(c.field),u.originalPaths.add(c.value),u.sourceCount+=1,r.set(d,u)}return[...r.entries()].map(([c,l])=>({path:l.path,scope:l.scope,status:i.has(c)?"already_linked":"addable",source_count:l.sourceCount,source_fields:[...l.sourceFields].sort((d,u)=>d.localeCompare(u)),original_paths:[...l.originalPaths].sort((d,u)=>d.localeCompare(u))})).sort((c,l)=>{let d=c.status.localeCompare(l.status);if(d!==0)return d;let u=c.path.localeCompare(l.path);return u!==0?u:c.scope.localeCompare(l.scope)})}async function ji(e,t,n){let i=await Ue(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return ze(i,"files")}async function As(e,t){let n=await Ge(t),i=await Promise.all(e.map(async o=>{let s=o.trim();if(!s)throw new g("Files lookup paths must not be empty.",_.USAGE);if(!G.isAbsolute(s))return ne(s);let a=await Ge(s);return Qe(n,a)?ne(G.relative(n,a)):ne(a)})),r=[...new Set(i)].sort((o,s)=>o.localeCompare(s));if(r.length===0)throw new g("Files lookup requires at least one path.",_.USAGE);return r}function Es(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new g(`Files lookup ${i} must be a non-negative integer.`,_.USAGE);let{offset:t=0,limit:n=50}=e;return{offset:Math.max(0,Math.floor(t)),limit:e.noTruncate?void 0:Math.max(0,Math.floor(n))}}function Bi(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Ui(e,t){let n=e.item.priority-t.item.priority;if(n!==0)return n;let i=t.item.updated_at.localeCompare(e.item.updated_at);return i===0?e.item.id.localeCompare(t.item.id):i}function Cs(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(ne(n.path))&&(e.scope===void 0||n.scope===e.scope)).sort((n,i)=>{let r=n.path.localeCompare(i.path);return r===0?n.scope.localeCompare(i.scope):r})})).filter(t=>t.files.length>0).sort(Ui)}async function Is(e){if(e.explain)return oi({workspaceRoot:e.workspaceRoot,paths:e.paths,candidates:e.matching,corpus:e.metadata,...e.lineRange?{lineRange:e.lineRange}:{},...e.decisionDepth===void 0?{}:{decisionDepth:e.decisionDepth}})}async function Ts(e){if([e.strictRead,e.noTruncate,e.explain,rn()].includes(!0))return null;let t=await yn(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?gn({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Os(e){let t=[],n=await Oe(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=Cs({metadata:n,paths:e.paths,scope:e.scope}),r=t.filter(c=>/^item_list_(?:item|directory)_read_failed:/u.test(c));if(e.strictRead&&r.length>0)throw new g(`Files lookup could not read every item: ${r.join("; ")}`,_.GENERIC_FAILURE);let o=await Is({explain:e.explain,workspaceRoot:e.workspaceRoot,paths:e.paths,matching:i,metadata:n,lineRange:e.lineRange,decisionDepth:e.decisionDepth}),a=(o?[...i].sort((c,l)=>{let d=o.explanations.get(l.item.id).score-o.explanations.get(c.item.id).score;return d!==0?d:Ui(c,l)}):i).slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:a.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+a.length<i.length,truncated:e.offset+a.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:a.map(c=>({item:Bi(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function Jd(e,t){let n=B(process.cwd(),t.path),i=ge(n);if(!await M(U(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let r=await As(e.paths,i);if(e.lineRange&&r.length!==1)throw new g("Files lookup line attribution requires exactly one source path.",_.USAGE);let o=await N(n),s=K(o,X()),{offset:a,limit:c}=Es(e),l=await Ts({pmRoot:n,typeToFolder:s.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!0,explain:e.explain===!0||e.lineRange!==void 0});return l?{paths:r,total:l.total,count:l.matches.length,offset:a,limit:c,has_more:a+l.matches.length<l.total,truncated:a+l.matches.length<l.total,completeness:{status:"unchecked",source:"index"},warnings:[],matches:l.matches.map(d=>({item:Bi(d.item),files:d.files}))}:Os({pmRoot:n,settings:o,typeToFolder:s.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,workspaceRoot:i,explain:e.explain===!0||e.lineRange!==void 0,lineRange:e.lineRange,decisionDepth:e.decisionDepth})}async function Xd(e,t,n){let i=B(process.cwd(),n.path),r=ge(i);if(!await M(U(i)))throw new g(`Tracker is not initialized at ${i}. Run pm init first.`,_.NOT_FOUND);let o=await N(i),s=K(o,X()),a=await Ie(i,e,o.id_prefix,o.item_format,s.type_to_folder);if(!a)throw new g(`Item ${e} not found`,_.NOT_FOUND);let c=await Te(a,{schema:o.schema}),l=await xs(c.document,r,process.cwd()),d=l.filter(E=>E.status==="addable"),u=l.filter(E=>E.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let E=c.document.metadata.files??[];return{id:a.id,files:E,changed:!1,apply:m,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let k=ue(t.author,o.author_default),p=d.map(E=>({path:E.path,scope:E.scope,note:f})),h=[],y=new Set,v=await De({pmRoot:i,settings:o,id:e,op:"files_discover",author:k,message:t.message??"Discover referenced file links",force:t.force,mutate(E){let F=[...E.metadata.files??[]],W=new Set(F.map(I=>_e(I,r)));h=[],y.clear();for(let[I,de]of p.entries()){let ae=_e(de,r);W.has(ae)||(F.push(de),W.add(ae),h.push(de),y.add(I))}let P=It(F),b=t.appendStable?P:Ct(P);return b.length>0?E.metadata.files=b:delete E.metadata.files,{changedFields:h.length>0?["files"]:[],warnings:h.length!==p.length?[`files_discover_skipped_existing:${p.length-h.length}`]:[]}}}),x=v.item.files??[],S=new Set(h.map(E=>_e(E,r))),A=x.filter(E=>S.has(_e(E,r))),J=d.filter((E,F)=>!y.has(F)),H=[...u,...J];return{id:v.item.id,files:x,changed:A.length>0,apply:!0,count:x.length,candidate_count:l.length,addable_count:d.length,added_count:A.length,skipped_existing_count:H.length,candidates:l,added:A,skipped_existing:H}}import{readFileSync as Ds}from"node:fs";import He from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="673a5a26-6214-58d6-af19-baee5a8359f0")}catch{}})();var Fs=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Ot=new Set(["--pm-path","--path","--author"]),Ps={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},Ms=new Set(["-p","--package"]),Ls=new Set(["-c","--call"]),Ns=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),$s=new Set(["-C","--prefix","--userconfig","--cache"]),tu=new Set(["--cwd"]),nu=new Set(["--cwd"]),js=new Set(["exec","x"]),iu=new Set(["run","run-script"]),ru=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function Bs(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Us(e,t=process.cwd()){let n=zs(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[i,...r]=n;if(zi(i)||Gi(i,t))return r;if(i==="node"&&r[0]&&Gi(r[0],t))return r.slice(1);let o=i==="npx"||i==="bunx"?Dt(r):i==="pnpm"?Hs(r):i==="npm"?Ws(r):null;return o&&(zi(o.command)||qs(o.command))?o.args:null}var qi=(e,t="pm")=>{let n=t.trim().toLowerCase(),i=n.length;for(;i>0&&n[i-1]==="-";)i-=1;let r=n.slice(0,i);if(r.length===0)return[];let o=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),s=new Set;for(let a of Bs(o)){let c=Us(a),l=c?Vs(c):null,d=l&&Fs.has(l.subcommand)?Ks(l.remaining,Ps[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&s.add(d)}return[...s].sort((a,c)=>a.localeCompare(c))};function zs(e){let t=0;for(e[t]==="env"&&(t+=1);t<e.length;){let n=e[t];if(/^(?:[a-z_][a-z0-9_]*|\$env:[a-z_][a-z0-9_]*)=.*/.test(n)){t+=1;continue}break}return e.slice(t)}function ou(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ot.has(n)){t+=2;continue}t+=1;continue}return n}}function zi(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Gs(e){let t=e.trim();if(!t.startsWith("@")){let r=t.indexOf("@");return r===-1?t:t.slice(0,r)}let n=t.indexOf("/");if(n===-1)return t;let i=t.indexOf("@",n+1);return i===-1?t:t.slice(0,i)}function qs(e){let t=Gs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Gi(e,t=process.cwd()){let n=e.replaceAll("\\","/");if(n!=="dist/cli.js"&&n!=="./dist/cli.js"&&!n.endsWith("/dist/cli.js"))return!1;let i=He.resolve(t,e);try{return JSON.parse(Ds(He.join(He.dirname(He.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Dt(e){let t=0;for(;t<e.length;){let i=e[t];if(i==="--"){t+=1;break}if(!i.startsWith("-"))break;let r=/^(?:-c|--call)=(.*)$/.exec(i);if(r){let o=r[1];return o?{command:o,args:e.slice(t+1)}:null}if(Ls.has(i)){t+=1;break}t+=Ms.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function Hi(e,t){let n=0;for(;n<e.length;){let i=e[n];if(i==="--"){n+=1;continue}if(i.startsWith("-")){if(i.includes("=")){n+=1;continue}if(t.has(i)){n+=2;continue}n+=1;continue}return{subcommand:i,args:e.slice(n+1)}}return null}function Hs(e){let t=Hi(e,Ns);return t?.subcommand!=="dlx"?null:Dt(t.args)}function Ws(e){let t=Hi(e,$s);return!t||!js.has(t.subcommand)?null:Dt(t.args)}function Vs(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Ot.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Ks(e,t=new Set){for(let n=0;n<e.length;n+=1){let i=e[n];if(i==="--")return e[n+1];if(!i.startsWith("-"))return i;!i.includes("=")&&(Ot.has(i)||t.has(i))&&(n+=1)}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="01f042d0-7f02-59f5-8894-cf48eb936d99")}catch{}})();async function Wi(e){return e.includeBody?wn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Oe(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7dd04a2f-1798-5c16-8740-5b7094f81cc0")}catch{}})();var Zs=["src","tests","docs"],Qs=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],ea=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),ta=["resolution","expected_result","actual_result"],na=["default","tracked-all","tracked-all-strict"],Vi=["core","strict","custom"],Ve=["off","warn","error"];var Pt=["author","acceptance_criteria","estimated_minutes","close_reason"],Zi=[...Pt,"reviewer","risk","confidence","sprint","release"],$t=Array.from(new Set(Zi)),ia={author:"author",acceptance_criteria:"acceptance_criteria","acceptance-criteria":"acceptance_criteria",estimated_minutes:"estimated_minutes","estimated-minutes":"estimated_minutes",estimate:"estimated_minutes",close_reason:"close_reason","close-reason":"close_reason",reviewer:"reviewer",risk:"risk",confidence:"confidence",sprint:"sprint",release:"release"},ra={author:"validate_metadata_missing_author",acceptance_criteria:"validate_metadata_missing_acceptance_criteria",estimated_minutes:"validate_metadata_missing_estimate",close_reason:"validate_metadata_missing_close_reason",reviewer:"validate_metadata_missing_reviewer",risk:"validate_metadata_missing_risk",confidence:"validate_metadata_missing_confidence",sprint:"validate_metadata_missing_sprint",release:"validate_metadata_missing_release"},oa={author:"missing_author",acceptance_criteria:"missing_acceptance_criteria",estimated_minutes:"missing_estimated_minutes",close_reason:"closed_missing_close_reason",reviewer:"missing_reviewer",risk:"missing_risk",confidence:"missing_confidence",sprint:"missing_sprint",release:"missing_release"},sa={author:"missing_author_item_ids",acceptance_criteria:"missing_acceptance_criteria_item_ids",estimated_minutes:"missing_estimated_minutes_item_ids",close_reason:"closed_missing_close_reason_item_ids",reviewer:"missing_reviewer_item_ids",risk:"missing_risk_item_ids",confidence:"missing_confidence_item_ids",sprint:"missing_sprint_item_ids",release:"missing_release_item_ids"},aa={author:"missing_author_truncated",acceptance_criteria:"missing_acceptance_criteria_truncated",estimated_minutes:"missing_estimated_minutes_truncated",close_reason:"closed_missing_close_reason_truncated",reviewer:"missing_reviewer_truncated",risk:"missing_risk_truncated",confidence:"missing_confidence_truncated",sprint:"missing_sprint_truncated",release:"missing_release_truncated"},ca=32*1024*1024,la=1e4,Qi=40,re=5,da=4096,ua=255,ma=Xs(Js);function er(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?er(i):i);return t}function fa(e){return{...e,checks:e.checks.map(t=>({...t,details:er(t.details)})),...e.fixes?{fixes:{mode:e.fixes.mode,auto_fix:e.fixes.auto_fix,prune_missing:e.fixes.prune_missing,planned_count:e.fixes.planned_count,applied_count:e.fixes.applied_count,gated_count:e.fixes.gated_count,failed_count:e.fixes.failed_count}}:{}}}function le(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Ki(e){return le(e).replace(/\/+$/,"")}function q(e){let t=L(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function Ye(e,t){return ln(e,t)??e}function Ae(e,t){return t.terminal_statuses.has(Ye(e,t))}function oe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function We(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function pa(e){let t=oe(qt),n={blocked_reason:oe(Ee.blocked_reason),resolution:oe(Ee.resolution),actual_result:oe(Ee.actual_result)},i=oe(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:oe(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:oe(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:oe(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:We(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:We(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:We(r.resolution,n.resolution)?"default":"settings",actual_result:We(r.actual_result,n.actual_result)?"default":"settings"}}}function tr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Vi.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${Vi.join(", ")}.`,_.USAGE)}function nr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ve.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Ve.join(", ")}.`,_.USAGE)}function ir(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Ve.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Ve.join(", ")}.`,_.USAGE)}function ha(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>ia[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function _a(e,t,n){let i=ha(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Pt],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Zi],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:i.length>0?{profile:e,profile_source:t,required_fields:i,configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:{profile:e,profile_source:t,required_fields:[...Pt],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var ga=new Set(["acceptance_criteria","estimated_minutes"]);function rr(e,t,n,i){return!i&&ga.has(t)&&Ae(e.status,n)?!1:t==="author"?!L(e.author):t==="acceptance_criteria"?!L(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?Ye(e.status,n)===n.close_status&&!L(e.close_reason):t==="reviewer"?!L(e.reviewer):t==="risk"?!L(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!L(e.confidence):t==="sprint"?!L(e.sprint):!L(e.release)}function or(e){if(e===void 0)return"default";let t=e.trim().toLowerCase();if(t.length===0||t==="default")return"default";if(t==="tracked-all"||t==="tracked_all")return"tracked-all";if(t==="tracked-all-strict"||t==="tracked_all_strict")return"tracked-all-strict";throw new g(`Unknown --scan-mode value "${e}". Supported values: ${na.join(", ")}.`,_.USAGE)}function sr(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return $.resolve(t);let n=$.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return $.dirname($.dirname(n));let r=$.resolve(process.cwd()),o=Yi(n),s=Yi(r),a=$.relative(o,s);return a.length===0||!a.startsWith("..")&&!$.isAbsolute(a)?n:r}function Yi(e){try{return Ys.native(e)}catch{return $.resolve(e)}}function ya(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function jt(e,t,n){let i=t.length>0?$.join(e,t):e,r;try{r=await Nt.readdir(i,{withFileTypes:!0})}catch(o){if(V(o))return;throw o}for(let o of r){if(o.name.startsWith("."))continue;let s=t.length>0?$.join(t,o.name):o.name;if(o.isDirectory()){if(ea.has(o.name))continue;await jt(e,s,n);continue}o.isFile()&&n.push(le(s))}}async function Mt(e){let t=[];for(let n of Zs)await jt(e,n,t);for(let n of Qs){let i=$.join(e,n);try{(await Nt.stat(i)).isFile()&&t.push(le(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function ar(e){try{let{stdout:t}=await ma("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:ca,windowsHide:!0,timeout:la}),n=t.split("\0").map(i=>le(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function wa(e,t){let n=new Set,i=Ki(Gt);i.length>0&&n.add(i);let r=Ki($.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((o,s)=>o.localeCompare(s))}function Ji(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function ka(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await ar(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await Mt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Mt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function D(e,t=re){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function se(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=D(e,Qi);return{values:n.values,truncated:n.truncated,total:e.length}}var ba={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},va={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function Ra(e){let t=e.missing_fields.map(n=>`${ba[n]} "${va[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function cr(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(s=>typeof s=="string"):si(t);if(r.length===0)return;let o=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...o?{fix_hints_truncated:!0}:{}}}function lr(e){let t=new Set;return e.checkMetadata&&t.add("metadata"),e.checkResolution&&t.add("resolution"),(e.checkLifecycle||e.checkStaleBlockers)&&t.add("lifecycle"),e.checkFiles&&t.add("files"),e.checkHistoryDrift&&t.add("history_drift"),e.checkCommandReferences&&t.add("command_references"),e.checkStorageIntegrity&&t.add("storage_integrity"),t.size===0?(e.autoFix&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle")),e.pruneMissing&&t.add("files"),t.size===0&&(t.add("metadata"),t.add("resolution"),t.add("lifecycle"),t.add("files"),t.add("command_references"),t.add("history_drift"),t.add("format_version"),t.add("storage_integrity")),t):(e.pruneMissing&&t.add("files"),t)}var Sa="validate_metadata_duplicate_issue_codes";function dr(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:re,i=e.slice(0,n);return{rows:i.map(o=>({code:o.code,count:o.count,ids:o.ids,titles:o.titles,remediation_hint:`Items ${o.ids.join(", ")} share issue code "${o.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${Sa}:${e.length}`]}}function xa(){return Object.fromEntries($t.map(e=>[e,[]]))}function Aa(e,t,n){let i=xa();for(let r of e)for(let o of $t)rr(r,o,t,n)&&i[o].push(r.id);return i}function Ea(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let o=t[r];o.length>0&&i.push(`${ra[r]}:${o.length}`)}return i.push(...n),i}function ur(e,t){let n={};for(let i of e.required_fields){let r=t[i],o=r?r.length:0,s=oa[i];o>0&&s&&(n[s]=o)}return n}function mr(e,t,n){let i=[];for(let r of e.required_fields){let o=t[r];if(o)for(let s of o){let a=n.get(s)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function Ca(e,t,n,i){for(let r of t.required_fields){let o=n[r];if(!o||o.length===0)continue;let s=sa[r],a=aa[r];if(!s||!a)continue;let c=D(o,i?o.length:re);e[s]=c.values,e[a]=c.truncated}}function fr(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:L(n.get(r)?.resolution)})):[]}function pr(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:L(n.get(r)?.type)})):[]}function Ia(e,t,n,i){let r=new Map(e.map(h=>[h.id,h])),o=t.profile==="strict",s=Aa(e,n,o),a=Ri(e),c=dr(a,i),l=Ea(t,s,c.warnings),d=ur(t,s),u=mr(t,s,r),m=Si(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[...$t],counts:d,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),Ca(f,t,s,i);let k=fr(t,s,r),p=pr(t,s,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",ok:l.length===0,details:f},warnings:l,closeReasonBackfillRows:k,estimateBackfillRows:p}}function Ta(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(Ye(m.status,t))),o=[],s=[];for(let m of r){let f=ta.filter(k=>!L(m[k]));f.length!==0&&(o.push({id:m.id,missing_fields:f}),s.push({id:m.id,missing_fields:f,close_reason:L(m.close_reason)}))}let a=o.length>0?[`validate_resolution_missing_fields:${o.length}`]:[],c=n?Number.POSITIVE_INFINITY:re,l=D(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=o.map(m=>Ra(m)),u=D(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",ok:a.length===0,details:{checked_closed_items:r.length,missing_resolution_items:o.length,missing_resolution_rows:l.values,missing_resolution_rows_truncated:l.truncated,missing_resolution_remediation_hints:u.values,missing_resolution_remediation_hints_truncated:u.truncated}},warnings:a,resolutionBackfillRows:s}}function hr(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function _r(e,t="pm",n=et()){let i=new Set(e.map(o=>o.id)),r=[...e].sort((o,s)=>o.id.localeCompare(s.id));return new Map(r.map(o=>{let s=new Set,a=q(o.blocked_by);a&&i.has(a)&&s.add(a),(o.dependencies??[]).filter(l=>{let d=q(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>q(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>s.add(l));let c=q(o.definition_of_ready);return yr(c??"",t).filter(l=>i.has(l)).forEach(l=>s.add(l)),[o.id,[...s].sort((l,d)=>l.localeCompare(d))]}))}function gr(e,t,n){let i=Rn(e,n?d=>Ae(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),o=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),s=t?Number.POSITIVE_INFINITY:re,a=D(r,s),c=D(o,s),l=D(i.active.map(d=>d.source==="parent"?`pm update ${d.holder_id} --unset parent`:d.source==="blocked_by"?`pm update ${d.holder_id} --unset blocked_by`:`pm update ${d.holder_id} --replace-deps '<correct dependency edges>'`),s);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",ok:r.length===0,details:{checked_items:e.length,dangling_reference_count:r.length+o.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:o.length,legacy_closed_dangling_reference_count:i.legacy_terminal.filter(d=>d.holder_status==="closed").length,legacy_terminal_dangling_reference_rows:c.values,legacy_terminal_dangling_reference_rows_truncated:c.truncated,no_active_blocker_sentinel_count:i.no_active_blocker_sentinels.length,remediation_hints:l.values,remediation_hints_truncated:l.truncated}},warnings:r.length>0?[`validate_dangling_dependency_references:${r.length}`]:[]}}function yr(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${hr(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,o)=>r.localeCompare(o))}function Bt(e){let t=0,n=new Map,i=new Map,r=[],o=new Set,s=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),o.add(d);for(let m of e.get(d)??[])n.has(m)?o.has(m)&&i.set(d,Math.min(i.get(d),n.get(m))):(a(m),i.set(d,Math.min(i.get(d),i.get(m))));if(i.get(d)!==n.get(d))return;let u=[];for(;r.length>0;){let m=r.pop();if(o.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),s.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return s.filter(d=>{if(d.length>1)return!0;let u=d[0];return(e.get(u)??[]).includes(u)}).sort((d,u)=>d[0].localeCompare(u[0])||d.length-u.length||d.join(",").localeCompare(u.join(",")))}function Ut(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],o=new Set([n]),s=a=>{let c=(t.get(a)??[]).filter(l=>i.has(l));for(let l of c){if(l===n&&r.length>1)return r.push(n),!0;if(!o.has(l)){if(o.add(l),r.push(l),s(l))return!0;r.pop(),o.delete(l)}}return!1};return s(n)?[...r]:[...e,n]}function wr(e,t="pm"){let n=_r(e,t),i=Bt(n),r=[...new Set(i.flat())].sort((s,a)=>s.localeCompare(a)),o=i.map(s=>Ut(s,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:o}}function kr(e,t=et()){let n=new Map(e.map(o=>[o.id.toLowerCase(),o.id])),i=new Map(e.map(o=>[o.id,[]]));return[...e].sort((o,s)=>o.id.localeCompare(s.id)).forEach(o=>{let s=i.get(o.id),a=q(o.parent),c=a?n.get(a.toLowerCase()):void 0;c&&s.push(c),(o.dependencies??[]).forEach(l=>{let d=t.resolve(l.kind);if(!d?.hierarchy)return;let u=n.get(l.id.toLowerCase());u&&(d.hierarchyDirection==="source_parent"?i.get(u).push(o.id):s.push(u))})}),i.forEach((o,s)=>{i.set(s,[...new Set(o)].sort((a,c)=>a.localeCompare(c)))}),i}function br(e){let t=kr(e),n=Bt(t),i=[...new Set(n.flat())].sort((o,s)=>o.localeCompare(s)),r=n.map(o=>Ut(o,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function vr(e){return e.startsWith("docs/")?"docs_unowned":e.startsWith("tests/")?"tests_unowned":e.startsWith("src/")?"source_unowned":e.endsWith(".md")?"docs_unowned":"unlinked_existing"}function Ke(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Rr(e,t){let n=Ke(e).split("/").filter(Boolean),i=Ke(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function Oa(e,t){let n=Ke(t),i=Ke(e),r=t.endsWith("/")?t:`${t}/`,o=e.startsWith(r),s=n.length>0&&n===i,a=Rr(e,t);return!o&&!s&&a===0?null:o?{score:t.length+1e3,confidence:"path_prefix"}:s?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function Da(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function Fa(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(o=>(i==="docs"?o.docs??[]:o.files??[]).map(s=>({item:o,link:s}))).forEach(({item:o,link:s})=>{if(s.scope!=="project")return;let a=le(s.path);if(a.length===0||a===e)return;let c=Oa(e,a);c!==null&&Da(r,o,c.score)&&(r={item:o,score:c.score,confidence:c.confidence})}),r?{id:r.item.id,type:r.item.type,title:r.item.title,status:r.item.status,confidence:r.confidence}:null}function Sr(e,t){return e.map(n=>{let i=vr(n),r=i==="docs_unowned"?"docs":"files",o=Fa(n,i,t),s=o?.id??"<id>";return{path:n,classification:i,owner_candidate:o,remediation_hint:`pm ${r} ${s} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function xr(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function Pa(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=q(e[n]);return r?i.some(o=>r.toLowerCase().includes(o)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function Ma(e,t,n,i,r){let o=q(t.parent),s=o?n.get(i.get(o.toLowerCase())??o):void 0;return{id:e.id,parent_id:t.id,grandparent_id:s?.id,grandparent_active:s!==void 0&&!Ae(s.status,r)}}function La(e,t,n,i){let r=q(e.blocked_by),o=q(e.blocked_reason),s=o?.toLowerCase(),a=Ye(e.status,n),c=[];return t.has(a)?(!r&&!o&&c.push("blocked_status_missing_blocker_context"),s?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),s&&i.stale_blocker_reason_patterns.some(l=>s.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),o&&c.push("non_blocked_status_has_blocked_reason"),c)}function Na(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),o=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),s=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!Ae(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=Pa(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=q(c.parent),u=d?r.get(o.get(d.toLowerCase())??d):void 0;if(u&&Ae(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(Ma(c,u,r,o,n))),t){let m=La(c,s,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,k)=>f.localeCompare(k))})}}return a}function $a(e){e.closureLikeRows.sort((t,n)=>t.id.localeCompare(n.id)),e.terminalParentRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.terminalParentFixRows.sort((t,n)=>t.id.localeCompare(n.id)||t.parent_id.localeCompare(n.parent_id)),e.staleBlockerRows.sort((t,n)=>t.id.localeCompare(n.id))}function Xi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function ja(e,t,n,i,r,o){let s=[];e.closureLikeRows.length>0&&s.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&s.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&s.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=Xi("validate_lifecycle_dependency_cycles",n,r),c=Xi("validate_hierarchy_parent_cycle",i,o);return[...s,...a?[a]:[],...c?[c]:[]]}function Ar(e){let t=le(e);return t.length>da||t.split(/[\\/]/).some(n=>n.length>ua)}async function Ba(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(Ar(n))return!1;try{let i=await Nt.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return ya(i,["ENOENT","ENOTDIR"])}}async function Ua(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(o=>({item:r,artifact:o,link_kind:"files"})),...(r.docs??[]).map(o=>({item:r,artifact:o,link_kind:"docs"}))]);for(let{item:r,artifact:o,link_kind:s}of i){if(o.scope!=="project")continue;if(Se(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=le(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await Ba(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:s})))}return n}function za(e,t,n,i,r,o){let s=i==="tracked-all-strict",a=s&&!r,c=r||s,l=c?[]:wa(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Ji(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Ji(f,l)),m={};if(d.length>0){let f=se(d,o);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:s,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Er(e,t,n,i,r,o,s,a="pm"){let c=Na(e,t,r,o);$a(c);let l=wr(c.activeItems,a),d=br(e),u=ja(c,t,n,i,l.cycle_count,d.cycle_count),m=s?Number.POSITIVE_INFINITY:re,f=D(c.closureLikeRows.map(A=>`${A.id}:${A.fields.join(",")}`),m),k=D(c.terminalParentRows.map(A=>`${A.id}:${A.parent_id}:${A.parent_status}`),m),p=D(c.staleBlockerRows.map(A=>`${A.id}:${A.status}:${A.reasons.join(",")}`),m),h=D(l.cycle_item_ids,m),y=D(l.cycle_sample_paths,m),v=D(d.cycle_item_ids,m),x=D(d.cycle_sample_paths,m),S=l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error";return{check:{name:"lifecycle",status:S?"error":u.length===0?"ok":"warn",ok:!S&&u.length===0,details:{checked_active_items:c.activeItems.length,active_closure_like_metadata_items:c.closureLikeRows.length,active_closure_like_metadata_rows:f.values,active_closure_like_metadata_rows_truncated:f.truncated,active_terminal_parent_items:c.terminalParentRows.length,active_terminal_parent_rows:k.values,active_terminal_parent_rows_truncated:k.truncated,stale_blocker_checks_enabled:t,stale_blocker_items:c.staleBlockerRows.length,stale_blocker_rows:p.values,stale_blocker_rows_truncated:p.truncated,dependency_cycle_severity_policy:n,dependency_cycle_count:l.cycle_count,dependency_cycle_item_count:l.cycle_item_ids.length,dependency_cycle_item_ids:h.values,dependency_cycle_item_ids_truncated:h.truncated,dependency_cycle_sample_paths:y.values,dependency_cycle_sample_paths_truncated:y.truncated,parent_cycle_severity_policy:i,parent_cycle_count:d.cycle_count,parent_cycle_item_count:d.cycle_item_ids.length,parent_cycle_item_ids:v.values,parent_cycle_item_ids_truncated:v.truncated,parent_cycle_sample_paths:x.values,parent_cycle_sample_paths_truncated:x.truncated,stale_blocker_reason_patterns:[...o.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:o.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...o.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:o.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...o.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:o.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...o.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:o.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Cr(e,t,n,i,r,o){let s=await Ua(e,t),a=new Map(e.map(b=>[b.id,b])),c=[...new Set(s.missingLinkedPaths)].sort((b,I)=>b.localeCompare(I)),l=await ka(t,i),d=za(l,n,t,i,r,o),u=d.candidateFiles.filter(b=>!s.linkedProjectPaths.has(b)),m=Sr(u,e),f=Ei(c,d.candidateFiles),k=new Map(f.map(b=>[b.path,b.classification])),p=f.filter(b=>b.classification==="moved").length,h=s.staleLinkRows.map(b=>({...b,classification:k.get(b.path)??"deleted"})).sort((b,I)=>b.item_id.localeCompare(I.item_id)||b.path.localeCompare(I.path)||b.link_kind.localeCompare(I.link_kind)),y=[];d.strictModeForcesPmInternals&&y.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&y.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&y.push(`validate_files_orphaned_paths:${u.length}`);let v=[...s.remoteLinkedPaths].sort((b,I)=>b.localeCompare(I)),x=se(v,o),S=se(c,o),A=se(u,o),J=se(m.map(b=>`${b.path}:${b.classification}:owner_candidate=${b.owner_candidate?.id??"unowned"}`),o),H=o?m:se(xr(m),!1).values,E=se(Ci(f),o),F=h.map(b=>({item_id:b.item_id,path:b.path,link_kind:b.link_kind,classification:b.classification})),W=Ti(F,b=>{let I=a.get(b);return I?{type:I.type,title:I.title,status:I.status}:void 0}),P=o?W:se(Oi(W),!1).values;return{check:{name:"files",status:y.length===0?"ok":"warn",ok:y.length===0,details:{workspace_root:t,scan_mode_requested:l.requestedMode,scan_mode_applied:l.appliedMode,strict_tracked_all_mode:d.strictTrackedAllMode,strict_mode_forces_pm_internals:d.strictModeForcesPmInternals,strict_mode_forces_pm_internals_notice:d.strictModeForcesPmInternals?"tracked-all-strict force-enables PM internals; pass --include-pm-internals to make inclusion explicit.":null,file_list_detail_mode:o?"full":"summary",file_list_summary_limit:Qi,candidate_scan_source:l.source,include_pm_internals:d.includePmInternalsEffective,include_pm_internals_requested:r,pm_internal_candidate_prefixes:d.pmInternalCandidatePrefixes,pm_internal_excluded_count:d.excludedPmInternalPaths.length,excluded_total:d.excludedPmInternalPaths.length,excluded_by_reason:d.excludedByReason,linked_project_paths:s.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:x.total,remote_linked_paths:x.values,remote_linked_paths_truncated:x.truncated,candidate_total_raw:l.candidateTotal,candidate_scanned_raw:l.candidateScanned,candidate_total:d.candidateFiles.length,candidate_scanned:d.candidateFiles.length,scanned_candidate_files:d.candidateFiles.length,missing_linked_paths_count:c.length,missing_linked_paths_total:S.total,missing_linked_paths:S.values,missing_linked_paths_truncated:S.truncated,missing_linked_paths_moved_count:p,missing_linked_paths_deleted_count:c.length-p,missing_linked_path_classifications:E.values,missing_linked_path_classifications_truncated:E.truncated,missing_linked_path_rows_count:W.length,missing_linked_path_rows:P,orphaned_paths_count:u.length,orphaned_paths_total:A.total,orphaned_paths:A.values,orphaned_paths_truncated:A.truncated,orphaned_path_classifications:J.values,orphaned_path_classifications_truncated:J.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:H}},warnings:y,staleLinkPruneRows:h}}async function Ga(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:o,chainMismatches:s,driftedItems:a}=await fi(e,t),c=[];i.length>0&&c.push(`validate_history_drift_missing_streams:${i.length}`),r.length>0&&c.push(`validate_history_drift_unreadable_streams:${r.length}`),o.length>0&&c.push(`validate_history_drift_hash_mismatches:${o.length}`),s.length>0&&c.push(`validate_history_drift_chain_mismatches:${s.length}`);let l=n?Number.POSITIVE_INFINITY:re,d=D(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",ok:c.length===0,details:{checked_items:t.length,drifted_items_count:a.length,drifted_items:d.values,drifted_items_truncated:d.truncated,counts:{missing_streams:i.length,unreadable_streams:r.length,hash_mismatches:o.length,chain_mismatches:s.length}}},warnings:c}}function qa(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function Ir(e,t,n){let i=new Set(e.map(h=>h.id.toLowerCase())),r=0,o=0,s=new Set,a=[],c=e.flatMap(h=>(h.tests??[]).map(y=>({item:h,linkedTest:y})));for(let{item:h,linkedTest:y}of c){if(typeof y.command!="string"||y.command.trim().length===0)continue;r+=1;let v=qi(y.command,t);if(v.length!==0){o+=v.length;for(let x of v)s.add(x),i.has(x.toLowerCase())||a.push(qa(h.id,x,y.command))}}let l=[...new Set(a)].sort((h,y)=>h.localeCompare(y)),d=[...new Set(l.map(h=>h.split(":")[1]??""))].filter(h=>h.length>0).sort((h,y)=>h.localeCompare(y)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:re,f=D(l,m),k=D(d,m),p=D([...s].sort((h,y)=>h.localeCompare(y)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",ok:u.length===0,details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:o,unique_referenced_pm_ids_count:s.size,unique_referenced_pm_ids:p.values,unique_referenced_pm_ids_truncated:p.truncated,stale_pm_id_references_count:l.length,stale_pm_ids_count:d.length,stale_pm_ids:k.values,stale_pm_ids_truncated:k.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function Ha(e,t){let n=cn(e.map(c=>({ref:c.id,version:an(c)}))),i=[];n.outdated.length>0&&i.push(`validate_format_version_outdated_items:${n.outdated.length}`),n.ahead.length>0&&i.push(`validate_format_version_ahead_items:${n.ahead.length}`);let r=t?Number.POSITIVE_INFINITY:re,o=D(n.outdated,r),s=D(n.ahead,r),a=n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok";return{check:{name:"format_version",status:a,ok:a==="ok",details:{checked_items:e.length,current_format_version:sn,outdated_items_count:n.outdated.length,outdated_items:o.values,outdated_items_truncated:o.truncated,ahead_items_count:n.ahead.length,ahead_items:s.values,ahead_items_truncated:s.truncated}},warnings:i}}var Lt="pm validate auto-fix";async function Tr(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:Lt};if(e.kind==="set_resolution"?i.resolution=e.value:e.kind==="set_close_reason"?i.closeReason=e.value:e.kind==="set_estimate"?i.estimatedMinutes=e.value:e.kind==="reparent"?i.parent=e.parent_id:i.unset=["parent"],!n.runUpdate)throw new g("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",_.USAGE);await n.runUpdate(e.item_id,i,t);return}case"prune_file_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`);case"prune_doc_link":throw new Error(`Unsupported non-batched fix kind: ${e.kind}`)}}function Ft(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function Or(e,t,n){let i=[],r=[],o=new Map;for(let s of e.filter(a=>Ft(a)===null))try{await Tr(s,t,n),i.push(s)}catch(a){r.push({fix:s,error:a})}for(let s of e.filter(a=>Ft(a)!==null)){let a=Ft(s),c=o.get(a);c?c.push(s):o.set(a,[s])}for(let s of o.values()){let a=s[0];if(!a)continue;let c=s.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await ji(a.item_id,{remove:c,message:Lt},t):await Ni(a.item_id,{remove:c,message:Lt},t),i.push(...s)}catch(l){r.push(...s.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Vu={applyValidateFix:Tr,applyValidateFixes:Or,attachValidateFixHints:cr,buildCommandReferencesCheck:Ir,buildDependencyReferencesCheck:gr,buildCloseReasonBackfillRows:fr,buildFilesCheck:Cr,buildLifecycleCheck:Er,buildLifecycleDependencyGraph:_r,buildLifecycleParentGraph:kr,buildEstimateBackfillRows:pr,buildMetadataCounts:ur,buildMissingFieldOccurrences:mr,buildOrphanedPathRows:Sr,classifyOrphanedPath:vr,collectDefaultProjectFileCandidates:Mt,collectTrackedGitFileCandidates:ar,detectLifecycleDependencyCycles:wr,detectLifecycleParentCycles:br,escapeRegExp:hr,extractItemIds:yr,findLifecycleDependencyCycleComponents:Bt,isMetadataFieldMissing:rr,linkedArtifactPathExceedsFilesystemLimits:Ar,listFilesRecursive:jt,resolveDependencyCycleSeverity:nr,resolveParentCycleSeverity:ir,resolveFileScanMode:or,resolveLifecycleDependencyCycleSamplePath:Ut,resolveRequestedChecks:lr,resolveValidateMetadataProfile:tr,resolveWorkspaceRoot:sr,sharedDirectoryPrefixLength:Rr,summarizeOrphanedPathRows:xr,summarizeDuplicateIssueCodes:dr,toMeaningfulString:q};async function Wa(e,t,n,i){let r=await ti(e,new Set(t.map(p=>p.id)),n,{schema:i.schema,extensionFieldNames:Ht(X())}),o=[];r.unreadable_item_files.length>0&&o.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&o.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&o.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&o.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&o.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&o.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let s=o.length,a=await Fi(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Vn(e,je(i));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await ve(e),d=l===null?null:await Kn(l);d!==null&&d.status!=="ok"&&o.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await vt(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:f}=Qn(u);m.length>0&&o.push(`validate_merge_decisions_unreviewed:${m.length}`);let k=s>0?"error":o.length>0?"warn":"ok";return{check:{name:"storage_integrity",status:k,ok:k==="ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:m.length,pending_merge_decision_items:[...new Set(m.map(p=>p.item_id))].sort((p,h)=>p.localeCompare(h)),lossless_merge_receipt_count:f.length,lossless_merge_receipt_items:[...new Set(f.map(p=>p.item_id))].sort((p,h)=>p.localeCompare(h)),tracked_runtime_cache:{tracker_relative_root:a.tracker_relative_root,tracked_paths:a.tracked_paths,tracked_path_count:a.tracked_path_count,remediation_command:a.remediation_command}}},warnings:o}}function ie(e,t,n){n&&cr(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Va(e){let t={checks:[],warnings:[...e.initialWarnings],closeReasonBackfillRows:[],estimateBackfillRows:[],resolutionBackfillRows:[],terminalParentFixRows:[],staleLinkPruneRows:[]},n=e.options.fixHints===!0,i=e.options.verboseDiagnostics===!0||e.options.allAffectedIds===!0||e.global.json===!0;if(e.requestedChecks.has("metadata")){let r=Ia(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,ie(t,r,n)}if(e.requestedChecks.has("resolution")){let r=Ta(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,ie(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Er(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,ie(t,r,n),ie(t,gr(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Cr(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,ie(t,r,n)}return e.requestedChecks.has("command_references")&&ie(t,Ir(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&ie(t,await Ga(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&ie(t,Ha(e.items,i),n),e.requestedChecks.has("storage_integrity")&&ie(t,await Wa(e.pmRoot,e.items,K(e.settings,X()).type_to_folder,e.settings),n),t}function Ka(e,t,n){let i=[];return e.autoFix===!0&&(i.push(..._i(t.closeReasonBackfillRows)),i.push(...hi(t.resolutionBackfillRows)),i.push(...gi(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...yi(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...wi(t.staleLinkPruneRows)),i}async function Ya(e,t,n,i,r,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=Ka(e,t,n),{applicable:a,gated:c}=bi(s,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Or(a,r,o);d.push(...m.applied.map(Re)),u.push(...m.failed.map(({fix:f,error:k})=>({...Re(f),error:k instanceof Error?k.message:String(k)})))}return{mode:l?"dry_run":"apply",auto_fix:e.autoFix===!0,prune_missing:e.pruneMissing===!0,granted_fix_scopes:[...i].sort((m,f)=>m.localeCompare(f)),planned_count:s.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:s.map(Re),applied_fixes:d,gated_fixes:c.map(m=>({...Re(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Ku(e,t,n={}){nn(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new g("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",_.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new g("--fix-scope requires --auto-fix.",_.USAGE);let r=ki(e.fixScope),o=B(process.cwd(),t.path);if(!await M(U(o)))throw new g(`Tracker is not initialized at ${o}. Run pm init first.`,_.NOT_FOUND);let s=await N(o),a=tn(s.schema),c=K(s,X()),l=lr(e),d=[],u=await Wi({includeBody:l.has("history_drift"),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let F=await ut(o);F.actionable_unknown_event_count>0&&d.push(`validate_history_unknown_author_events:${F.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=tr(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),k=_a(f,m,s.validation.metadata_required_fields),p=pa(s),h=nr(e.dependencyCycleSeverity),y=ir(e.parentCycleSeverity),v=or(e.scanMode),x=sr(o),S=await Va({requestedChecks:l,options:e,global:t,pmRoot:o,workspaceRoot:x,settings:s,items:u,statusRegistry:a,metadataPolicy:k,lifecyclePatternPolicy:p,dependencyCycleSeverity:h,parentCycleSeverity:y,fileScanMode:v,initialWarnings:[...new Set(d)]}),A=i?await Ya(e,S,s,r,t,n):void 0,J=[...new Set(S.warnings)].sort((F,W)=>F.localeCompare(W)),E={ok:!S.checks.some(F=>F.status==="error"),has_warnings:J.length>0,checks:S.checks,warnings:J,...A!==void 0?{fixes:A}:{},generated_at:Z(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...fa(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Yc as a,fi as b,Oo as c,R as d,T as e,Pr as f,kc as g,bc as h,vc as i,In as j,Rc as k,Sc as l,xc as m,Ac as n,Ec as o,dt as p,Cc as q,Ic as r,lt as s,Tc as t,Oc as u,Tn as v,Dc as w,zr as x,Dn as y,Uc as z,ut as A,Wr as B,Vr as C,zc as D,Kr as E,Qr as F,eo as G,Ne as H,zn as I,me as J,_t as K,oo as L,ve as M,wt as N,je as O,Vn as P,Kn as Q,hl as R,_l as S,ao as T,Fi as U,po as V,Al as W,vt as X,Qn as Y,El as Z,Cl as _,ti as $,Ni as aa,Bl as ba,oi as ca,ji as da,Jd as ea,Xd as fa,Ns as ga,$s as ha,tu as ia,nu as ja,iu as ka,ru as la,Bs as ma,Us as na,zs as oa,ou as pa,zi as qa,qs as ra,Gi as sa,Dt as ta,Hi as ua,Hs as va,Ws as wa,Vs as xa,fa as ya,Vu as za,Ku as Aa};
17
- //# sourceMappingURL=chunk-OGC4XSBC.js.map
@@ -1,2 +0,0 @@
1
- import{Ba as K,Da as _,Fa as d,Ga as L,Ka as Q,Ma as Z,Oa as tt,U as V,V as S,Wa as et,Ya as rt,Z as W,bb as nt,cb as ot,jb as it,l as z,lb as st,nb as P,o as C,oa as Y,ob as D,pa as X,qa as J,wa as p}from"./chunk-6XYLENDV.js";import{F as M,L as G,O as B,P as q,R as j,p as k,s as H,t as m}from"./chunk-2RI2FESN.js";import{Y as c,Z as l}from"./chunk-CP4K4WFS.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]="47c087c2-124a-58b7-a5c9-09403235f4a2")}catch{}})();function yt(t,e){let n=-1;return t.forEach((r,o)=>{let i=Date.parse(r.ts);if(!Number.isFinite(i))throw new l(`History for this item contains invalid timestamp at entry ${o+1}.`,c.GENERIC_FAILURE);i<=e&&(n=o)}),n}function wt(t){let e=t[0]?.ts??null,n=t.at(-1)?.ts??null,r={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:e,last_timestamp:n}};return n!==null&&(r.examples=["1",String(t.length),n],r.valid_range.first_version=1,r.valid_range.last_version=t.length),{guidance:r,lastTimestamp:n}}function pt(t,e){let n={};if(e instanceof Error&&e.message.trim().length>0&&(n.reason=e.message.trim()),typeof e!="object"||e===null)return n;let r=e;if(typeof r.index=="number"&&Number.isInteger(r.index)&&r.index>=0&&(n.patchIndex=r.index),typeof r.operation=="object"&&r.operation!==null){let o=r.operation;Object.assign(n,Object.fromEntries(["op","path","from"].flatMap(i=>{let s=o[i];return typeof s=="string"?[[i,s]]:[]})))}if(n.patchIndex!==void 0){let o=t[n.patchIndex];o&&(n.op??=o.op,n.path??=o.path,n.from??=o.from)}return n}function Mt(t,e,n={}){let r=t.trim(),o=n.errorSubject??"history",i=o==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=wt(e);if(!r)throw new l(`Missing ${o} target. Use a timestamp or version number.`,c.USAGE,s);if(/^\d+$/.test(r)){let u=Number(r);if(!Number.isSafeInteger(u)||u<1||u>e.length)throw new l(`${i} version must be between 1 and ${e.length} for this item.`,c.USAGE,s);return{kind:"version",raw:r,historyIndex:u-1}}let h=Date.parse(r);if(!Number.isFinite(h))throw new l(`Invalid ${o} target "${t}". Use a positive version number or ISO timestamp.`,c.USAGE,s);let f=yt(e,h);if(f<0||n.allowFutureTimestamp!==!0&&h>Date.parse(a))throw new l(o==="restore"?`No history entries exist at or before timestamp ${r}.`:`No history entry exists at timestamp ${r}.`,c.USAGE,s);return{kind:"timestamp",raw:r,historyIndex:f}}function A(t,e,n,r){let o=Q(t,e);if(o.ok)return o.document;let i=pt(e,o.error),s=[`history_op=${r}`,i.patchIndex===void 0?null:`patch_index=${i.patchIndex}`,i.op?`op=${i.op}`:null,i.path?`path=${i.path}`:null,i.from?`from=${i.from}`:null].filter(a=>a!==null);throw new l(`Failed to apply history patch at entry ${n} (${s.join(", ")}). ${i.reason??String(o.error)}`,c.GENERIC_FAILURE)}function Gt(t,e){let n=structuredClone(_);for(let r=0;r<=e;r+=1){let o=t[r];if(!o)throw new l(`History target entry ${r+1} does not exist.`,c.USAGE);if(d(n)!==o.before_hash)throw new l(`History hash mismatch before replay at entry ${r+1}.`,c.GENERIC_FAILURE);if(n=A(n,o.patch,r+1,o.op),d(n)!==o.after_hash)throw new l(`History hash mismatch after replay at entry ${r+1}.`,c.GENERIC_FAILURE)}return n}function Bt(t,e){if(Object.keys(t.metadata).length>0)return t;throw new l(`History target ${e.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,c.USAGE)}import U from"node:fs/promises";import gt from"node:fs/promises";(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]="a2ec9f1a-aae2-59d5-8c9a-7acd8bf5a7a2")}catch{}})();function It(t){if(!t.itemDocument)return[];let e=t.itemDocument.metadata?.assignee?.trim();if(!e||e===t.author||t.force)return[];let n=et(t.settings);if(n.ownership_enforcement==="strict")throw new l(`Item ${t.subjectId} is assigned to ${e}. Use --force to override.`,c.CONFLICT);return n.ownership_enforcement==="warn"?[`ownership_warning:assignee_conflict:${t.subjectId}:${e}`]:[]}async function _t(t){let e=await H(t.subject.historyPath);if(e!==t.historyRawBeforeLock)throw new l(`History for ${t.subject.id} changed while waiting for lock; retry ${t.operation}.`,c.CONFLICT);let n=await P(t.pmRoot,t.subject.id,t.settings.id_prefix,t.settings.item_format,t.typeRegistry.type_to_folder),r=n?await D(n,{schema:t.settings.schema}):null;if((r?.raw??null)!==(t.currentItemRawBeforeLock??null))throw new l(`Item ${t.subject.id} changed while waiting for lock; retry ${t.operation}.`,c.CONFLICT);return{historyRawUnderLock:e,locatedUnderLock:n,loadedItemUnderLock:r}}async function Zt(t){let e=t.writeHistoryRaw??m;try{await e(t.historyPath,t.nextHistoryRaw),await p(t.historyPath)}catch(n){try{t.historyRawUnderLock===null?await gt.rm(t.historyPath,{force:!0}):await e(t.historyPath,t.historyRawUnderLock),await p(t.historyPath)}catch(r){throw new AggregateError([n,r],`History rewrite failed and rollback also failed: ${String(n)}`)}throw n}}async function at(t){let e=[...It({itemDocument:t.itemDocument,subjectId:t.subject.id,author:t.author,force:t.force,settings:t.settings})],n=await W(t.pmRoot,t.subject.id,t.settings.locks.ttl_seconds,t.author,!!t.force,t.settings.governance.force_required_for_stale_lock,t.settings.locks.wait_ms);try{let r=await _t({pmRoot:t.pmRoot,subject:t.subject,settings:t.settings,typeRegistry:t.typeRegistry,historyRawBeforeLock:t.historyRawBeforeLock,currentItemRawBeforeLock:t.currentItemRawBeforeLock,operation:t.operation});return await t.applyRewrite(r),t.applyPostRewrite&&e.push(...await t.applyPostRewrite(r)),e}finally{await n()}}(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]="cd2a27ec-0f12-591d-ab34-529ddda05063")}catch{}})();function ct(t){return Array.isArray(t)?t:typeof t=="string"?[t]:[]}function xt(t){let e=[];for(let n of t)e.includes(n)||e.push(n);return e.includes("g")||e.push("g"),e.join("")}function bt(t){let e=t.trim();if(e.length===0)throw new l("history-redact --regex requires a non-empty pattern.",c.USAGE);let n=e,r="g";if(e.startsWith("/")&&e.length>1){let o=e.lastIndexOf("/");o>0&&(n=e.slice(1,o),r=xt(e.slice(o+1)))}if(n.length===0)throw new l("history-redact --regex cannot use an empty pattern.",c.USAGE);try{new RegExp(n,r)}catch{throw new l("Invalid --regex value; provide a valid JavaScript regular expression.",c.USAGE)}return{kind:"regex",source:n,flags:r}}function Rt(t,e){let n=[...new Set(ct(t).map(i=>i.trim()))].filter(i=>i.length>0).map(i=>({kind:"literal",value:i})),r=[...new Set(ct(e).map(i=>i.trim()))].filter(i=>i.length>0).map(bt),o=[...n,...r];if(o.length===0)throw new l("history-redact requires at least one matcher via --literal or --regex.",c.USAGE,{code:"missing_required_argument",required:"Provide --literal <value> and/or --regex <pattern>.",examples:['pm history-redact pm-a1b2 --literal "[redacted_path_prefix]/private"','pm history-redact pm-a1b2 --regex "/192\\\\.168\\\\.[0-9.]+/g" --replacement "[scrubbed_ip]"']});return o}function Et(t,e,n){if(e.length===0)return{value:t,replacements:0};let r=0,o=0;for(;r<=t.length;){let i=t.indexOf(e,r);if(i===-1)break;o+=1,r=i+Math.max(1,e.length)}return o===0?{value:t,replacements:0}:{value:t.split(e).join(n),replacements:o}}function vt(t,e,n){let r=new RegExp(e.source,e.flags),o=[...t.matchAll(r)];return o.length===0?{value:t,replacements:0}:{value:t.replace(r,n),replacements:o.length}}function lt(t,e,n){let r=t,o=0;for(let i of e){let s=i.kind==="literal"?Et(r,i.value,n):vt(r,i,n);r=s.value,o+=s.replacements}return{value:r,replacements:o}}function F(t,e,n){if(typeof t=="string")return lt(t,e,n);if(Array.isArray(t)){let r=0;return{value:t.map(i=>{let s=F(i,e,n);return r+=s.replacements,s.value}),replacements:r}}if(typeof t=="object"&&t!==null){let r=0,o={};for(let[i,s]of Object.entries(t)){let a=F(s,e,n);r+=a.replacements,o[i]=a.value}return{value:o,replacements:r}}return{value:t,replacements:0}}function kt(t){let e=structuredClone(_),n=0,r=0;for(let o=0;o<t.length;o+=1){let i=t[o];d(e)!==i.before_hash&&(n+=1),e=A(e,i.patch,o+1,i.op),d(e)!==i.after_hash&&(r+=1)}return{hashMismatchesBefore:n,hashMismatchesAfter:r,finalDocument:e}}function Ht(t,e,n){let r=0,o=!1,i=t.message;if(typeof t.message=="string"){let a=lt(t.message,e,n);i=a.value,r+=a.replacements,a.replacements>0&&(o=!0)}let s=t.patch.map(a=>{if(!Object.prototype.hasOwnProperty.call(a,"value"))return a;let h=F(a.value,e,n);return r+=h.replacements,h.replacements>0?(o=!0,{...a,value:h.value}):a});return{entry:{...t,message:i,patch:s},replacements:r,changed:o}}function Pt(t,e,n){let r=structuredClone(_),o=0,i=0,s=[];for(let a=0;a<t.length;a+=1){let h=Ht(t[a],e,n);i+=h.replacements,h.changed&&(o+=1);let f=d(r);r=A(r,h.entry.patch,a+1,h.entry.op);let u=d(r);s.push({...h.entry,before_hash:f,after_hash:u})}return{entries:s,finalDocument:r,entriesChanged:o,replacements:i}}function Dt(t){return Object.keys(t.metadata).length>0}async function At(t,e){let n=t.located?.itemPath??null;if(!t.located)return{raw:null,path:n,document:null};let r=await D(t.located,{schema:e.schema});return{raw:r.raw,path:n,document:r.document}}function Tt(t){if(!Dt(t.finalDocument))return{raw:null,path:null,document:null};let e=X(L(t.finalDocument),{schema:t.settings.schema});if(e.metadata.id!==t.subject.id)throw new l("history-redact would change the item id; narrow your patterns.",c.USAGE);return{document:e,path:q(t.pmRoot,e.metadata.type,t.subject.id,"toon",t.typeToFolder),raw:Y(e,{format:"toon",schema:t.settings.schema})}}function $t(t,e){return typeof t.message=="string"&&t.message.trim().length>0?t.message:`history-redact replaced ${e.replacements} match(es) across ${e.entriesChanged} entr${e.entriesChanged===1?"y":"ies"}.`}function jt(t){let e=[...t.rewritten.entries];if(t.dryRun||!t.changed)return{rewrittenEntries:e,auditEntryAdded:!1};let n=t.nextItemDocument??L(t.rewritten.finalDocument);return e.push(K({nowIso:S(),author:t.author,op:"history_redact",before:n,after:n,message:t.message})),{rewrittenEntries:e,auditEntryAdded:!0}}async function Ct(t){let e=[];return at({pmRoot:t.pmRoot,subject:t.subject,settings:t.settings,typeRegistry:t.typeRegistry,historyRawBeforeLock:t.historyRawBeforeLock,currentItemRawBeforeLock:t.currentItem.raw,operation:"history-redact",author:t.author,force:t.force,itemDocument:t.currentItem.document,applyRewrite:async({historyRawUnderLock:n})=>{let r=await it(t.pmRoot,t.author),o=new Set;t.currentItem.path&&o.add(t.currentItem.path),t.nextItem.path&&o.add(t.nextItem.path);let i=new Map;t.currentItem.path&&t.currentItem.raw!==null&&i.set(t.currentItem.path,t.currentItem.raw);let s=()=>{};try{try{t.nextItem.path&&t.nextItem.raw!==null&&t.nextItem.raw!==t.currentItem.raw&&await m(t.nextItem.path,t.nextItem.raw),t.currentItem.path&&(!t.nextItem.path||t.nextItem.path!==t.currentItem.path)&&await U.rm(t.currentItem.path,{force:!0}),await m(t.subject.historyPath,tt(t.rewrittenEntries))}catch(h){try{await St(t.subject.historyPath,n,o,i)}finally{await p(t.subject.historyPath)}throw h}await p(t.subject.historyPath);let a=t.nextItem.path??t.currentItem.path;a&&(e=await st({pmRoot:t.pmRoot,preferredFormat:t.settings.item_format,typeToFolder:t.typeRegistry.type_to_folder,schema:t.settings.schema,itemPath:a,...t.currentItem.path?{previousItemPath:t.currentItem.path}:{},document:t.nextItem.document}))}finally{await r().catch(a=>{s=()=>{throw a}})}s()},applyPostRewrite:async()=>[...e,...await Lt(t.subject.historyPath,[t.nextItem.path,t.currentItem.path])]})}async function St(t,e,n,r){e===null?await U.rm(t,{force:!0}):await m(t,e);for(let o of n){let i=r.get(o);i===void 0?await U.rm(o,{force:!0}):await m(o,i)}}async function Lt(t,e){let n=[],r=new Set(e.filter(o=>o!==null));for(let o of r)n.push(...await C({path:o,scope:"project",op:"history_redact"}));return n.push(...await C({path:t,scope:"project",op:"history_redact:history"})),n}async function Ut(t,e,n,r){let o=await P(t,e,n.id_prefix,n.item_format,r);if(o)return{id:o.id,historyPath:j(t,o.id),located:o};let i=ot(e,n.id_prefix),s=nt(e),a=i===s?[i]:[i,s];for(let h of a){let f=j(t,h);if(await k(f))return{id:h,historyPath:f,located:null}}throw new l(`Item ${e} not found`,c.NOT_FOUND)}async function xe(t,e,n){let r=G(process.cwd(),n.path);if(!await k(B(r)))throw new l(`Tracker is not initialized at ${r}. Run pm init first.`,c.NOT_FOUND);let o=await rt(r),i=M(o,z()),s=e.replacement??"",a=s.length===0,h=a?"[redacted]":s,f=Rt(e.literal,e.regex),u=await Ut(r,t,o,i.type_to_folder);if(!await k(u.historyPath))throw new l(`No history stream exists for ${u.id}.`,c.NOT_FOUND);let ht=await H(u.historyPath),x=await J(u.historyPath,u.id);if(x.length===0)throw new l(`No history entries exist for ${u.id}; nothing to redact.`,c.USAGE);let b=kt(x),y=Pt(x,f,h),T=b.hashMismatchesBefore+b.hashMismatchesAfter,$=!!e.dryRun,R=y.replacements>0,E=[];T>0&&E.push(`history_redact_preexisting_hash_mismatches:${T}`),R||E.push("history_redact_no_matches");let g=await At(u,o),w=Tt({pmRoot:r,subject:u,settings:o,typeToFolder:i.type_to_folder,finalDocument:y.finalDocument}),ut=(g.path??null)!==(w.path??null)||(g.raw??null)!==(w.raw??null),N=V(e.author,o.author_default),ft=$t(e,y),{rewrittenEntries:O,auditEntryAdded:dt}=jt({rewritten:y,dryRun:$,changed:R,nextItemDocument:w.document,author:N,message:ft}),v=Z(O);if(!v.ok)throw new l(`history-redact produced an invalid rewritten chain (${v.errors.join(", ")}).`,c.GENERIC_FAILURE);return!$&&R&&E.push(...await Ct({pmRoot:r,subject:u,settings:o,typeRegistry:i,historyRawBeforeLock:ht,currentItem:g,nextItem:w,author:N,force:e.force,rewrittenEntries:O})),{id:u.id,dry_run:$,changed:R,patterns:{literal_count:f.filter(I=>I.kind==="literal").length,regex_count:f.filter(I=>I.kind==="regex").length,total_count:f.length,replacement_is_default:a},history:{path:u.historyPath,entries_scanned:x.length,entries_changed:y.entriesChanged,replacements:y.replacements,hash_mismatches_before:b.hashMismatchesBefore,hash_mismatches_after:b.hashMismatchesAfter,preexisting_hash_mismatches:T,audit_entry_added:dt,verify_ok:v.ok,verify_errors:v.errors},item:{existed_before:g.path!==null,exists_after:w.path!==null,path_before:g.path,path_after:w.path,changed:ut},warnings:[...new Set(E)].sort((I,mt)=>I.localeCompare(mt)),generated_at:S()}}export{Mt as a,A as b,Gt as c,Bt as d,Zt as e,at as f,Ut as g,xe as h};
2
- //# sourceMappingURL=chunk-PKPOZXLL.js.map