@unbrained/pm-cli 2026.8.12 → 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.
- package/.claude-plugin/marketplace.json +2 -2
- package/CHANGELOG.md +162 -111
- package/dist/cli/error-guidance.js +4 -8
- package/dist/cli/main.js +40 -3
- package/dist/cli/register-assurance.js +28 -17
- package/dist/cli-bundle/bundle-manifest.json +141 -173
- package/dist/cli-bundle/chunks/chunk-BBOFSVAK.js +197 -0
- package/dist/cli-bundle/chunks/chunk-BFALV3YP.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-WLAHPSOX.js → chunk-FIW4P64F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BM5YJ2UW.js → chunk-G5JUB66K.js} +52 -52
- package/dist/cli-bundle/chunks/chunk-SBRKH6OR.js +2 -0
- package/dist/cli-bundle/chunks/chunk-TMJ7URWS.js +13 -0
- package/dist/cli-bundle/chunks/chunk-TXMEUUUY.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-KOQMGCTA.js → chunk-XAVMOK6B.js} +50 -50
- package/dist/cli-bundle/chunks/chunk-YAMTJL6Y.js +34 -0
- package/dist/cli-bundle/chunks/chunk-YSVSMJ2B.js +2 -0
- package/dist/cli-bundle/chunks/{register-list-query-XPCJRUUD.js → register-list-query-T3EHHNNV.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-4RJCBKRS.js → register-mutation-E27WCLSZ.js} +2 -2
- package/dist/cli-bundle/chunks/register-operations-4R6I7CPY.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-LLHAKP2V.js → register-setup-3YXZ444E.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-JAFRIWVF.js → chunk-4DQ2YERC.js} +4 -4
- package/dist/cli-bundle/focused-chunks/chunk-F43TT2QQ.js +8 -0
- package/dist/cli-bundle/focused-chunks/chunk-K7RWWOAG.js +4 -0
- package/dist/cli-bundle/focused-chunks/chunk-KFSZ3BP6.js +16 -0
- package/dist/cli-bundle/focused-chunks/{chunk-KHM2CS2C.js → chunk-KSEDUWVZ.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-KYUQGTSB.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ZMGWAYH7.js → chunk-LZ4MV3RH.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PGXJQLCT.js +155 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RWPAWUOT.js → chunk-PPFGQDSI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-Q4YY3XNF.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-QK753U3U.js +46 -0
- package/dist/cli-bundle/focused-chunks/chunk-QUMB2J27.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-SM7MTG27.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GQW4BPUT.js → chunk-WCVE2NIG.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XDNAW5OI.js +18 -0
- package/dist/cli-bundle/focused-chunks/{chunk-YIAXMC3T.js → chunk-YOOI3UZX.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZM6TZVHC.js +2 -0
- package/dist/cli-bundle/main.js +13 -13
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +45 -41
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +109 -1
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/checkpoint/checkpoint-gc.js +7 -12
- package/dist/core/extensions/activation-summary-markdown.js +5 -4
- package/dist/core/extensions/activation-summary.d.ts +2 -0
- package/dist/core/extensions/activation-summary.js +6 -2
- package/dist/core/extensions/capability-usage.d.ts +1 -1
- package/dist/core/extensions/capability-usage.js +4 -3
- package/dist/core/extensions/contribution-inventory.d.ts +1 -0
- package/dist/core/extensions/contribution-inventory.js +6 -2
- package/dist/core/extensions/extension-registries.js +3 -2
- package/dist/core/extensions/extension-types.d.ts +83 -1
- package/dist/core/extensions/extension-types.js +3 -2
- package/dist/core/extensions/loader.d.ts +2 -8
- package/dist/core/extensions/loader.js +53 -144
- package/dist/core/extensions/registration-values.d.ts +43 -0
- package/dist/core/extensions/registration-values.js +210 -0
- package/dist/core/extensions/runtime-registrations.d.ts +3 -1
- package/dist/core/extensions/runtime-registrations.js +12 -2
- package/dist/core/fs/fs-utils.d.ts +2 -0
- package/dist/core/fs/fs-utils.js +7 -3
- package/dist/core/history/drift-cache.js +4 -3
- package/dist/core/history/drift-scan.d.ts +6 -0
- package/dist/core/history/drift-scan.js +76 -58
- package/dist/core/history/workspace-history.d.ts +59 -0
- package/dist/core/history/workspace-history.js +197 -10
- package/dist/core/lock/lock-gc.js +8 -13
- package/dist/core/lock/lock.js +5 -4
- package/dist/core/output/output.js +12 -4
- package/dist/core/search/vector-stores.js +6 -11
- package/dist/core/store/item-metadata-cache.js +4 -4
- package/dist/core/telemetry/runtime.d.ts +6 -0
- package/dist/core/telemetry/runtime.js +101 -30
- package/dist/sdk/agent/command-recovery.d.ts +2 -0
- package/dist/sdk/agent/command-recovery.js +10 -2
- package/dist/sdk/annotations.js +4 -4
- package/dist/sdk/cli-contracts/completeness.js +9 -3
- package/dist/sdk/cli-contracts/enum-contracts.d.ts +1 -1
- package/dist/sdk/cli-contracts/flag-contracts.js +6 -3
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +6 -1
- package/dist/sdk/cli-contracts/runtime-contracts.js +155 -60
- package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +32 -0
- package/dist/sdk/cli-contracts/schemas/assurance-definition.js +25 -2
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +35 -5
- package/dist/sdk/cli-contracts/tool-schema.js +17 -2
- package/dist/sdk/cli-program.js +3 -3
- package/dist/sdk/comments.js +4 -3
- package/dist/sdk/compile-cache.js +4 -3
- package/dist/sdk/compose.d.ts +3 -1
- package/dist/sdk/compose.js +16 -2
- package/dist/sdk/context-relevance.js +12 -4
- package/dist/sdk/context-signal-store.js +4 -3
- package/dist/sdk/extension/install-runtime.js +4 -4
- package/dist/sdk/extension/managed-state.js +4 -3
- package/dist/sdk/extension-contracts.d.ts +1 -1
- package/dist/sdk/flag-invocation-contracts.js +5 -6
- package/dist/sdk/generated/generated-error-code-catalog-part-1.js +14 -2
- package/dist/sdk/governance/assurance-action.d.ts +27 -3
- package/dist/sdk/governance/assurance-action.js +112 -28
- package/dist/sdk/governance/assurance-mutation-error.d.ts +7 -0
- package/dist/sdk/governance/assurance-mutation-error.js +25 -2
- package/dist/sdk/governance/assurance-presets.d.ts +54 -0
- package/dist/sdk/governance/assurance-presets.js +136 -0
- package/dist/sdk/governance/assurance-runtime.d.ts +4 -0
- package/dist/sdk/governance/assurance-runtime.js +109 -8
- package/dist/sdk/governance/assurance.d.ts +39 -0
- package/dist/sdk/governance/assurance.js +145 -6
- package/dist/sdk/governance/gc.js +5 -11
- package/dist/sdk/governance/health.js +18 -6
- package/dist/sdk/governance/validate-history-drift.d.ts +7 -0
- package/dist/sdk/governance/validate-history-drift.js +68 -0
- package/dist/sdk/governance/validate.js +6 -48
- package/dist/sdk/graph/assembly.d.ts +23 -0
- package/dist/sdk/graph/assembly.js +54 -2
- package/dist/sdk/graph/durable-cache.js +91 -3
- package/dist/sdk/graph/governance-contracts.d.ts +12 -0
- package/dist/sdk/graph/governance-contracts.js +29 -0
- package/dist/sdk/graph/governance.d.ts +51 -3
- package/dist/sdk/graph/governance.js +216 -35
- package/dist/sdk/graph/index.d.ts +2 -2
- package/dist/sdk/graph/index.js +4 -4
- package/dist/sdk/graph/mutation-advisory.js +15 -7
- package/dist/sdk/graph/remediation.js +12 -2
- package/dist/sdk/guide.js +4 -4
- package/dist/sdk/history-read.d.ts +8 -0
- package/dist/sdk/history-read.js +2 -2
- package/dist/sdk/index.d.ts +3 -2
- package/dist/sdk/index.js +5 -4
- package/dist/sdk/linked-artifacts.d.ts +2 -0
- package/dist/sdk/linked-artifacts.js +29 -4
- package/dist/sdk/merge/install.js +5 -4
- package/dist/sdk/query/activity.js +4 -3
- package/dist/sdk/query/history.js +20 -3
- package/dist/sdk/read-output-budget.d.ts +2 -0
- package/dist/sdk/read-output-budget.js +12 -5
- package/dist/sdk/read-output-contracts.d.ts +61 -5
- package/dist/sdk/read-output-contracts.js +210 -28
- package/dist/sdk/read-output-rows.d.ts +11 -0
- package/dist/sdk/read-output-rows.js +47 -2
- package/dist/sdk/relationship-history.js +5 -5
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +3 -3
- package/dist/sdk/runtime.js +5 -3
- package/dist/sdk/schema-migration.js +4 -4
- package/dist/sdk/test/execution.js +4 -4
- package/dist/sdk/workspace-memory.js +4 -4
- package/dist/sdk/workspace-snapshot.js +8 -14
- package/dist/sdk/workspace-transaction-gc.js +4 -9
- package/dist/sdk/workspace-transaction.js +4 -4
- package/dist/sdk/workspace.js +4 -3
- package/docs/ASSURANCE.md +163 -3
- package/docs/COMMANDS.md +31 -2
- package/docs/CONFIGURATION.md +2 -0
- package/docs/EXTENSIONS.md +11 -12
- package/docs/READ_OUTPUT_CONTRACTS.md +44 -8
- package/docs/RELATIONSHIP_GRAPH.md +34 -4
- package/docs/SDK.md +29 -8
- package/docs/SDK_CONTEXT_INTEGRITY.md +32 -1
- package/docs/TESTING.md +47 -16
- package/docs/performance/sdk-entrypoint-import-costs.md +20 -13
- package/marketplace.json +2 -2
- package/package.json +6 -6
- package/packages/pm-beads/extensions/beads/index.ts +1 -0
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/extensions/calendar/index.ts +1 -0
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/extensions/digital-twin/index.ts +7 -0
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/extensions/governance-audit/index.ts +4 -0
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/extensions/guide-shell/index.ts +5 -0
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/extensions/linked-test-adapters/index.ts +6 -0
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/extensions/search-advanced/index.ts +2 -0
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/extensions/templates/index.ts +4 -0
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/extensions/todos/index.ts +2 -0
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/extensions/vcs/index.ts +7 -0
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/scripts/bundle-cli.mjs +17 -4
- package/sdk/public-surface.json +390 -60
- package/dist/cli-bundle/chunks/chunk-3PS7X6GS.js +0 -8
- package/dist/cli-bundle/chunks/chunk-7KL6KMWF.js +0 -13
- package/dist/cli-bundle/chunks/chunk-D55A5AEN.js +0 -33
- package/dist/cli-bundle/chunks/chunk-KIKDWECH.js +0 -196
- package/dist/cli-bundle/chunks/chunk-R76342NV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RBTK5EZV.js +0 -5
- package/dist/cli-bundle/chunks/chunk-VLUQOIDT.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-2OGISOVR.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2DALMVF7.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-5OQIMELN.js +0 -155
- package/dist/cli-bundle/focused-chunks/chunk-5TAGTDRE.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-ECADZMVC.js +0 -18
- package/dist/cli-bundle/focused-chunks/chunk-EJGXRA6B.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-FFGSZCPK.js +0 -16
- package/dist/cli-bundle/focused-chunks/chunk-ISKOBJCM.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KPSXVBDV.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-KTLOKKCQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LGYK3NUF.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-NBLUKITQ.js +0 -4
- package/dist/cli-bundle/focused-chunks/chunk-NYLOUPOB.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-Q4T463SD.js +0 -31
- package/dist/cli-bundle/focused-chunks/chunk-QVZVY53N.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UTEWXDEQ.js +0 -17
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import{f as Ae,g as nt}from"./chunk-GQW4BPUT.js";import{a as Xt,g as tt,i as Zt}from"./chunk-QVZVY53N.js";import{g as bn,i as vn}from"./chunk-KPSXVBDV.js";import{s as ge,t as yn,u as ye,ua as kn,v as wn}from"./chunk-ECADZMVC.js";import{Ka as dn,Oa as Z,Pa as un,Ra as mn,T as de,U as X,Ua as fn,Va as pn,Xa as M,Y as nn,ca as rn,da as on,eb as hn,ga as sn,ha as an,jb as _n,k as J,ka as it,ma as cn,mb as Ee,nb as Ce,ob as Ie,q as tn,qb as gn,tb as Te,wa as rt,ya as ln}from"./chunk-5OQIMELN.js";import{$ as Yt,E as V,J as Vt,K as B,L as _e,N as U,Q as Kt,Qa as Qt,U as L,ca as Ze,h as qt,o as Je,p as N,r as Ht,s as ae,v as Xe,w as Wt}from"./chunk-NBLUKITQ.js";import{j as en}from"./chunk-5TAGTDRE.js";import{N as zt,U as Gt,V as xe,Y as _,Z as g,aa as Qe,ba as Jt,ca as et,t as Ye}from"./chunk-ISKOBJCM.js";import Fe from"node:fs/promises";import Pe from"node:path";import{Option as lc}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 Oe(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 Q(e,t){return e[t]===!1?!0:void 0}function Rn(e,t){return t.some(n=>e[n]===!0)?!0:void 0}function Sn(e,t){for(let[n,i]of Object.entries(t))n==="__proto__"||n==="constructor"||n==="prototype"||Object.hasOwn(e,n)||(e[n]=i)}function xn(e){let t=r=>tt(e,Oe(Ae,r)),n=r=>Zt(e,Oe(nt,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,Oe(nt,"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:Rn(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 Sn(i,e),i}function C(e,t){let n=Oe(Xt,t),i=tt(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:Q(e,"notes"),noLearnings:Q(e,"learnings"),noFiles:Q(e,"files")??t,filterFilesMissing:t,noDocs:Q(e,"docs")??n,filterDocsMissing:n,noTests:Q(e,"tests"),noComments:Q(e,"comments"),noDeps:Q(e,"deps"),emptyBody:w(e,"emptyBody"),noLinkedCommand:Q(e,"linkedCommand")}}function ot(e){let t={status:C(e,"status"),type:C(e,"type"),tag:C(e,"tag"),priority:C(e,"priority"),deadlineBefore:C(e,"deadlineBefore"),deadlineAfter:C(e,"deadlineAfter"),updatedAfter:C(e,"updatedAfter"),updatedBefore:C(e,"updatedBefore"),createdAfter:C(e,"createdAfter"),createdBefore:C(e,"createdBefore"),today:w(e,"today"),recent:w(e,"recent"),ids:C(e,"ids"),assignee:C(e,"assignee"),assigneeFilter:C(e,"assigneeFilter"),parent:C(e,"parent"),sprint:C(e,"sprint"),release:C(e,"release"),limit:C(e,"limit"),offset:C(e,"offset"),noTruncate:Q(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:Rn(e,["filterEstimatesMissing","filterEstimateMissing"]),filterResolutionMissing:w(e,"filterResolutionMissing"),filterMetadataMissing:w(e,"filterMetadataMissing"),...Fr(e)};return Sn(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 we(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function yc(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 wc(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 kc(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 Nr=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"]),Mr=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 En(e,t){let n={},i=t!==void 0&&Mr.has(t),r=t==="files"||t==="files-discover"||t==="docs";for(let[o,s]of Object.entries(e)){if(Array.isArray(s)&&Nr.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 bc(e,t){let n=Yt(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=En({...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 vc(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 Rc(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 Sc(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 xc(e){return e.trim().toLowerCase().split(/\s+/).filter(Boolean).join(" ")}function ct(e){return Array.isArray(e)?e.map(t=>String(t)).filter(t=>t.length>0):[]}function Ac(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 Ec(e,t){return{changedFields:e.fullChangedFields===!0?"full":"compact",idOnly:e.idOnly===!0,runnerOptions:{...t}}}function at(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 st(e){if(typeof e=="string"&&e.trim().length>0)return e;if(Array.isArray(e))return ct(e)}function De(e){if(typeof e=="number"&&Number.isFinite(e)||typeof e=="string"&&e.trim().length>0)return e}function Cc(e){let t=st(e.kind),n=st(e.exemptIsolate),i=st(e.exemptIsolateType);return{...t===void 0?{}:{kind:t},maxDepth:De(e.maxDepth),limit:De(e.limit),after:R(e,"after"),direction:R(e,"direction"),maxPaths:De(e.maxPaths),sample:De(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 Ic(e){return{status:R(e,"filterStatus"),list:we(e.list)?ot(e.list):at(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 An(e){let t={};for(let[n,i]of Object.entries(e))Ur.has(n)||(t[n]=i);return Cn(t)}function Cn(e){let t=En(e,"update-many");for(let n of Ae)for(let i of n.keys){let r=t[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=String(r))}return xn(t)}function Tc(e){if(we(e.list)||we(e.update)){let t=we(e.update)?e.update:An(e);return{status:T(e,"filterStatus"),list:we(e.list)?ot(e.list):at(e),update:Cn(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:at(e),update:An(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 ee(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"]],In=e=>typeof e=="string"?e:"",Tn=e=>{let t=e??{},n=In(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(In(t.ts))>=Gr);return qr[i][r]};function On(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=Tn(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 jc=(e,t,n=20,i=new Set)=>On(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 lt=async(e,t=20,n=!1)=>{let i=Pe.join(e,"history"),r;try{r=(await Fe.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 Fe.readFile(Pe.join(i,k),"utf8"))}catch{p=new Set}for(let y of r){let v;try{v=await Fe.readFile(Pe.join(i,y),"utf8")}catch{continue}let x=y.slice(0,-6),S=On(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&&ee("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&&ee("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===Z||/^[a-z0-9][a-z0-9-]*$/iu.test(i);return(n<1||!o||!Number.isSafeInteger(r)||r<1)&&ee(`history-author-acknowledge --event expects <item-id>:<one-based-line>, received "${t}".`,{code:"history_author_acknowledge_target_unreadable"}),{item_id:i,line:r}})}function Bc(e,t){let n=Wr(ct(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&&ee("Specify exactly one selector: events or all_actionable.",{code:"history_author_acknowledge_selector_required"}),s>1&&ee("Author acknowledgment accepts either explicit events or all_actionable, not both.",{code:"history_author_acknowledge_selector_conflict"});let a=t.all_actionable===!0?(await lt(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)&&ee("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===Z||/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"});let k;try{let h=(await Fe.readFile(Pe.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];k=JSON.parse(h??"")}catch{ee(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,{code:"history_author_acknowledge_target_unreadable"})}Tn(k)!=="actionable_unknown"&&ee(`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 M(e),u=await mn({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 Le,realpath as ft,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 ke from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var Fn="# pm-cli:runtime-cache:start",dt="# pm-cli:runtime-cache:end",Pn=".agents/pm",ut=["runtime/","search/","locks/","transactions/","checkpoints/"],Xr=["search/eval-queries.json"];async function Dn(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 mt(e){let t=e.replaceAll("\\","/");return ke.isAbsolute(e)||t===".."||t.startsWith("../")}function Zr(e=Pn){let t=Nn(e);return[Fn,...ut.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...Xr.map(n=>`!${t}/${n}`),dt].join(`
|
|
2
|
-
`)}async function Wc(e,t={}){let n=ke.join(e,".gitignore"),i=Pn;if(t.pmRoot!==void 0){let d=Nn(ke.relative(ke.resolve(e),ke.resolve(t.pmRoot)));if(mt(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Dn(()=>Yr(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let o=r.indexOf(Fn),s=r.indexOf(dt),c=(o>=0&&s>=o?`${r.slice(0,o)}${r.slice(s+dt.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
|
|
3
|
-
|
|
4
|
-
`:""}${Zr(i)}
|
|
5
|
-
`;return l===r?{path:n,changed:!1}:(await Dn(()=>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 Ln(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]="94d2a7a8-ce00-5689-b2f6-3d4813234b55")}catch{}})();var ht=io(no),Ne="# pm-cli:merge-drivers:start",Bn="# pm-cli:merge-drivers:end",ue="# pm-cli:merge-drivers:v2:start",pt="# pm-cli:merge-drivers:v2:end",ro="merge-fence";function Mn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function Un(){let e=Wt(import.meta.url,["../../.."]);return`${Mn(process.execPath)} ${Mn(O.join(e,"dist","cli.js"))}`}var zn=[{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=Ln(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 be(e){try{let{stdout:t}=await ht("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await ft(t.trim())}catch{return null}}async function Gn(e){let t=await be(e);if(t===null)throw new g("pm merge install requires a git repository (merge drivers are git configuration).",_.USAGE);return t}function _t(e,t){return O.relative(e,t).replaceAll("\\","/")}function K(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function $n(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=$n(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=$n(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 N(n.value)||!await N(i.value))return!1;try{let r=O.dirname(O.dirname(i.value)),o=JSON.parse(await Le(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 gt(e,t){let n=e.length>0?`${e}/`:"",i=[`${K(`${n}**/*.toon`)} merge=pm-item-toon`,`${K(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${K(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${K(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${K(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${K(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${K(`${n}settings.json`)} merge=pm-json`),i.push(`${K(`${n}**/*.json`)} merge=pm-json`),i.push(`${K(`${n}extensions/**`)} -merge`),i.push(`${K(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}function jn(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 qn(e,t,n){let i=O.join(e,".gitattributes"),r="";try{r=await Le(i,"utf8")}catch(l){if(!(l instanceof Error&&"code"in l&&l.code==="ENOENT"))throw l}let o=[ue,...t,pt].join(`
|
|
6
|
-
`),a=jn(jn(r,ue,pt),Ne,Bn).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 Me(e){let t=V(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function Hn(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 Le(x,"utf8");if(A.includes(ue)||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(ue),c=a?ue:Ne,l=a?pt:Bn,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=gt(_t(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 Wn(e){let t=Un(),n=[],i=[];for(let r of zn){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 ht("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 ul(e){let t;try{t=await Gn(O.resolve(e))}catch{return{status:"no_git"}}let n=_t(t,O.resolve(e)),i=await M(e),r=de(void 0,i.author_default),o=await nn(e,ro,i.locks.ttl_seconds,r,!1,pn(i).force_required_for_stale_lock,i.locks.wait_ms);try{let s=O.join(t,".gitattributes"),a;try{a=await Le(s,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:s};throw u}if(!a.includes(ue)&&!a.includes(Ne))return{status:"not_installed",path:s};let c=await M(e),l=Me(c),d=await qn(t,gt(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await o()}}async function ml(e,t){let n=oo({cwd:process.cwd(),explicitPath:t.path,dryRun:e.dryRun===!0,environment:process.env}),i=n.pm_root;if(!await N(U(i)))throw new g(`Tracker is not initialized at ${i}. Run pm init first.`,_.NOT_FOUND);let r=await Gn(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([ft(t),ft(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=_t(o,r);if(mt(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 M(r),c=Me(a),l=gt(s,c),d=[],u=Un();for(let f of zn)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 ht("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 qn(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:X()}}import{execFile as co}from"node:child_process";import{randomUUID as lo}from"node:crypto";import{readdir as uo,readFile as Yn}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 yt(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 Jn(e,t){let n=j.dirname(j.resolve(e,t));for(let i=0;i<12;i+=1){if(await N(j.join(n,"settings.json")))return n;let r=j.dirname(n);if(r===n)break;n=r}return null}function wt(e){return j.join(e,"merge-receipts")}function $e(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:Vn(t.retained)??et(Qe(t.retained)),discarded_hash:Vn(t.discarded)??et(Qe(t.discarded))}))}}function Vn(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 vl(e){let t=await yt(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:X(),value_availability:"clone_local"};await Je(t),await ae(j.join(t,$e(o.id)),`${JSON.stringify(o,null,2)}
|
|
11
|
-
`);let s=await Jn(e.cwd,o.item_path);if(s!==null){let a=wt(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 Je(a),await ae(j.join(a,$e(o.id)),`${JSON.stringify(l,null,2)}
|
|
12
|
-
`)}return o}async function Kn(e,t){if(!await N(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 Yn(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 kt(e,t={}){let n=await yt(e),i=n===null?[]:await Kn(n,t),r=t.pmRoot??j.join(e,".agents","pm"),o=await Kn(wt(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 Xn(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 Rl(e,t){let n=await yt(e);if(n===null)return;await ae(j.join(n,$e(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:X()},null,2)}
|
|
13
|
-
`);let i=await Jn(e,t.item_path);if(i!==null){let r=j.join(wt(i),$e(t.id));if(await N(r)){let o=JSON.parse(await Yn(r,"utf8"));await ae(r,`${JSON.stringify({...o,state:"reconciled",reconciled_at:X()},null,2)}
|
|
14
|
-
`)}}}async function Sl(e){let t=await kt(e.cwd??process.cwd(),{...e,includeLossless:!0});return{ok:!0,count:t.length,receipts:t,generated_at:X()}}import me from"node:fs/promises";import fe 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 me.readdir(fe.join(e,r))}catch{return}for(let s of o)for(let a of Vt)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=it(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 bt(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 me.readdir(fe.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 me.readFile(fe.join(e,"history",r),"utf8")}catch(s){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:bt("history stream",s)});continue}_o({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},o)}return n}function Zn(e){let t=it(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 Ht(U(e))}catch(o){n+=1,t.push({path:"settings.json",detail:bt("configuration file",o)})}if(i!==null){n+=1;let o=Zn(i);o!==null&&t.push({path:"settings.json",detail:o})}let r;try{r=await me.readdir(fe.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 me.readFile(fe.join(e,"schema",o),"utf8")}catch(c){t.push({path:`schema/${o}`,detail:bt("configuration file",c)});continue}let a=Zn(s);a!==null&&t.push({path:`schema/${o}`,detail:a})}return{scanned:n,unparseable:t}}async function Qn(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=fe.join(e,u.relativePath);return cn(await me.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 ei 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 ti(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 ni(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 Ll(e){let t=/^(\d+):(\d+)$/u.exec(e.trim()),n=t?{start:Number(t[1]),end:Number(t[2])}:void 0;if(ni(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=ei.relative(e.workspaceRoot,ei.resolve(e.workspaceRoot,e.sourcePath)),n=await ti(e.workspaceRoot,["blame","--line-porcelain","-L",`${e.lineRange.start},${e.lineRange.end}`,"--",t]),i=await ti(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=vn(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 ii(e){ni(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 Lt from"node:fs/promises";import{realpathSync as Ks}from"node:fs";import{execFile as Ys}from"node:child_process";import $ from"node:path";import{promisify as Js}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 ri(e){return Object.values(Oo(e))}import pe from"node:fs/promises";import{createHash as Do}from"node:crypto";import si 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]="1bffe32d-543d-588a-a1e9-d72553cab06c")}catch{}})();var ai=4,Fo="history-drift-cache.json";function ci(e){return si.join(e,"runtime",Fo)}async function Po(e){try{let t=await pe.readFile(ci(e),"utf8"),n=JSON.parse(t);return n.version!==ai||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function li(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function No(e,t,n,i,r){let o=un(e),s;try{s=await pe.stat(o)}catch(l){return li(l,"ENOENT")||r.unreadableStreams.push(Z),!1}let a=r.missingStreams.length,c=await ui({itemId:Z,historyPath:o,stat:s,cached:t[Z],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(Z),n[Z]={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 di(e){return Do("sha256").update(e).digest("hex")}async function Lo(e){let t=await pe.readFile(e,"utf8");return di(t)}async function Mo(e){let t=await pe.readFile(e,"utf8"),n=di(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=dn(i);return{latestAfterHash:r,chainOk:o.ok,contentHash:n,itemHashVersion:o.item_hash_version??rt}}function $o(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function oi(e,t,n){try{let i=await Mo(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function ui(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 oi(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??rt},cacheDirty:!1}:{verification:await oi(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function mi(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=Kt(e,u.id),f;try{f=await pe.stat(m)}catch(x){li(x,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let k=o[u.id],p=await ui({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;ln({metadata:y,body:h},p.verification.itemHashVersion)!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await No(e,o,s,c,i);if(a||=l,a||Object.keys(o).length!==Object.keys(s).length){let u=ci(e);try{await pe.mkdir(si.dirname(u),{recursive:!0}),await ae(u,JSON.stringify({version:ai,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"],vt=["metadata","resolution","estimates","lifecycle"],Bo="completed";function Rt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function fi(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function pi(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=fi(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 ${Rt(i)}`,gate:"resolution"})}return t}function hi(e){let t=[];for(let n of e){let i=fi(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 ${Rt(i)}`,gate:"metadata"})}return t}function _i(e,t){return e.map(n=>{let i=fn(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 gi(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 yi(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 ${Rt(n.path)}`})}return t}function wi(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: ${vt.join(", ")}.`,_.USAGE);return new Set(jo)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(vt.includes(r)){n.add(r);continue}throw new g(`Unknown --fix-scope value "${i}". Supported values: ${vt.join(", ")}.`,_.USAGE)}return n}function ki(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 ve(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 bi(e){return typeof e=="string"&&e.trim().length>0}function vi(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||bi(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:bi(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 Ri(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 Si=3;function xi(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Ai(e,t,n=Si){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Si,r=new Map;for(let o of t){let s=xi(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(xi(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 Ei(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 Re(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 Ci(e){return`${e.item_id} ${e.link_kind}`}function Ii(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(Ci(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Ci(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 Ti(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 Oi 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 St(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Qo(e){return`'${e.replaceAll("'","'\\''")}'`}async function es(e,t=Vo){return t(e).catch(()=>Oi.resolve(e))}async function Di(e){let t=await be(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=St(Oi.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=ut.map(o=>`${i}/${St(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(St(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]="3fe80124-596b-591c-9f0d-fbbc129c6bb4")}catch{}})();var is=["path","scope","note"],rs=["pattern","glob","path","scope","note"],os=["path"],ss=["from","to"],as=new Set(["note","scope"]);function Pi(e){let t=e??"project";if(!Ye.includes(t))throw new g(`Invalid scope "${e}". Valid scopes: ${Ye.join(", ")} (default: project).`,_.USAGE);return t}function Ni(e){return e.startsWith("```")||e.includes(`
|
|
16
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:yn(e)}function cs(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Ni(n)||!n.includes(",")?[t]:kn(n)})}function ls(e,t){return e?cs(e).map(n=>{let i=n.trim(),r=Ni(i)?ge(n,"--add"):{path:i};if(ye(r,"--add",is),!r.path)throw new g(`--add requires path=<value> or a bare ${t} path`,_.USAGE);return{path:r.path,scope:Pi(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=ge(n,"--add-glob");ye(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:Pi(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=ge(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(ye(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=ge(t,"--migrate");ye(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 xt(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 te(e){return e.split(z.sep).join("/")}function At(e,t,n=process.cwd()){let i=e.trim();if(Re(i))return i;if(z.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return te(i.replaceAll("\\",z.sep));let r=z.relative(t,n);return r.startsWith(`..${z.sep}`)||r===".."||z.isAbsolute(r)?te(z.normalize(i)):te(z.relative(t,z.resolve(n,i)))}async function fs(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=>At(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 ps(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 hs(e){return`${e.path}::${e.scope}`}function Et(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function Ct(e){return[...new Map(e.map(t=>[hs(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function _s(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(Re(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&&l.code==="ENOENT"){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 gs(e,t,n,i){let r=0;for(let s=0;s<e.length;s+=1){let a=xt(e[s].path,i);a!==e[s].path&&(e[s]={...e[s],path:a},r+=1)}return{adds:t.map(s=>{let a=xt(s.path,i);return a!==s.path&&(r+=1),{...s,path:a}}),removes:n.map(s=>xt(s,i)),count:r}}function ys(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=Ct(e);return i?r:Et(r)}async function Fi(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 _s(t,e.workspaceRoot):void 0}}async function je(e,t,n,i){let{metadataKey:r}=i,o=wn(),s=B(process.cwd(),n.path),a=_e(s),c=process.cwd();if(!await N(U(s)))throw new g(`Tracker is not initialized at ${s}. Run pm init first.`,_.NOT_FOUND);let l=await M(s),d=V(l,J()),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:At(P.path,a,c)})),h=ds(m),y=await fs(h,a,c),v=ps([...p,...y],t.note,p.length>0||h.length>0),x=us(f).map(P=>At(P,a,c)),S=ms(k);if(!(v.length>0||x.length>0||S.length>0)){let P=await Ee(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 Ce(P,{schema:l.schema})).document.metadata[r]??[];return Fi({id:P.id,artifacts:I,changed:!1,options:t,workspaceRoot:a})}let Y=de(t.author,l.author_default),H=await Te({pmRoot:s,settings:l,id:e,op:i.op,author:Y,message:t.message,force:t.force,skipNoop:!0,mutate(P){let b=P.metadata,I=b[r]??[],le=[...I],se=gs(le,v,x,S),Ke=ys(le,se.adds,se.removes,i.supportsAppendStable&&t.appendStable===!0);Ke.length>0?b[r]=Ke:delete b[r];let Ut=!Jt(I,Ke);return{changedFields:Ut?[r]:[],warnings:Ut&&se.count>0?[`path_migrations_applied:${se.count}`]:[]}}}),E=H.item[r]??[],F=H.warnings.find(P=>P.startsWith("path_migrations_applied:")),W=F?Number(F.slice(24)):0;return Fi({id:H.item.id,artifacts:E,changed:H.changedFields.includes(r),migrationsApplied:W,options:t,workspaceRoot:a})}function Be(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 Li(e,t,n){let i=await je(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Be(i,"docs")}import Mi 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 ws=32768;function It(e){return te(G.normalize(e))}async function Ue(e){try{return await Mi.realpath(e)}catch{return G.resolve(e)}}function he(e,t){let n=G.isAbsolute(e.path)?G.resolve(e.path):G.resolve(t,e.path);return`${It(n)}::${e.scope}`}function ze(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)=>ze(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))ze(r,t?`${t}.${i}`:i,n)}function ks(e){let t=[];return ze(e.metadata,"metadata",t),ze(e.body,"body",t),t}function bs(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 vs(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,ws);for(let[a,c]of[[n,r.value],[i,s]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=bs(l[0]);!d||o.has(d)||(o.add(d),t.push({field:r.field,value:d}))}}}return t}async function Rs(e,t,n=t){let i=G.isAbsolute(e)?G.resolve(e):G.resolve(n,e),r;try{r=await Mi.stat(i)}catch{return}if(!r.isFile())return;let[o,s]=await Promise.all([Ue(t),Ue(i)]);if(Xe(o,s)){let a=G.relative(o,s);return!a||a.startsWith("..")||G.isAbsolute(a)?void 0:{path:It(a),scope:"project"}}return{path:It(i),scope:"global"}}async function Ss(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>he(c,t))),r=new Map,o=vs(ks(e)),s=new Map;await Promise.all([...new Set(o.map(c=>c.value))].map(async c=>{s.set(c,await Rs(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=he(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 $i(e,t,n){let i=await je(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Be(i,"files")}async function xs(e,t){let n=await Ue(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 te(s);let a=await Ue(s);return Xe(n,a)?te(G.relative(n,a)):te(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 As(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 ji(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}function Bi(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 Es(e){return e.metadata.map(t=>({item:t,files:(t.files??[]).filter(n=>e.paths.includes(te(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(Bi)}async function Cs(e){if(e.explain)return ii({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 Is(e){if([e.strictRead,e.noTruncate,e.explain,tn()].includes(!0))return null;let t=await _n(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?hn({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function Ts(e){let t=[],n=await Ie(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema),i=Es({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 Cs({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:Bi(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:ji(c.item),files:c.files,...o?{traceability:o.explanations.get(c.item.id)}:{}})),...o?{traceability_receipt:o.receipt}:{}}}async function Wd(e,t){let n=B(process.cwd(),t.path),i=_e(n);if(!await N(U(n)))throw new g(`Tracker is not initialized at ${n}. Run pm init first.`,_.NOT_FOUND);let r=await xs(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 M(n),s=V(o,J()),{offset:a,limit:c}=As(e),l=await Is({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:ji(d.item),files:d.files}))}:Ts({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 Vd(e,t,n){let i=B(process.cwd(),n.path),r=_e(i);if(!await N(U(i)))throw new g(`Tracker is not initialized at ${i}. Run pm init first.`,_.NOT_FOUND);let o=await M(i),s=V(o,J()),a=await Ee(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 Ce(a,{schema:o.schema}),l=await Ss(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=de(t.author,o.author_default),p=d.map(E=>({path:E.path,scope:E.scope,note:f})),h=[],y=new Set,v=await Te({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=>he(I,r)));h=[],y.clear();for(let[I,le]of p.entries()){let se=he(le,r);W.has(se)||(F.push(le),W.add(se),h.push(le),y.add(I))}let P=Ct(F),b=t.appendStable?P:Et(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=>he(E,r))),A=x.filter(E=>S.has(he(E,r))),Y=d.filter((E,F)=>!y.has(F)),H=[...u,...Y];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 Os}from"node:fs";import Ge 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 Ds=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),Tt=new Set(["--pm-path","--path","--author"]),Fs={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"])},Ps=new Set(["-p","--package"]),Ns=new Set(["-c","--call"]),Ls=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),Ms=new Set(["-C","--prefix","--userconfig","--cache"]),Xd=new Set(["--cwd"]),Zd=new Set(["--cwd"]),$s=new Set(["exec","x"]),Qd=new Set(["run","run-script"]),eu=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function js(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function Bs(e,t=process.cwd()){let n=Us(e.split(" ").filter(s=>s.length>0));if(n.length===0)return null;let[i,...r]=n;if(Ui(i)||zi(i,t))return r;if(i==="node"&&r[0]&&zi(r[0],t))return r.slice(1);let o=i==="npx"||i==="bunx"?Ot(r):i==="pnpm"?qs(r):i==="npm"?Hs(r):null;return o&&(Ui(o.command)||Gs(o.command))?o.args:null}var Gi=(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 js(o)){let c=Bs(a),l=c?Ws(c):null,d=l&&Ds.has(l.subcommand)?Vs(l.remaining,Fs[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 Us(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 tu(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Tt.has(n)){t+=2;continue}t+=1;continue}return n}}function Ui(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function zs(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 Gs(e){let t=zs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function zi(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=Ge.resolve(t,e);try{return JSON.parse(Os(Ge.join(Ge.dirname(Ge.dirname(i)),"package.json"),"utf8")).name==="@unbrained/pm-cli"}catch{return!1}}function Ot(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(Ns.has(i)){t+=1;break}t+=Ps.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function qi(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 qs(e){let t=qi(e,Ls);return t?.subcommand!=="dlx"?null:Ot(t.args)}function Hs(e){let t=qi(e,Ms);return!t||!$s.has(t.subcommand)?null:Ot(t.args)}function Ws(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(Tt.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Vs(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("=")&&(Tt.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 Hi(e){return e.includeBody?gn(e.pmRoot,e.settings.item_format,e.typeToFolder,e.warnings,e.settings.schema,{forceSourceScan:!0}):Ie(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]="5affc1f1-2b4f-5f04-a6cb-c3e389bcb356")}catch{}})();var Xs=["src","tests","docs"],Zs=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Qs=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),ea=["resolution","expected_result","actual_result"],ta=["default","tracked-all","tracked-all-strict"],Wi=["core","strict","custom"],He=["off","warn","error"];var Ft=["author","acceptance_criteria","estimated_minutes","close_reason"],Xi=[...Ft,"reviewer","risk","confidence","sprint","release"],Mt=Array.from(new Set(Xi)),na={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"},ia={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"},ra={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"},oa={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"},sa={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"},aa=32*1024*1024,ca=1e4,Zi=40,ie=5,la=4096,da=255,ua=Js(Ys);function Qi(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?Qi(i):i);return t}function ma(e){return{...e,checks:e.checks.map(t=>({...t,details:Qi(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 ce(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function Vi(e){return ce(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 Ve(e,t){return an(e,t)??e}function Se(e,t){return t.terminal_statuses.has(Ve(e,t))}function re(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function qe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function fa(e){let t=re(Gt),n={blocked_reason:re(xe.blocked_reason),resolution:re(xe.resolution),actual_result:re(xe.actual_result)},i=re(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:re(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:re(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:re(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:qe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:qe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:qe(r.resolution,n.resolution)?"default":"settings",actual_result:qe(r.actual_result,n.actual_result)?"default":"settings"}}}function er(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(Wi.includes(t))return t;throw new g(`Unknown --metadata-profile value "${e}". Supported values: ${Wi.join(", ")}.`,_.USAGE)}function tr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(He.includes(t))return t;throw new g(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${He.join(", ")}.`,_.USAGE)}function nr(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(He.includes(t))return t;throw new g(`Unknown --parent-cycle-severity value "${e}". Supported values: ${He.join(", ")}.`,_.USAGE)}function pa(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>na[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function ha(e,t,n){let i=pa(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...Ft],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...Xi],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:[...Ft],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var _a=new Set(["acceptance_criteria","estimated_minutes"]);function ir(e,t,n,i){return!i&&_a.has(t)&&Se(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"?Ve(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 rr(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: ${ta.join(", ")}.`,_.USAGE)}function or(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=Ki(n),s=Ki(r),a=$.relative(o,s);return a.length===0||!a.startsWith("..")&&!$.isAbsolute(a)?n:r}function Ki(e){try{return Ks.native(e)}catch{return $.resolve(e)}}function sr(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function $t(e,t,n){let i=t.length>0?$.join(e,t):e,r;try{r=await Lt.readdir(i,{withFileTypes:!0})}catch(o){if(sr(o,["ENOENT"]))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(Qs.has(o.name))continue;await $t(e,s,n);continue}o.isFile()&&n.push(ce(s))}}async function Pt(e){let t=[];for(let n of Xs)await $t(e,n,t);for(let n of Zs){let i=$.join(e,n);try{(await Lt.stat(i)).isFile()&&t.push(ce(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function ar(e){try{let{stdout:t}=await ua("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:aa,windowsHide:!0,timeout:ca}),n=t.split("\0").map(i=>ce(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function ga(e,t){let n=new Set,i=Vi(zt);i.length>0&&n.add(i);let r=Vi($.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((o,s)=>o.localeCompare(s))}function Yi(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function ya(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 Pt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await Pt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function D(e,t=ie){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function oe(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=D(e,Zi);return{values:n.values,truncated:n.truncated,total:e.length}}var wa={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},ka={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function ba(e){let t=e.missing_fields.map(n=>`${wa[n]} "${ka[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"):ri(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 va="validate_metadata_duplicate_issue_codes";function dr(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:ie,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:[`${va}:${e.length}`]}}function Ra(){return Object.fromEntries(Mt.map(e=>[e,[]]))}function Sa(e,t,n){let i=Ra();for(let r of e)for(let o of Mt)ir(r,o,t,n)&&i[o].push(r.id);return i}function xa(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let o=t[r];o.length>0&&i.push(`${ia[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=ra[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 Aa(e,t,n,i){for(let r of t.required_fields){let o=n[r];if(!o||o.length===0)continue;let s=oa[r],a=sa[r];if(!s||!a)continue;let c=D(o,i?o.length:ie);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 Ea(e,t,n,i){let r=new Map(e.map(h=>[h.id,h])),o=t.profile==="strict",s=Sa(e,n,o),a=vi(e),c=dr(a,i),l=xa(t,s,c.warnings),d=ur(t,s),u=mr(t,s,r),m=Ri(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:[...Mt],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]),Aa(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 Ca(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(Ve(m.status,t))),o=[],s=[];for(let m of r){let f=ea.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:ie,l=D(o.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=o.map(m=>ba(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=Ze()){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=bn(e,n?d=>Se(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:ie,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 jt(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 Bt(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=jt(n),r=[...new Set(i.flat())].sort((s,a)=>s.localeCompare(a)),o=i.map(s=>Bt(s,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:o}}function kr(e,t=Ze()){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=jt(t),i=[...new Set(n.flat())].sort((o,s)=>o.localeCompare(s)),r=n.map(o=>Bt(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 We(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Rr(e,t){let n=We(e).split("/").filter(Boolean),i=We(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function Ia(e,t){let n=We(t),i=We(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 Ta(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function Oa(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=ce(s.path);if(a.length===0||a===e)return;let c=Ia(e,a);c!==null&&Ta(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=Oa(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 Da(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 Fa(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&&!Se(s.status,r)}}function Pa(e,t,n,i){let r=q(e.blocked_by),o=q(e.blocked_reason),s=o?.toLowerCase(),a=Ve(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=>!Se(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=Da(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&&Se(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(Fa(c,u,r,o,n))),t){let m=Pa(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 La(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 Ji(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function Ma(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=Ji("validate_lifecycle_dependency_cycles",n,r),c=Ji("validate_hierarchy_parent_cycle",i,o);return[...s,...a?[a]:[],...c?[c]:[]]}function Ar(e){let t=ce(e);return t.length>la||t.split(/[\\/]/).some(n=>n.length>da)}async function $a(e,t){let n=$.isAbsolute(t)?t:$.resolve(e,t);if(Ar(n))return!1;try{let i=await Lt.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return sr(i,["ENOENT","ENOTDIR"])}}async function ja(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(Re(o.path)){n.remoteLinkedPaths.add(o.path.trim());continue}let a=ce(o.path);a.length!==0&&(n.linkedProjectPaths.add(a),await $a(t,o.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:s})))}return n}function Ba(e,t,n,i,r,o){let s=i==="tracked-all-strict",a=s&&!r,c=r||s,l=c?[]:ga(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>Yi(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!Yi(f,l)),m={};if(d.length>0){let f=oe(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);La(c);let l=wr(c.activeItems,a),d=br(e),u=Ma(c,t,n,i,l.cycle_count,d.cycle_count),m=s?Number.POSITIVE_INFINITY:ie,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 ja(e,t),a=new Map(e.map(b=>[b.id,b])),c=[...new Set(s.missingLinkedPaths)].sort((b,I)=>b.localeCompare(I)),l=await ya(t,i),d=Ba(l,n,t,i,r,o),u=d.candidateFiles.filter(b=>!s.linkedProjectPaths.has(b)),m=Sr(u,e),f=Ai(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=oe(v,o),S=oe(c,o),A=oe(u,o),Y=oe(m.map(b=>`${b.path}:${b.classification}:owner_candidate=${b.owner_candidate?.id??"unowned"}`),o),H=o?m:oe(xr(m),!1).values,E=oe(Ei(f),o),F=h.map(b=>({item_id:b.item_id,path:b.path,link_kind:b.link_kind,classification:b.classification})),W=Ii(F,b=>{let I=a.get(b);return I?{type:I.type,title:I.title,status:I.status}:void 0}),P=o?W:oe(Ti(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:Zi,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:Y.values,orphaned_path_classifications_truncated:Y.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:H}},warnings:y,staleLinkPruneRows:h}}async function Ua(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:o,chainMismatches:s,driftedItems:a}=await mi(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:ie,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 za(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=Gi(y.command,t);if(v.length!==0){o+=v.length;for(let x of v)s.add(x),i.has(x.toLowerCase())||a.push(za(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:ie,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 Ga(e,t){let n=sn(e.map(c=>({ref:c.id,version:on(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:ie,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:rn,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 Nt="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:Nt};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 Dt(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=>Dt(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=>Dt(a)!==null)){let a=Dt(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 $i(a.item_id,{remove:c,message:Nt},t):await Li(a.item_id,{remove:c,message:Nt},t),i.push(...s)}catch(l){r.push(...s.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Gu={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:Pt,collectTrackedGitFileCandidates:ar,detectLifecycleDependencyCycles:wr,detectLifecycleParentCycles:br,escapeRegExp:hr,extractItemIds:yr,findLifecycleDependencyCycleComponents:jt,isMetadataFieldMissing:ir,linkedArtifactPathExceedsFilesystemLimits:Ar,listFilesRecursive:$t,resolveDependencyCycleSeverity:tr,resolveParentCycleSeverity:nr,resolveFileScanMode:rr,resolveLifecycleDependencyCycleSamplePath:Bt,resolveRequestedChecks:lr,resolveValidateMetadataProfile:er,resolveWorkspaceRoot:or,sharedDirectoryPrefixLength:Rr,summarizeOrphanedPathRows:xr,summarizeDuplicateIssueCodes:dr,toMeaningfulString:q};async function qa(e,t,n,i){let r=await Qn(e,new Set(t.map(p=>p.id)),n,{schema:i.schema,extensionFieldNames:qt(J())}),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 Di(e);a.tracked_path_count>0&&o.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await Hn(e,Me(i));c.status==="drift"&&o.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await be(e),d=l===null?null:await Wn(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 kt(l,{includeLossless:!0,pmRoot:e}),{pendingDecisions:m,lossless:f}=Xn(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 ne(e,t,n){n&&cr(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Ha(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=Ea(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,ne(t,r,n)}if(e.requestedChecks.has("resolution")){let r=Ca(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,ne(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,ne(t,r,n),ne(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,ne(t,r,n)}return e.requestedChecks.has("command_references")&&ne(t,Ir(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&ne(t,await Ua(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&ne(t,Ga(e.items,i),n),e.requestedChecks.has("storage_integrity")&&ne(t,await qa(e.pmRoot,e.items,V(e.settings,J()).type_to_folder,e.settings),n),t}function Wa(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...hi(t.closeReasonBackfillRows)),i.push(...pi(t.resolutionBackfillRows)),i.push(..._i(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...gi(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...yi(t.staleLinkPruneRows)),i}async function Va(e,t,n,i,r,o){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let s=Wa(e,t,n),{applicable:a,gated:c}=ki(s,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Or(a,r,o);d.push(...m.applied.map(ve)),u.push(...m.failed.map(({fix:f,error:k})=>({...ve(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(ve),applied_fixes:d,gated_fixes:c.map(m=>({...ve(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function qu(e,t,n={}){en(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=wi(e.fixScope),o=B(process.cwd(),t.path);if(!await N(U(o)))throw new g(`Tracker is not initialized at ${o}. Run pm init first.`,_.NOT_FOUND);let s=await M(o),a=Qt(s.schema),c=V(s,J()),l=lr(e),d=[],u=await Hi({includeBody:l.has("history_drift"),pmRoot:o,settings:s,typeToFolder:c.type_to_folder,warnings:d});if(l.has("history_drift")){let F=await lt(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=er(typeof e.metadataProfile=="string"?e.metadataProfile:s.validation.metadata_profile),k=ha(f,m,s.validation.metadata_required_fields),p=fa(s),h=tr(e.dependencyCycleSeverity),y=nr(e.parentCycleSeverity),v=rr(e.scanMode),x=or(o),S=await Ha({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 Va(e,S,s,r,t,n):void 0,Y=[...new Set(S.warnings)].sort((F,W)=>F.localeCompare(W)),E={ok:!S.checks.some(F=>F.status==="error"),has_warnings:Y.length>0,checks:S.checks,warnings:Y,...A!==void 0?{fixes:A}:{},generated_at:X(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?E:{...ma(E),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Wc as a,mi as b,Oo as c,R as d,T as e,Pr as f,yc as g,wc as h,kc as i,En as j,bc as k,vc as l,Rc as m,Sc as n,xc as o,ct as p,Ac as q,Ec as r,at as s,Cc as t,Ic as u,Cn as v,Tc as w,zr as x,Tn as y,jc as z,lt as A,Wr as B,Vr as C,Bc as D,Kr as E,Qr as F,eo as G,Ne as H,Bn as I,ue as J,pt as K,oo as L,be as M,gt as N,Me as O,Hn as P,Wn as Q,ul as R,ml as S,ao as T,Di as U,po as V,vl as W,kt as X,Xn as Y,Rl as Z,Sl as _,Qn as $,Li as aa,Ll as ba,ii as ca,$i as da,Wd as ea,Vd as fa,Ls as ga,Ms as ha,Xd as ia,Zd as ja,Qd as ka,eu as la,js as ma,Bs as na,Us as oa,tu as pa,Ui as qa,Gs as ra,zi as sa,Ot as ta,qi as ua,qs as va,Hs as wa,Ws as xa,ma as ya,Gu as za,qu as Aa};
|
|
17
|
-
//# sourceMappingURL=chunk-UTEWXDEQ.js.map
|