@unbrained/pm-cli 2026.8.6 → 2026.8.7
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 +30 -0
- package/dist/cli/main.js +4 -2
- package/dist/cli/register-operations.js +11 -2
- package/dist/cli/stats-analytics-json.d.ts +9 -0
- package/dist/cli/stats-analytics-json.js +69 -0
- package/dist/cli-bundle/bundle-manifest.json +397 -397
- package/dist/cli-bundle/chunks/append-7BXBFDGD.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-TPKDJ5WL.js → chunk-2AXF3VSK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-R6RKEYYW.js → chunk-2XS43CCV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-T45OHXDW.js → chunk-3A6KWB72.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-3ISTDB42.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-SXECIECW.js → chunk-4MTI7XOV.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-MCS73BKB.js → chunk-6BX5UDCN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-A3XQ7VPU.js → chunk-6QPO7KLR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BP6EMEDP.js → chunk-7MXHZHSQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GU3TSEHD.js → chunk-7ZPMJW4U.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-343QETLI.js → chunk-AGYNSNCI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-B4H7FEFH.js +5 -0
- package/dist/cli-bundle/chunks/{chunk-CA3BURYF.js → chunk-B4KLBBMN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3ZJRFYY2.js → chunk-CALJHNBL.js} +12 -12
- package/dist/cli-bundle/chunks/{chunk-M357ZCOR.js → chunk-CFIGP5LY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SVV3DQES.js → chunk-CS6MRHG7.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DWOAOZHZ.js → chunk-CUGNQQKH.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-D4FPS43D.js +164 -0
- package/dist/cli-bundle/chunks/{chunk-L6LGKJX3.js → chunk-H5Y5YE6A.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5PBP2ZP3.js → chunk-H5Y6UV6E.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QJ7C3JIW.js → chunk-H7KGWPDF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D7I3TUGV.js → chunk-HFSD77TQ.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-AOBDLU4T.js → chunk-HX2GTA6L.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4AVFKHHC.js → chunk-J2IEKAVR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OXY3SJ3N.js → chunk-K44PYFXH.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-M4VEE3FK.js → chunk-K4KGEEBT.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-KFLK5TRH.js +21 -0
- package/dist/cli-bundle/chunks/{chunk-FDBRXV25.js → chunk-KL6IEBV2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JQ4NZ5EB.js → chunk-KWQZDZSS.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UVVXHGYS.js → chunk-KZ4X3DGU.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LD77HJMQ.js +13 -0
- package/dist/cli-bundle/chunks/{chunk-AYRUGRNS.js → chunk-ME2JJ4LA.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NFLJ3FHD.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-MDTH7SAE.js → chunk-NG6OXIBR.js} +8 -8
- package/dist/cli-bundle/chunks/{chunk-R6LSRGPS.js → chunk-NYIGHWQY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3KFVGGRE.js → chunk-NZ75GNSA.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q3VOP62W.js → chunk-PCJWJNC2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-C3YABSJK.js → chunk-PD3225AM.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JFZIS6JF.js → chunk-PDEGKG7P.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-PIE5HBNA.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-SD3YXU2U.js → chunk-PW2H7YJR.js} +20 -20
- package/dist/cli-bundle/chunks/{chunk-PECV7L5T.js → chunk-TPKN3S7S.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-F4NREH3G.js → chunk-TPXAXTCO.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-UFWUJO4V.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-WSI5KZQJ.js → chunk-UQLZQVFW.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-4OVGQW22.js → chunk-VT3Z5G7D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RUAU5OSH.js → chunk-WOD3WWUN.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DQGJ2RWT.js → chunk-WSJEIGJF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RAFUN7IX.js → chunk-WYNUU7ZW.js} +49 -46
- package/dist/cli-bundle/chunks/{chunk-5ZKQPA44.js → chunk-YGPNCCXZ.js} +2 -2
- package/dist/cli-bundle/chunks/close-CMY3BAUG.js +2 -0
- package/dist/cli-bundle/chunks/close-many-SA4XZCTK.js +2 -0
- package/dist/cli-bundle/chunks/comments-EZ556ZD3.js +2 -0
- package/dist/cli-bundle/chunks/copy-ZSGPA52X.js +2 -0
- package/dist/cli-bundle/chunks/{create-TG67IVFI.js → create-I5DVV4YG.js} +2 -2
- package/dist/cli-bundle/chunks/delete-RL3JACSW.js +2 -0
- package/dist/cli-bundle/chunks/{deps-AJUGP2OH.js → deps-S7UBCECS.js} +2 -2
- package/dist/cli-bundle/chunks/{docs-QOCLDRKJ.js → docs-ZZNVBBYO.js} +2 -2
- package/dist/cli-bundle/chunks/{files-3ST5TY64.js → files-27C337VT.js} +2 -2
- package/dist/cli-bundle/chunks/focus-5Z2SG7LU.js +2 -0
- package/dist/cli-bundle/chunks/{history-compact-7BJFML4S.js → history-compact-HJQK67CZ.js} +2 -2
- package/dist/cli-bundle/chunks/{history-redact-WJN3HYXR.js → history-redact-PWC6PDWA.js} +2 -2
- package/dist/cli-bundle/chunks/{history-repair-XDNZUB7F.js → history-repair-N3CY4WBF.js} +2 -2
- package/dist/cli-bundle/chunks/{learnings-SZMUPVNA.js → learnings-4FH23XDT.js} +2 -2
- package/dist/cli-bundle/chunks/{profile-KL53JIAC.js → profile-5Y5XXH5N.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-QH7ONPKU.js → register-list-query-FJZCJ67O.js} +2 -2
- package/dist/cli-bundle/chunks/{register-mutation-OCRQNZK4.js → register-mutation-YGYPW3BL.js} +3 -3
- package/dist/cli-bundle/chunks/register-operations-WMDSUMQF.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-QWBQ6HBS.js → register-setup-DL7FFABC.js} +2 -2
- package/dist/cli-bundle/chunks/restore-6KYBV5BY.js +2 -0
- package/dist/cli-bundle/chunks/{schema-QJ27OTRV.js → schema-EQGKBYXJ.js} +2 -2
- package/dist/cli-bundle/chunks/update-QVTYOD6I.js +2 -0
- package/dist/cli-bundle/chunks/update-many-DJSBU525.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-MBBMTDD3.js → chunk-2ECLECMK.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-CL3NB7VW.js → chunk-3K4XV2BF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-ME4XVOBJ.js → chunk-4EX25PXM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4VJQTS3P.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-73JUDYXT.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-GSW2Y7VZ.js → chunk-CIXVQPB7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-7YTZ7A4E.js → chunk-DLTS3IHM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YHDCGUIW.js → chunk-DQ6FKGL3.js} +10 -10
- package/dist/cli-bundle/focused-chunks/{chunk-YLPZHWX7.js → chunk-HNL6IFGS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-JLG2C4EQ.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-6KDHXURF.js → chunk-MHMTKV5V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GEYU23YS.js → chunk-MOTJFQ3F.js} +22 -22
- package/dist/cli-bundle/focused-chunks/{chunk-EYO4F74Z.js → chunk-NBJKQP4S.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XNVXIQ4B.js → chunk-QHRTT7WT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-27DK4A5O.js → chunk-R2LEMEV5.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-4JC3AOGS.js → chunk-RPNYG5MO.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-EAXXF2HW.js → chunk-RW5IYD4J.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-TQMFQYXR.js → chunk-TIKDBG4D.js} +16 -16
- package/dist/cli-bundle/focused-chunks/{chunk-N7QN3NE6.js → chunk-VZFU2R4M.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GIERI4YU.js → chunk-YZEZAPJK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-ZJIMJHDB.js +2 -0
- package/dist/cli-bundle/main.js +2 -2
- 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 +29 -28
- 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 +1 -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 +1 -1
- package/dist/core/extensions/reserved-host-flags.js +3 -2
- package/dist/core/history/workspace-history.d.ts +22 -2
- package/dist/core/history/workspace-history.js +60 -36
- package/dist/core/output/output.d.ts +2 -0
- package/dist/core/output/output.js +3 -2
- package/dist/core/shared/command-types.d.ts +2 -0
- package/dist/core/shared/command-types.js +2 -2
- package/dist/mcp/tool-definitions.js +6 -2
- package/dist/sdk/author-attribution.js +23 -7
- package/dist/sdk/cli-bootstrap.d.ts +2 -0
- package/dist/sdk/cli-bootstrap.js +7 -2
- package/dist/sdk/cli-contracts/completeness.js +51 -4
- package/dist/sdk/cli-contracts/flag-contracts.js +3 -2
- package/dist/sdk/cli-contracts/registration-helpers.js +3 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +14 -8
- package/dist/sdk/cli-contracts/tool-parameter-tables.js +116 -10
- package/dist/sdk/cli-contracts/tool-schema.js +18 -2
- package/dist/sdk/cli-program.js +3 -2
- package/dist/sdk/completion.js +5 -2
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +2 -2
- package/dist/sdk/core.d.ts +3 -1
- package/dist/sdk/core.js +4 -3
- package/dist/sdk/extension.js +9 -11
- package/dist/sdk/generated-error-code-catalog.js +112 -2
- package/dist/sdk/history-analytics.d.ts +141 -0
- package/dist/sdk/history-analytics.js +283 -0
- package/dist/sdk/improvement-ledger-validation.d.ts +3 -0
- package/dist/sdk/improvement-ledger-validation.js +63 -0
- package/dist/sdk/improvement-ledger.d.ts +139 -0
- package/dist/sdk/improvement-ledger.js +261 -0
- package/dist/sdk/index.d.ts +6 -2
- package/dist/sdk/index.js +8 -4
- package/dist/sdk/lifecycle/plan.js +6 -3
- package/dist/sdk/merge/install.js +10 -2
- package/dist/sdk/read-output-budget.js +24 -22
- package/dist/sdk/read-output-contracts.d.ts +10 -2
- package/dist/sdk/read-output-contracts.js +124 -65
- package/dist/sdk/read-output-rows.d.ts +29 -0
- package/dist/sdk/read-output-rows.js +100 -0
- package/dist/sdk/read-output-session.d.ts +69 -0
- package/dist/sdk/read-output-session.js +200 -0
- package/dist/sdk/runtime-input.d.ts +2 -0
- package/dist/sdk/runtime-input.js +14 -2
- package/dist/sdk/runtime-primitives.d.ts +1 -1
- package/dist/sdk/runtime-primitives.js +3 -3
- package/dist/sdk/runtime-stats-options.d.ts +9 -0
- package/dist/sdk/runtime-stats-options.js +38 -0
- package/dist/sdk/runtime.d.ts +1 -0
- package/dist/sdk/runtime.js +6 -27
- package/dist/sdk/stats.d.ts +40 -0
- package/dist/sdk/stats.js +112 -29
- package/docs/IMPROVEMENT_ANALYTICS.md +103 -0
- package/docs/OUTPUT_PROJECTION_CONTRACTS.md +5 -5
- package/docs/README.md +1 -0
- package/docs/READ_OUTPUT_CONTRACTS.md +60 -1
- package/marketplace.json +2 -2
- package/package.json +3 -3
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- 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/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- 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/sdk/public-surface.json +374 -821
- package/dist/cli-bundle/chunks/append-XAJ5Z4XS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-AJE3AHPD.js +0 -8
- package/dist/cli-bundle/chunks/chunk-E7BFPLUZ.js +0 -5
- package/dist/cli-bundle/chunks/chunk-HS7OVAUN.js +0 -164
- package/dist/cli-bundle/chunks/chunk-SV3YQ4RY.js +0 -2
- package/dist/cli-bundle/chunks/chunk-V663653R.js +0 -20
- package/dist/cli-bundle/chunks/chunk-XPOQQJTX.js +0 -13
- package/dist/cli-bundle/chunks/chunk-YCCDXBNU.js +0 -2
- package/dist/cli-bundle/chunks/chunk-ZFBWCKYF.js +0 -2
- package/dist/cli-bundle/chunks/close-DI66JMSB.js +0 -2
- package/dist/cli-bundle/chunks/close-many-VFKT6U3O.js +0 -2
- package/dist/cli-bundle/chunks/comments-E73HIEZJ.js +0 -2
- package/dist/cli-bundle/chunks/copy-WBYVLCPC.js +0 -2
- package/dist/cli-bundle/chunks/delete-6XKUVVQN.js +0 -2
- package/dist/cli-bundle/chunks/focus-R2AWS63Y.js +0 -2
- package/dist/cli-bundle/chunks/register-operations-HIBJXRGB.js +0 -2
- package/dist/cli-bundle/chunks/restore-FXA5QPM7.js +0 -2
- package/dist/cli-bundle/chunks/update-7GBO4SXG.js +0 -2
- package/dist/cli-bundle/chunks/update-many-VF6ZKQUO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-74CWP3A4.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-7AZDTGPA.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-LKQXXO62.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-QL5H3AQH.js +0 -2
|
@@ -1,14 +1,14 @@
|
|
|
1
|
-
import{f as
|
|
2
|
-
`)}async function
|
|
1
|
+
import{f as Xt}from"./chunk-MHMTKV5V.js";import{h as de,i as Vt,j as ue,k as Yt,n as Jt}from"./chunk-4EX25PXM.js";import{Ca as ie,Da as Ut,Fa as zt,Ia as Bt,Ja as Gt,K as ne,L as Y,La as $,P as Ft,Ua as Wt,V as Lt,W as $t,Z as Dt,Za as qt,_ as Mt,ab as ve,ba as Be,bb as be,cb as Ht,da as Ot,eb as Kt,hb as Ee,k as q,na as Nt,q as Pt,za as jt}from"./chunk-MOTJFQ3F.js";import{D as z,I as Rt,J as B,K as le,Ka as At,M as O,P as xt,T as P,aa as je,h as bt,o as Et,p as L,q as St,r as ce,u as Ne,v as It}from"./chunk-RW5IYD4J.js";import{i as Tt}from"./chunk-R2LEMEV5.js";import{N as kt,U as vt,V as ke,Y as g,Z as y,aa as Ue,ba as Ct,ca as ze,t as Oe}from"./chunk-ZJIMJHDB.js";import{readFile as Se,realpath as He,writeFile as Ki}from"node:fs/promises";import{execFile as Vi}from"node:child_process";import x from"node:path";import{promisify as Yi}from"node:util";import{readFile as Gi,writeFile as Wi}from"node:fs/promises";import me 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 Qt="# pm-cli:runtime-cache:start",Ge="# pm-cli:runtime-cache:end",en=".agents/pm",We=["runtime/","search/","locks/","transactions/","checkpoints/"],qi=["search/eval-queries.json"];async function Zt(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 y("The workspace .gitignore is not writable.",g.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 tn(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function qe(e){let t=e.replaceAll("\\","/");return me.isAbsolute(e)||t===".."||t.startsWith("../")}function Hi(e=en){let t=tn(e);return[Qt,...We.map(n=>n==="search/"?`${t}/${n}*`:`${t}/${n}`),...qi.map(n=>`!${t}/${n}`),Ge].join(`
|
|
2
|
+
`)}async function $o(e,t={}){let n=me.join(e,".gitignore"),i=en;if(t.pmRoot!==void 0){let d=tn(me.relative(me.resolve(e),me.resolve(t.pmRoot)));if(qe(d))return{path:n,changed:!1};d.length>0&&(i=d)}let r="";try{r=await Zt(()=>Gi(n,"utf8"))}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let s=r.indexOf(Qt),o=r.indexOf(Ge),c=(s>=0&&o>=s?`${r.slice(0,s)}${r.slice(o+Ge.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
|
|
3
3
|
|
|
4
|
-
`:""}${
|
|
5
|
-
`;return l===r?{path:n,changed:!1}:(await
|
|
4
|
+
`:""}${Hi(i)}
|
|
5
|
+
`;return l===r?{path:n,changed:!1}:(await Zt(()=>Wi(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]="a250384a-0279-5d01-ade4-f64be3119ed9")}catch{}})();var Ke=Yi(Vi),Q="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",Ji="merge-fence";function nn(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function sn(){let e=It(import.meta.url,["../../.."]);return`${nn(process.execPath)} ${nn(x.join(e,"dist","cli.js"))}`}var on=[{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}];async function pe(e){try{let{stdout:t}=await Ke("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await He(t.trim())}catch{return null}}async function an(e){let t=await pe(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",g.USAGE);return t}function Ve(e,t){return x.relative(e,t).replaceAll("\\","/")}function G(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function rn(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 Xi(e,t){let n=rn(e,0);if(n===null||e[n.nextOffset]!==" ")return!1;let i=rn(e,n.nextOffset+1);if(i===null||e.slice(i.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(x.basename(n.value))||x.basename(i.value)!=="cli.js"||x.basename(x.dirname(i.value))!=="dist"||!await L(n.value)||!await L(i.value))return!1;try{let r=x.dirname(x.dirname(i.value)),s=JSON.parse(await Se(x.join(r,"package.json"),"utf8")),o=typeof s.bin=="object"&&s.bin!==null&&"pm"in s.bin?s.bin.pm:void 0;return s.name==="@unbrained/pm-cli"&&(s.bin==="dist/cli.js"||o==="dist/cli.js")}catch{return!1}}function Ye(e,t){let n=e.length>0?`${e}/`:"",i=[`${G(`${n}**/*.toon`)} merge=pm-item-toon`,`${G(`${n}**/*.md`)} merge=pm-item-markdown`];for(let r of t)i.push(`${G(`${n}${r}/*.toon`)} merge=pm-item-toon`),i.push(`${G(`${n}${r}/*.md`)} merge=pm-item-markdown`);return i.push(`${G(`${n}**/*.jsonl`)} merge=pm-relationship`),i.push(`${G(`${n}history/*.jsonl`)} merge=pm-history`),i.push(`${G(`${n}settings.json`)} merge=pm-json`),i.push(`${G(`${n}**/*.json`)} merge=pm-json`),i.push(`${G(`${n}extensions/**`)} -merge`),i.push(`${G(`${n}extensions/.managed-extensions.json`)} merge=pm-json`),i}async function cn(e,t,n){let i=x.join(e,".gitattributes"),r="";try{r=await Se(i,"utf8")}catch(u){if(!(u instanceof Error&&"code"in u&&u.code==="ENOENT"))throw u}let s=[Q,...t,fe].join(`
|
|
6
6
|
`),o=r.indexOf(Q),a=r.indexOf(fe),l=(o>=0&&a>o?`${r.slice(0,o)}${r.slice(a+fe.length)}`:r.replace(Q,"").replace(fe,"")).trimEnd(),d=`${l.length>0?`${l}
|
|
7
7
|
|
|
8
8
|
`:""}${s}
|
|
9
|
-
`;return d===r?{path:i,changed:!1}:(n||await
|
|
10
|
-
`).map(p=>p.trim()).filter(p=>p.length>0):[],d=Ve(Ke(i,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),w=l.filter(p=>!m.has(p));return{status:f.length>0||w.length>0?"drift":"ok",path:o,missing_patterns:f,stale_patterns:w,schema_scope:"project"}}async function ln(e){let t=rn(),n=[],i=[];for(let r of sn){let s=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${o}`;try{let{stdout:c}=await He("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Ji(l,o)&&i.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function Jo(e){let t;try{t=await on(x.resolve(e))}catch{return{status:"no_git"}}let n=Ke(t,x.resolve(e)),i=await $(e),r=ne(void 0,i.author_default),s=await Pt(e,Yi,i.locks.ttl_seconds,r,!1,Bt(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=x.join(t,".gitattributes"),a;try{a=await Ee(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:o};throw u}if(!a.includes(Q))return{status:"not_installed",path:o};let c=await $(e),l=Se(c),d=await an(t,Ve(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Xo(e,t){let n=t.path?.trim(),i=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),s=n===void 0&&i!==void 0&&i.length>0&&r!==void 0&&r.length>0,o=n!==void 0?B(process.cwd(),n):s?x.resolve(r):B(process.cwd());if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let a=await on(n!==void 0?o:s?x.resolve(i):process.cwd());return Xi({pmRoot:o,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Xi(e){let t=x.resolve(e.pmRoot),n=x.resolve(e.workspaceRoot),i=e.dryRun===!0,r,s;try{[r,s]=await Promise.all([qe(t),qe(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.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 o=Ke(s,r);if(We(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await $(r),c=Se(a),l=Ve(o,c),d=[],u=rn();for(let f of sn)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 He("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.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 an(s,l,i);return{ok:!0,dry_run:i,workspace_root:s,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 validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"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:V()}}import Ie from"node:fs/promises";import Re 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]="364a8999-58e2-58c9-bfa6-acd8c42ec471")}catch{}})();var Zi="2026-07-15T06:22:12.276Z",Qi=Date.parse(Zi),er=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],dn=e=>typeof e=="string"?e:"",un=e=>{let t=e??{},n=dn(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(dn(t.ts))>=Qi);return er[i][r]};function mn(e,t,n=20,i=new Set,r=!1){let s=[],o=[],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 w;try{w=JSON.parse(f)}catch{continue}l+=1;let p=un(w);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.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:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var ia=(e,t,n=20,i=new Set)=>mn(e,t,n,i);function tr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Ye=async(e,t=20,n=!1)=>{let i=Re.join(e,"history"),r;try{r=(await Ie.readdir(i)).filter(h=>h.endsWith(".jsonl")).sort((h,v)=>h.localeCompare(v))}catch{r=[]}let s=new Set,o=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,w="_workspace.jsonl",p=new Set;if(r.includes(w))try{p=tr(await Ie.readFile(Re.join(i,w),"utf8"))}catch{p=new Set}for(let h of r){let v;try{v=await Ie.readFile(Re.join(i,h),"utf8")}catch{continue}let E=h.slice(0,-6),S=mn(E,v,t-o.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&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let _=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:[...s].sort((h,v)=>h.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:a}:{}}};async function ra(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),s=t.events??[];if(+(t.all_actionable===!0)+ +(s.length>0)>1)throw new TypeError("Author acknowledgment accepts either explicit events or all_actionable, not both.");let a=t.all_actionable===!0?(await Ye(e,0,!0)).actionable_events:s;if([a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1))throw new TypeError("Author acknowledgment requires events, reviewer, attributed_author, and reason.");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){if([/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1))throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`);let w;try{let _=(await Ie.readFile(Re.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];w=JSON.parse(_??"")}catch{throw new TypeError(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`)}if(un(w)!=="actionable_unknown")throw new TypeError(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`)}let d=await $(e),u=await Ut({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{execFile as nr}from"node:child_process";import{randomUUID as ir}from"node:crypto";import{readdir as rr,readFile as sr}from"node:fs/promises";import _e from"node:path";import{promisify as or}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var ar=or(nr);async function Je(e){try{let{stdout:t}=await ar("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}}function fn(e){return`${e}.json`}function pa(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,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:Ue(je(t.retained)),discarded_hash:Ue(je(t.discarded))}))}}async function _a(e){let t=await Je(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=_e.basename(i,_e.extname(i)),s={version:1,id:ir(),item_path:i.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:V()};return await bt(t),await ce(_e.join(t,fn(s.id)),`${JSON.stringify(s,null,2)}
|
|
11
|
-
`),s}async function
|
|
12
|
-
`)}async function ga(e){let t=await Xe(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:V()}}import re from"node:fs/promises";import se 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 cr(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await re.readdir(se.join(e,r))}catch{return}for(let o of s)for(let a of It)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function lr(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=ze(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.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{s.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)&&s.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&&(s.repairReconciliations+=1))}function Ze(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 dr(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await re.readdir(se.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await re.readFile(se.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Ze("history stream",o)});continue}lr({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function pn(e){let t=ze(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 ur(e){let t=[],n=0,i=null;try{i=await Et(O(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Ze("configuration file",s)})}if(i!==null){n+=1;let s=pn(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await re.readdir(se.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await re.readFile(se.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Ze("configuration file",c)});continue}let a=pn(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function _n(e,t,n,i={}){let r=await cr(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,w)=>f.localeCompare(w))})).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=se.join(e,u.relativePath);return Mt(await re.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 dr(e,s),d=await ur(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.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 ft from"node:fs/promises";import{realpathSync as Cs}from"node:fs";import{execFile as As}from"node:child_process";import F from"node:path";import{promisify as Ts}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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var mr=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:"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 validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{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_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{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 fr(e){if(typeof e!="string")return;let t=e.trim();for(let n of mr)if(t===n.code||t.startsWith(`${n.code}:`))return n}function pr(e){let t={};for(let n of e){let i=fr(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function hn(e){return Object.values(pr(e))}import oe from"node:fs/promises";import{createHash as _r}from"node:crypto";import yn 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var wn=3,hr="history-drift-cache.json";function kn(e){return yn.join(e,"runtime",hr)}async function gr(e){try{let t=await oe.readFile(kn(e),"utf8"),n=JSON.parse(t);return n.version!==wn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function vn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function yr(e,t,n,i,r){let s=jt(e),o;try{o=await oe.stat(s)}catch(l){return vn(l,"ENOENT")||r.unreadableStreams.push(ie),!1}let a=r.missingStreams.length,c=await En({itemId:ie,historyPath:s,stat:o,cached:t[ie],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(ie),n[ie]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function bn(e){return _r("sha256").update(e).digest("hex")}async function wr(e){let t=await oe.readFile(e,"utf8");return bn(t)}async function kr(e){let t=await oe.readFile(e,"utf8"),n=bn(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let o=s.trim();if(o.length===0)continue;let a=JSON.parse(o);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:Nt(i).ok,contentHash:n}:null}function vr(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function gn(e,t,n){try{let i=await kr(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function En(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(vr(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await gn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await wr(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},cacheDirty:!1}:{verification:await gn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function Sn(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await gr(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=Rt(e,u.id),f;try{f=await oe.stat(m)}catch(E){vn(E,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let w=s[u.id],p=await En({itemId:u.id,historyPath:m,stat:f,cached:w,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),o[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};let{body:_,...h}=u;Ot({metadata:h,body:_})!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await yr(e,s,o,c,i);if(a||=l,a||Object.keys(s).length!==Object.keys(o).length){let u=kn(e);try{await oe.mkdir(yn.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:wn,entries:o}))}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 br=["metadata","resolution"],Qe=["metadata","resolution","estimates","lifecycle"],Er="completed";function et(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function In(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function Rn(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=In(n.close_reason)??Er;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${et(i)}`,gate:"resolution"})}return t}function xn(e){let t=[];for(let n of e){let i=In(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 ${et(i)}`,gate:"metadata"})}return t}function Cn(e,t){return e.map(n=>{let i=zt(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 An(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 Tn(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 ${et(n.path)}`})}return t}function Pn(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 y(`--fix-scope values must not be empty. Supported values: ${Qe.join(", ")}.`,g.USAGE);return new Set(br)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(Qe.includes(r)){n.add(r);continue}throw new y(`Unknown --fix-scope value "${i}". Supported values: ${Qe.join(", ")}.`,g.USAGE)}return n}function Fn(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 he(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 Sr=/^([A-Z][A-Z0-9]*-\d+)\b/;function Ir(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Sr.exec(t);return n?n[1]:null}function Ln(e){return typeof e=="string"&&e.trim().length>0}function $n(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||Ln(i.duplicate_of))continue;let r=Ir(i.title);if(r===null)continue;let s=t.get(r);s||(s=[],t.set(r,s)),s.some(o=>o.id===i.id)||s.push({id:i.id,title:i.title,parent:Ln(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let s=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].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 Dn(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,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}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 Mn=3;function On(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function Nn(e,t,n=Mn){let i=Number.isFinite(n)&&n>=1?Math.floor(n):Mn,r=new Map;for(let s of t){let o=On(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{let o=(r.get(On(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function jn(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 Rr=/^[a-z][a-z0-9+.-]+:\/\//i;function ge(e){return Rr.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 xr(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function Un(e){return`${e.item_id} ${e.link_kind}`}function zn(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=xr(r.classification,i.classification),r.owners.set(Un(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[Un(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function Cr(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Bn(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="${Cr(i.title)}"`);return t}import{execFile as Ar}from"node:child_process";import{realpath as Tr}from"node:fs/promises";import Gn from"node:path";import{promisify as Pr}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 Fr=Pr(Ar),Lr=32*1024*1024,$r=1e4,Dr=["search/eval-queries.json"];function tt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Mr(e){return`'${e.replaceAll("'","'\\''")}'`}async function Or(e,t=Tr){return t(e).catch(()=>Gn.resolve(e))}async function Wn(e){let t=await pe(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 Or(e),i=tt(Gn.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=Ge.map(s=>`${i}/${tt(s)}`);try{let{stdout:s}=await Fr("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:Lr,windowsHide:!0,timeout:$r}),o=new Set(Dr.map(l=>`${i}/${l}`)),a=[...new Set(s.split("\0").filter(l=>l.length>0&&!o.has(tt(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=>Mr(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import Nr from"node:fs/promises";import D from"node:path";import jr 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 Ur=["path","scope","note"],zr=["pattern","glob","path","scope","note"],Br=["path"],Gr=["from","to"],Wr=new Set(["note","scope"]);function Hn(e){let t=e??"project";if(!Me.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Me.join(", ")} (default: project).`,g.USAGE);return t}function Kn(e){return e.startsWith("```")||e.includes(`
|
|
13
|
-
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Kt(e)}function qr(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Kn(n)||!n.includes(",")?[t]:Yt(n)})}function Hr(e,t){return e?qr(e).map(n=>{let i=n.trim(),r=Kn(i)?de(n,"--add"):{path:i};if(ue(r,"--add",Ur),!r.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return{path:r.path,scope:Hn(r.scope),note:r.note?.trim()||void 0}}):[]}function Kr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--add-glob");ue(i,"--add-glob",zr);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:r,scope:Hn(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Vr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--remove"),r=Object.keys(i).filter(s=>Wr.has(s.toLowerCase()));if(r.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(ue(i,"--remove",Br),!i.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return i.path}return n}):[]}function Yr(e){return e?e.map(t=>{let n=de(t,"--migrate");ue(n,"--migrate",Gr);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:i,to:r}}):[]}function nt(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 q(e){return e.split(D.sep).join("/")}function it(e,t,n=process.cwd()){let i=e.trim();if(ge(i))return i;if(D.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return q(i.replaceAll("\\",D.sep));let r=D.relative(t,n);return r.startsWith(`..${D.sep}`)||r===".."||D.isAbsolute(r)?q(D.normalize(i)):q(D.relative(t,D.resolve(n,i)))}async function Jr(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=D.isAbsolute(r.pattern),o=await jr(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>it(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 Xr(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Zr(e){return`${e.path}::${e.scope}`}function rt(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function st(e){return[...new Map(e.map(t=>[Zr(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function Qr(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ge(a)){o.push(a.trim());continue}let c=D.isAbsolute(a)?a:D.resolve(t,a);try{(await Nr.stat(c)).isFile()?i.push(a):s.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function es(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=nt(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=nt(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>nt(o,i)),count:r}}function ts(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=st(e);return i?r:rt(r)}async function qn(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 Qr(t,e.workspaceRoot):void 0}}async function xe(e,t,n,i){let{metadataKey:r}=i,s=Vt(),o=B(process.cwd(),n.path),a=le(o),c=process.cwd();if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let l=await $(o),d=z(l,W()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),w=await s.resolveList(t.migrate,"--migrate"),p=Hr(u,i.bareNoun).map(T=>({...T,path:it(T.path,a,c)})),_=Kr(m),h=await Jr(_,a,c),v=Xr([...p,...h],t.note,p.length>0||_.length>0),E=Vr(f).map(T=>it(T,a,c)),S=Yr(w);if(!(v.length>0||E.length>0||S.length>0)){let T=await ke(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!T)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await ve(T,{schema:l.schema})).document.metadata[r]??[];return qn({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:a})}let G=ne(t.author,l.author_default),j=await be({pmRoot:o,settings:l,id:e,op:i.op,author:G,message:t.message,force:t.force,skipNoop:!0,mutate(T){let k=T.metadata,R=k[r]??[],te=[...R],Z=es(te,v,E,S),De=ts(te,Z.adds,Z.removes,i.supportsAppendStable&&t.appendStable===!0);De.length>0?k[r]=De:delete k[r];let yt=!xt(R,De);return{changedFields:yt?[r]:[],warnings:yt&&Z.count>0?[`path_migrations_applied:${Z.count}`]:[]}}}),b=j.item[r]??[],A=j.warnings.find(T=>T.startsWith("path_migrations_applied:")),U=A?Number(A.slice(24)):0;return qn({id:j.item.id,artifacts:b,changed:j.changedFields.includes(r),migrationsApplied:U,options:t,workspaceRoot:a})}function Ce(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 Vn(e,t,n){let i=await xe(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ce(i,"docs")}import Yn from"node:fs/promises";import M 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]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var ns=32768;function ot(e){return q(M.normalize(e))}async function Ae(e){try{return await Yn.realpath(e)}catch{return M.resolve(e)}}function ae(e,t){let n=M.isAbsolute(e.path)?M.resolve(e.path):M.resolve(t,e.path);return`${ot(n)}::${e.scope}`}function Te(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)=>Te(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Te(r,t?`${t}.${i}`:i,n)}function is(e){let t=[];return Te(e.metadata,"metadata",t),Te(e.body,"body",t),t}function rs(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 ss(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 s=new Set,o=r.value.slice(0,ns);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=rs(l[0]);!d||s.has(d)||(s.add(d),t.push({field:r.field,value:d}))}}}return t}async function os(e,t,n=t){let i=M.isAbsolute(e)?M.resolve(e):M.resolve(n,e),r;try{r=await Yn.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Ae(t),Ae(i)]);if(Oe(s,o)){let a=M.relative(s,o);return!a||a.startsWith("..")||M.isAbsolute(a)?void 0:{path:ot(a),scope:"project"}}return{path:ot(i),scope:"global"}}async function as(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>ae(c,t))),r=new Map,s=ss(is(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await os(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=ae(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 Jn(e,t,n){let i=await xe(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ce(i,"files")}async function cs(e,t){let n=await Ae(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!M.isAbsolute(o))return q(o);let a=await Ae(o);return Oe(n,a)?q(M.relative(n,a)):q(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return r}function ls(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new y(`Files lookup ${i} must be a non-negative integer.`,g.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 Xn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function ds(e){if([e.strictRead,e.noTruncate,Tt()].includes(!0))return null;let t=await Wt(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Gt({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function us(e){let t=[],i=(await qt(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(o=>({item:o,files:(o.files??[]).filter(a=>e.paths.includes(q(a.path))&&(e.scope===void 0||a.scope===e.scope)).sort((a,c)=>{let l=a.path.localeCompare(c.path);return l===0?a.scope.localeCompare(c.scope):l})})).filter(o=>o.files.length>0).sort((o,a)=>{let c=o.item.priority-a.item.priority;if(c!==0)return c;let l=a.item.updated_at.localeCompare(o.item.updated_at);return l===0?o.item.id.localeCompare(a.item.id):l}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new y(`Files lookup could not read every item: ${r.join("; ")}`,g.GENERIC_FAILURE);let s=i.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<i.length,truncated:e.offset+s.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(o=>({item:Xn(o.item),files:o.files}))}}async function Lc(e,t){let n=B(process.cwd(),t.path),i=le(n);if(!await L(O(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let r=await cs(e.paths,i),s=await $(n),o=z(s,W()),{offset:a,limit:c}=ls(e),l=await ds({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!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:Xn(d.item),files:d.files}))}:us({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0})}async function $c(e,t,n){let i=B(process.cwd(),n.path),r=le(i);if(!await L(O(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let s=await $(i),o=z(s,W()),a=await ke(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await ve(a,{schema:s.schema}),l=await as(c.document,r,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let w=ne(t.author,s.author_default),p=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],h=new Set,v=await be({pmRoot:i,settings:s,id:e,op:"files_discover",author:w,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let A=[...b.metadata.files??[]],U=new Set(A.map(R=>ae(R,r)));_=[],h.clear();for(let[R,te]of p.entries()){let Z=ae(te,r);U.has(Z)||(A.push(te),U.add(Z),_.push(te),h.add(R))}let T=st(A),k=t.appendStable?T:rt(T);return k.length>0?b.metadata.files=k:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==p.length?[`files_discover_skipped_existing:${p.length-_.length}`]:[]}}}),E=v.item.files??[],S=new Set(_.map(b=>ae(b,r))),I=E.filter(b=>S.has(ae(b,r))),G=d.filter((b,A)=>!h.has(A)),j=[...u,...G];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:I.length,skipped_existing_count:j.length,candidates:l,added:I,skipped_existing:j}}(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]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var ms=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),at=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"]),_s=new Set(["-c","--call"]),hs=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),gs=new Set(["-C","--prefix","--userconfig","--cache"]),Mc=new Set(["--cwd"]),Oc=new Set(["--cwd"]),ys=new Set(["exec","x"]),Nc=new Set(["run","run-script"]),jc=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function ws(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function ks(e){let t=vs(e.split(" ").filter(s=>s.length>0));if(t.length===0)return null;let[n,...i]=t;if(Zn(n)||Qn(n))return i;if(n==="node"&&i[0]&&Qn(i[0]))return i.slice(1);let r=n==="npx"||n==="bunx"?ct(i):n==="pnpm"?Ss(i):n==="npm"?Is(i):null;return r&&(Zn(r.command)||Es(r.command))?r.args:null}var ei=(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 s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of ws(s)){let c=ks(a),l=c?Rs(c):null,d=l&&ms.has(l.subcommand)?xs(l.remaining,fs[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(d)}return[...o].sort((a,c)=>a.localeCompare(c))};function vs(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 Uc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return n}}function Zn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function bs(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 Es(e){let t=bs(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function Qn(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function ct(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 s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(_s.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 ti(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 Ss(e){let t=ti(e,hs);return t?.subcommand!=="dlx"?null:ct(t.args)}function Is(e){let t=ti(e,gs);return!t||!ys.has(t.subcommand)?null:ct(t.args)}function Rs(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(at.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function xs(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("=")&&(at.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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Ps=["src","tests","docs"],Fs=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],Ls=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),$s=["resolution","expected_result","actual_result"],Ds=["default","tracked-all","tracked-all-strict"],ni=["core","strict","custom"],Fe=["off","warn","error"];var dt=["author","acceptance_criteria","estimated_minutes","close_reason"],ai=[...dt,"reviewer","risk","confidence","sprint","release"],pt=Array.from(new Set(ai)),Ms={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"},Os={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"},Ns={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"},js={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"},Us={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"},zs=32*1024*1024,Bs=1e4,ci=40,K=5,Gs=4096,Ws=255,qs=Ts(As);function li(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?li(i):i);return t}function Hs(e){return{...e,checks:e.checks.map(t=>({...t,details:li(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 ee(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ii(e){return ee(e).replace(/\/+$/,"")}function N(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function $e(e,t){return Dt(e,t)??e}function ye(e,t){return t.terminal_statuses.has($e(e,t))}function J(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Pe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function Ks(e){let t=J(kt),n={blocked_reason:J(we.blocked_reason),resolution:J(we.resolution),actual_result:J(we.actual_result)},i=J(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:J(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:J(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:J(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:Pe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Pe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Pe(r.resolution,n.resolution)?"default":"settings",actual_result:Pe(r.actual_result,n.actual_result)?"default":"settings"}}}function di(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ni.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${ni.join(", ")}.`,g.USAGE)}function ui(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,g.USAGE)}function mi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Fe.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Fe.join(", ")}.`,g.USAGE)}function Vs(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Ms[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function Ys(e,t,n){let i=Vs(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...dt],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...ai],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:[...dt],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Js=new Set(["acceptance_criteria","estimated_minutes"]);function fi(e,t,n,i){return!i&&Js.has(t)&&ye(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?$e(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function pi(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 y(`Unknown --scan-mode value "${e}". Supported values: ${Ds.join(", ")}.`,g.USAGE)}function _i(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return F.resolve(t);let n=F.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return F.dirname(F.dirname(n));let r=F.resolve(process.cwd()),s=ri(n),o=ri(r),a=F.relative(s,o);return a.length===0||!a.startsWith("..")&&!F.isAbsolute(a)?n:r}function ri(e){try{return Cs.native(e)}catch{return F.resolve(e)}}function hi(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?F.join(e,t):e,r;try{r=await ft.readdir(i,{withFileTypes:!0})}catch(s){if(hi(s,["ENOENT"]))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?F.join(t,s.name):s.name;if(s.isDirectory()){if(Ls.has(s.name))continue;await _t(e,o,n);continue}s.isFile()&&n.push(ee(o))}}async function ut(e){let t=[];for(let n of Ps)await _t(e,n,t);for(let n of Fs){let i=F.join(e,n);try{(await ft.stat(i)).isFile()&&t.push(ee(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function gi(e){try{let{stdout:t}=await qs("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:zs,windowsHide:!0,timeout:Bs}),n=t.split("\0").map(i=>ee(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function Xs(e,t){let n=new Set,i=ii(wt);i.length>0&&n.add(i);let r=ii(F.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function si(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Zs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await gi(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await ut(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await ut(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function C(e,t=K){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function X(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=C(e,ci);return{values:n.values,truncated:n.truncated,total:e.length}}var Qs={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},eo={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function to(e){let t=e.missing_fields.map(n=>`${Qs[n]} "${eo[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function yi(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):hn(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function wi(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 no="validate_metadata_duplicate_issue_codes";function ki(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:K,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${no}:${e.length}`]}}function io(){return Object.fromEntries(pt.map(e=>[e,[]]))}function ro(e,t,n){let i=io();for(let r of e)for(let s of pt)fi(r,s,t,n)&&i[s].push(r.id);return i}function so(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${Os[r]}:${s.length}`)}return i.push(...n),i}function vi(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=Ns[i];s>0&&o&&(n[o]=s)}return n}function bi(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function oo(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=js[r],a=Us[r];if(!o||!a)continue;let c=C(s,i?s.length:K);e[o]=c.values,e[a]=c.truncated}}function Ei(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Si(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function ao(e,t,n,i){let r=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",o=ro(e,n,s),a=$n(e),c=ki(a,i),l=so(t,o,c.warnings),d=vi(t,o),u=bi(t,o,r),m=Dn(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:[...pt],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]),oo(f,t,o,i);let w=Ei(t,o,r),p=Si(t,o,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:w,estimateBackfillRows:p}}function co(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has($e(m.status,t))),s=[],o=[];for(let m of r){let f=$s.filter(w=>!P(m[w]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:P(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:K,l=C(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>to(m)),u=C(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:s.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:o}}function Ii(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ri(e,t="pm",n=Ne()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=N(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(l=>{let d=N(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>N(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>o.add(l));let c=N(s.definition_of_ready);return Ci(c??"",t).filter(l=>i.has(l)).forEach(l=>o.add(l)),[s.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function xi(e,t,n){let i=Jt(e,n?d=>ye(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:K,a=C(r,o),c=C(s,o),l=C(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>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.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 Ci(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Ii(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function ht(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.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(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return o.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 gt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=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(!s.has(l)){if(s.add(l),r.push(l),o(l))return!0;r.pop(),s.delete(l)}}return!1};return o(n)?[...r]:[...e,n]}function Ai(e,t="pm"){let n=Ri(e,t),i=ht(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>gt(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Ti(e,t=Ne()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),i=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,o)=>s.id.localeCompare(o.id)).forEach(s=>{let o=i.get(s.id),a=N(s.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(s.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(s.id):o.push(u))})}),i.forEach((s,o)=>{i.set(o,[...new Set(s)].sort((a,c)=>a.localeCompare(c)))}),i}function Pi(e){let t=Ti(e),n=ht(t),i=[...new Set(n.flat())].sort((s,o)=>s.localeCompare(o)),r=n.map(s=>gt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function Fi(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 Le(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function Li(e,t){let n=Le(e).split("/").filter(Boolean),i=Le(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function lo(e,t){let n=Le(t),i=Le(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=Li(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function uo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function mo(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=ee(o.path);if(a.length===0||a===e)return;let c=lo(e,a);c!==null&&uo(r,s,c.score)&&(r={item:s,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 $i(e,t){return e.map(n=>{let i=Fi(n),r=i==="docs_unowned"?"docs":"files",s=mo(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Di(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function fo(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=N(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function po(e,t,n,i,r){let s=N(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!ye(o.status,r)}}function _o(e,t,n,i){let r=N(e.blocked_by),s=N(e.blocked_reason),o=s?.toLowerCase(),a=$e(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function ho(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!ye(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=fo(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=N(c.parent),u=d?r.get(s.get(d.toLowerCase())??d):void 0;if(u&&ye(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(po(c,u,r,s,n))),t){let m=_o(c,o,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,w)=>f.localeCompare(w))})}}return a}function go(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 oi(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function yo(e,t,n,i,r,s){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=oi("validate_lifecycle_dependency_cycles",n,r),c=oi("validate_hierarchy_parent_cycle",i,s);return[...o,...a?[a]:[],...c?[c]:[]]}function Mi(e){let t=ee(e);return t.length>Gs||t.split(/[\\/]/).some(n=>n.length>Ws)}async function wo(e,t){let n=F.isAbsolute(t)?t:F.resolve(e,t);if(Mi(n))return!1;try{let i=await ft.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return hi(i,["ENOENT","ENOTDIR"])}}async function ko(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ge(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=ee(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await wo(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function vo(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,l=c?[]:Xs(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>si(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!si(f,l)),m={};if(d.length>0){let f=X(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Oi(e,t,n,i,r,s,o,a="pm"){let c=ho(e,t,r,s);go(c);let l=Ai(c.activeItems,a),d=Pi(e),u=yo(c,t,n,i,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:K,f=C(c.closureLikeRows.map(I=>`${I.id}:${I.fields.join(",")}`),m),w=C(c.terminalParentRows.map(I=>`${I.id}:${I.parent_id}:${I.parent_status}`),m),p=C(c.staleBlockerRows.map(I=>`${I.id}:${I.status}:${I.reasons.join(",")}`),m),_=C(l.cycle_item_ids,m),h=C(l.cycle_sample_paths,m),v=C(d.cycle_item_ids,m),E=C(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error"?"error":u.length===0?"ok":"warn",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:w.values,active_terminal_parent_rows_truncated:w.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:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:h.values,dependency_cycle_sample_paths_truncated:h.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:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function Ni(e,t,n,i,r,s){let o=await ko(e,t),a=new Map(e.map(k=>[k.id,k])),c=[...new Set(o.missingLinkedPaths)].sort((k,R)=>k.localeCompare(R)),l=await Zs(t,i),d=vo(l,n,t,i,r,s),u=d.candidateFiles.filter(k=>!o.linkedProjectPaths.has(k)),m=$i(u,e),f=Nn(c,d.candidateFiles),w=new Map(f.map(k=>[k.path,k.classification])),p=f.filter(k=>k.classification==="moved").length,_=o.staleLinkRows.map(k=>({...k,classification:w.get(k.path)??"deleted"})).sort((k,R)=>k.item_id.localeCompare(R.item_id)||k.path.localeCompare(R.path)||k.link_kind.localeCompare(R.link_kind)),h=[];d.strictModeForcesPmInternals&&h.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&h.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&h.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((k,R)=>k.localeCompare(R)),E=X(v,s),S=X(c,s),I=X(u,s),G=X(m.map(k=>`${k.path}:${k.classification}:owner_candidate=${k.owner_candidate?.id??"unowned"}`),s),j=s?m:X(Di(m),!1).values,b=X(jn(f),s),A=_.map(k=>({item_id:k.item_id,path:k.path,link_kind:k.link_kind,classification:k.classification})),U=zn(A,k=>{let R=a.get(k);return R?{type:R.type,title:R.title,status:R.status}:void 0}),T=s?U:X(Bn(U),!1).values;return{check:{name:"files",status:h.length===0?"ok":"warn",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:s?"full":"summary",file_list_summary_limit:ci,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:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.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:b.values,missing_linked_path_classifications_truncated:b.truncated,missing_linked_path_rows_count:U.length,missing_linked_path_rows:T,orphaned_paths_count:u.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:G.values,orphaned_path_classifications_truncated:G.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:j}},warnings:h,staleLinkPruneRows:_}}async function bo(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:s,chainMismatches:o,driftedItems:a}=await Sn(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}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let l=n?Number.POSITIVE_INFINITY:K,d=C(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",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:s.length,chain_mismatches:o.length}}},warnings:c}}function Eo(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function ji(e,t,n){let i=new Set(e.map(_=>_.id.toLowerCase())),r=0,s=0,o=new Set,a=[],c=e.flatMap(_=>(_.tests??[]).map(h=>({item:_,linkedTest:h})));for(let{item:_,linkedTest:h}of c){if(typeof h.command!="string"||h.command.trim().length===0)continue;r+=1;let v=ei(h.command,t);if(v.length!==0){s+=v.length;for(let E of v)o.add(E),i.has(E.toLowerCase())||a.push(Eo(_.id,E,h.command))}}let l=[...new Set(a)].sort((_,h)=>_.localeCompare(h)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,h)=>_.localeCompare(h)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:K,f=C(l,m),w=C(d,m),p=C([...o].sort((_,h)=>_.localeCompare(h)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:o.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:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function So(e,t){let n=$t(e.map(c=>({ref:c.id,version:Lt(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:K,s=C(n.outdated,r),o=C(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:Ft,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var mt="pm validate auto-fix";async function Ui(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:mt};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 y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.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 lt(e){return e.kind!=="prune_file_link"&&e.kind!=="prune_doc_link"?null:`${e.kind}:${e.item_id}`}async function zi(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>lt(a)===null))try{await Ui(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>lt(a)!==null)){let a=lt(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Jn(a.item_id,{remove:c,message:mt},t):await Vn(a.item_id,{remove:c,message:mt},t),i.push(...o)}catch(l){r.push(...o.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Rl={applyValidateFix:Ui,applyValidateFixes:zi,attachValidateFixHints:yi,buildCommandReferencesCheck:ji,buildDependencyReferencesCheck:xi,buildCloseReasonBackfillRows:Ei,buildFilesCheck:Ni,buildLifecycleCheck:Oi,buildLifecycleDependencyGraph:Ri,buildLifecycleParentGraph:Ti,buildEstimateBackfillRows:Si,buildMetadataCounts:vi,buildMissingFieldOccurrences:bi,buildOrphanedPathRows:$i,classifyOrphanedPath:Fi,collectDefaultProjectFileCandidates:ut,collectTrackedGitFileCandidates:gi,detectLifecycleDependencyCycles:Ai,detectLifecycleParentCycles:Pi,escapeRegExp:Ii,extractItemIds:Ci,findLifecycleDependencyCycleComponents:ht,isMetadataFieldMissing:fi,linkedArtifactPathExceedsFilesystemLimits:Mi,listFilesRecursive:_t,resolveDependencyCycleSeverity:ui,resolveParentCycleSeverity:mi,resolveFileScanMode:pi,resolveLifecycleDependencyCycleSamplePath:gt,resolveRequestedChecks:wi,resolveValidateMetadataProfile:di,resolveWorkspaceRoot:_i,sharedDirectoryPrefixLength:Li,summarizeOrphanedPathRows:Di,summarizeDuplicateIssueCodes:ki,toMeaningfulString:N};async function Io(e,t,n,i){let r=await _n(e,new Set(t.map(m=>m.id)),n,{schema:i.schema,extensionFieldNames:vt(W())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await Wn(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await cn(e,Se(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await pe(e),d=l===null?null:await ln(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await Xe(l);return u.length>0&&s.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":s.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),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:s}}function H(e,t,n){n&&yi(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function Ro(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=ao(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,H(t,r,n)}if(e.requestedChecks.has("resolution")){let r=co(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,H(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Oi(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,H(t,r,n),H(t,xi(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await Ni(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,H(t,r,n)}return e.requestedChecks.has("command_references")&&H(t,ji(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&H(t,await bo(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&H(t,So(e.items,i),n),e.requestedChecks.has("storage_integrity")&&H(t,await Io(e.pmRoot,e.items,z(e.settings,W()).type_to_folder,e.settings),n),t}function xo(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...xn(t.closeReasonBackfillRows)),i.push(...Rn(t.resolutionBackfillRows)),i.push(...Cn(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...An(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Tn(t.staleLinkPruneRows)),i}async function Co(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=xo(e,t,n),{applicable:a,gated:c}=Fn(o,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await zi(a,r,s);d.push(...m.applied.map(he)),u.push(...m.failed.map(({fix:f,error:w})=>({...he(f),error:w instanceof Error?w.message:String(w)})))}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:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(he),applied_fixes:d,gated_fixes:c.map(m=>({...he(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function xl(e,t,n={}){At(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let r=Pn(e.fixScope),s=B(process.cwd(),t.path);if(!await L(O(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,g.NOT_FOUND);let o=await $(s),a=Ct(o.schema),c=z(o,W()),l=[],d=await Ht(s,o.item_format,c.type_to_folder,l,o.schema),u=wi(e);if(u.has("history_drift")){let A=await Ye(s);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=di(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),w=Ys(f,m,o.validation.metadata_required_fields),p=Ks(o),_=ui(e.dependencyCycleSeverity),h=mi(e.parentCycleSeverity),v=pi(e.scanMode),E=_i(s),S=await Ro({requestedChecks:u,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:d,statusRegistry:a,metadataPolicy:w,lifecyclePatternPolicy:p,dependencyCycleSeverity:_,parentCycleSeverity:h,fileScanMode:v,initialWarnings:[...new Set(l)]}),I=i?await Co(e,S,o,r,t,n):void 0,G=[...new Set(S.warnings)].sort((A,U)=>A.localeCompare(U)),b={ok:!S.checks.some(A=>A.status==="error"),has_warnings:G.length>0,checks:S.checks,warnings:G,...I!==void 0?{fixes:I}:{},generated_at:V(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...Hs(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{Lo as a,Q as b,fe as c,pe as d,Ve as e,Se as f,cn as g,ln as h,Jo as i,Xo as j,Xi as k,Sn as l,pr as m,Zi as n,un as o,ia as p,Ye as q,ra as r,Wn as s,pa as t,_a as u,Xe as v,ha as w,ga as x,_n as y,Vn as z,Jn as A,Lc as B,$c as C,hs as D,gs as E,Mc as F,Oc as G,Nc as H,jc as I,ws as J,ks as K,vs as L,Uc as M,Zn as N,Es as O,Qn as P,ct as Q,ti as R,Ss as S,Is as T,Rs as U,Hs as V,Rl as W,xl as X};
|
|
14
|
-
//# sourceMappingURL=chunk-
|
|
9
|
+
`;return d===r?{path:i,changed:!1}:(n||await Ki(i,d,"utf8"),{path:i,changed:!0})}function Ie(e){let t=z(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((n,i)=>n.localeCompare(i))}async function ln(e,t){let n=x.resolve(e),i=null,r="",s=n;for(let p=0;p<8;p+=1){let _=x.join(s,".gitattributes");try{let v=await Se(_,"utf8");if(v.includes(Q)){i=s,r=v;break}}catch{}let h=x.dirname(s);if(h===s)break;s=h}if(i===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let o=x.join(i,".gitattributes"),a=r.indexOf(Q),c=r.indexOf(fe),l=c>a?r.slice(a+Q.length,c).split(`
|
|
10
|
+
`).map(p=>p.trim()).filter(p=>p.length>0):[],d=Ye(Ve(i,n),t),u=new Set(l),m=new Set(d),f=d.filter(p=>!u.has(p)),w=l.filter(p=>!m.has(p));return{status:f.length>0||w.length>0?"drift":"ok",path:o,missing_patterns:f,stale_patterns:w,schema_scope:"project"}}async function dn(e){let t=sn(),n=[],i=[];for(let r of on){let s=`merge.${r.key}.driver`,o=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${o}`;try{let{stdout:c}=await Ke("git",["config","--local","--get",s],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Xi(l,o)&&i.push(s)}catch{n.push(s)}}return{status:n.length>0?"missing":i.length>0?"drift":"ok",missing_keys:n,drifted_keys:i}}async function Xo(e){let t;try{t=await an(x.resolve(e))}catch{return{status:"no_git"}}let n=Ve(t,x.resolve(e)),i=await $(e),r=ne(void 0,i.author_default),s=await Ft(e,Ji,i.locks.ttl_seconds,r,!1,Gt(i).force_required_for_stale_lock,i.locks.wait_ms);try{let o=x.join(t,".gitattributes"),a;try{a=await Se(o,"utf8")}catch(u){if(u instanceof Error&&"code"in u&&u.code==="ENOENT")return{status:"not_installed",path:o};throw u}if(!a.includes(Q))return{status:"not_installed",path:o};let c=await $(e),l=Ie(c),d=await cn(t,Ye(n,l),!1);return{status:d.changed?"refreshed":"unchanged",path:d.path}}finally{await s()}}async function Zo(e,t){let n=t.path?.trim(),i=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),s=n===void 0&&i!==void 0&&i.length>0&&r!==void 0&&r.length>0,o=n!==void 0?B(process.cwd(),n):s?x.resolve(r):B(process.cwd());if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let a=await an(n!==void 0?o:s?x.resolve(i):process.cwd());return Zi({pmRoot:o,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Zi(e){let t=x.resolve(e.pmRoot),n=x.resolve(e.workspaceRoot),i=e.dryRun===!0,r,s;try{[r,s]=await Promise.all([He(t),He(n)])}catch(f){throw new y(`Cannot resolve tracker root ${t} or workspace root ${n}: ${String(f)}`,g.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 o=Ve(s,r);if(qe(o))throw new y(`Tracker root ${t} is outside the git repository ${n}; there is nothing to configure for this repository.`,g.USAGE);let a=await $(r),c=Ie(a),l=Ye(o,c),d=[],u=sn();for(let f of on)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 Ke("git",["config","--local",f.key,f.value],{cwd:s,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${s}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,g.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 cn(s,l,i);return{ok:!0,dry_run:i,workspace_root:s,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 validate" and, if history drift is reported, "pm history-repair --all" to reconcile item state with merged history.',"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:Y()}}import Re from"node:fs/promises";import xe 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]="09427917-8347-59cc-9358-452671aed3c3")}catch{}})();function _e(e,t){throw new y(e,g.USAGE,{code:t})}var Qi="2026-07-15T06:22:12.276Z",er=Date.parse(Qi),tr=[["attributed","attributed"],["legacy_unknown","actionable_unknown"]],un=e=>typeof e=="string"?e:"",mn=e=>{let t=e??{},n=un(t.author).trim().toLowerCase(),i=Number(["","unknown"].includes(n)),r=+(Date.parse(un(t.ts))>=er);return tr[i][r]};function fn(e,t,n=20,i=new Set,r=!1){let s=[],o=[],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 w;try{w=JSON.parse(f)}catch{continue}l+=1;let p=mn(w);if(p!=="attributed"){if(d+=1,p==="actionable_unknown"&&i.has(`${e}:${m+1}`)){u+=1;continue}a[p]+=1,r&&p==="actionable_unknown"&&o.push({item_id:e,line:m+1}),s.length<c&&s.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:s,samples_truncated:a.legacy_unknown+a.actionable_unknown>s.length,actionable_events:o}}var oa=(e,t,n=20,i=new Set)=>fn(e,t,n,i);function nr(e){let t=new Set;for(let n of e.split(/\r?\n/)){let i;try{i=JSON.parse(n)}catch{continue}let s=(typeof i=="object"&&i!==null&&typeof i.context=="object"&&i.context!==null?i.context:{}).author_acknowledgment;if(!(typeof s!="object"||s===null||!Array.isArray(s.events)))for(let o of s.events)typeof o=="object"&&o!==null&&typeof o.item_id=="string"&&Number.isSafeInteger(o.line)&&t.add(`${o.item_id}:${String(o.line)}`)}return t}var Je=async(e,t=20,n=!1)=>{let i=xe.join(e,"history"),r;try{r=(await Re.readdir(i)).filter(h=>h.endsWith(".jsonl")).sort((h,v)=>h.localeCompare(v))}catch{r=[]}let s=new Set,o=[],a=[],c=0,l=0,d=0,u=0,m=0,f=0,w="_workspace.jsonl",p=new Set;if(r.includes(w))try{p=nr(await Re.readFile(xe.join(i,w),"utf8"))}catch{p=new Set}for(let h of r){let v;try{v=await Re.readFile(xe.join(i,h),"utf8")}catch{continue}let E=h.slice(0,-6),S=fn(E,v,t-o.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&&s.add(E),o.push(...S.samples),n&&a.push(...S.actionable_events)}let _=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:[...s].sort((h,v)=>h.localeCompare(v)),samples:o,samples_truncated:_>o.length,...n?{actionable_events:a}:{}}};async function aa(e,t){let n=t.reviewer.trim(),i=t.attributed_author.trim(),r=t.reason.trim(),s=t.events??[];+(t.all_actionable===!0)+ +(s.length>0)>1&&_e("Author acknowledgment accepts either explicit events or all_actionable, not both.","history_author_acknowledge_selector_conflict");let a=t.all_actionable===!0?(await Je(e,0,!0)).actionable_events:s;[a.length>0,n.length>0,n.toLowerCase()!=="unknown",i.length>0,i.toLowerCase()!=="unknown",r.length>0].includes(!1)&&_e("Author acknowledgment requires events, reviewer, attributed_author, and reason.","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){[/^[a-z0-9][a-z0-9-]*$/i.test(m.item_id),Number.isSafeInteger(m.line),m.line>=1].includes(!1)&&_e(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable");let w;try{let _=(await Re.readFile(xe.join(e,"history",`${m.item_id}.jsonl`),"utf8")).split(/\r?\n/)[m.line-1];w=JSON.parse(_??"")}catch{_e(`Unknown-author acknowledgment target ${m.item_id}:${m.line} is not readable.`,"history_author_acknowledge_target_unreadable")}mn(w)!=="actionable_unknown"&&_e(`Author acknowledgment target ${m.item_id}:${m.line} is not an actionable unknown-author event.`,"history_author_acknowledge_target_not_actionable")}let d=await $(e),u=await zt({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{execFile as ir}from"node:child_process";import{randomUUID as rr}from"node:crypto";import{readdir as sr,readFile as or}from"node:fs/promises";import he from"node:path";import{promisify as ar}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]="c4721ede-e557-5720-a9c2-4b2b344cc6cc")}catch{}})();var cr=ar(ir);async function Xe(e){try{let{stdout:t}=await cr("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}}function pn(e){return`${e}.json`}function ga(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,preferred:e.preferred,decisions:e.decisions.map(t=>({field:t.field,retained_hash:ze(Ue(t.retained)),discarded_hash:ze(Ue(t.discarded))}))}}async function ya(e){let t=await Xe(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=he.basename(i,he.extname(i)),s={version:1,id:rr(),item_path:i.replaceAll("\\","/"),item_id:r,preferred:e.preferred,fields_from_theirs:[...e.fieldsFromTheirs],union_fields:[...e.unionFields],decisions:structuredClone(e.decisions),state:"pending",created_at:Y()};return await Et(t),await ce(he.join(t,pn(s.id)),`${JSON.stringify(s,null,2)}
|
|
11
|
+
`),s}async function Ze(e,t={}){let n=await Xe(e);if(n===null||!await L(n))return[];let i=[],r;try{r=await sr(n)}catch{return[]}for(let s of r.sort((o,a)=>o.localeCompare(a)))if(s.endsWith(".json"))try{let o=JSON.parse(await or(he.join(n,s),"utf8"));o.version===1&&(t.includeReconciled||o.state==="pending")&&i.push(o)}catch{}return i.sort((s,o)=>s.created_at.localeCompare(o.created_at))}async function wa(e,t){let n=await Xe(e);n!==null&&await ce(he.join(n,pn(t.id)),`${JSON.stringify({...t,state:"reconciled",reconciled_at:Y()},null,2)}
|
|
12
|
+
`)}async function ka(e){let t=await Ze(e.cwd??process.cwd(),e);return{ok:!0,count:t.length,receipts:t,generated_at:Y()}}import re from"node:fs/promises";import se 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 lr(e,t){let n=[...new Set(Object.values(t))],i=[];return await Promise.all(n.map(async r=>{let s;try{s=await re.readdir(se.join(e,r))}catch{return}for(let o of s)for(let a of Rt)if(o.toLowerCase().endsWith(a)){i.push({relativePath:`${r}/${o}`,id:o.slice(0,-a.length)});break}})),i.sort((r,s)=>r.relativePath.localeCompare(s.relativePath))}function dr(e,t){let{id:n,relativePath:i,liveItemIds:r,out:s}=e,o=Be(t);if(o){s.conflictMarkers.push({id:n,path:i,line:o.line,detail:`unresolved merge conflict marker ${o.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{s.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)&&s.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&&(s.repairReconciliations+=1))}function Qe(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 ur(e,t){let n={conflictMarkers:[],unparseable:[],resurrected:[],repairReconciliations:0,scanned:0},i;try{i=await re.readdir(se.join(e,"history"))}catch{return n}for(let r of i.sort((s,o)=>s.localeCompare(o))){if(!r.endsWith(".jsonl"))continue;n.scanned+=1;let s;try{s=await re.readFile(se.join(e,"history",r),"utf8")}catch(o){n.unparseable.push({id:r.slice(0,-6),path:`history/${r}`,detail:Qe("history stream",o)});continue}dr({id:r.slice(0,-6),relativePath:`history/${r}`,liveItemIds:t,out:n},s)}return n}function _n(e){let t=Be(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 mr(e){let t=[],n=0,i=null;try{i=await St(O(e))}catch(s){n+=1,t.push({path:"settings.json",detail:Qe("configuration file",s)})}if(i!==null){n+=1;let s=_n(i);s!==null&&t.push({path:"settings.json",detail:s})}let r;try{r=await re.readdir(se.join(e,"schema"))}catch{return{scanned:n,unparseable:t}}for(let s of r.sort((o,a)=>o.localeCompare(a))){if(!s.endsWith(".json"))continue;n+=1;let o;try{o=await re.readFile(se.join(e,"schema",s),"utf8")}catch(c){t.push({path:`schema/${s}`,detail:Qe("configuration file",c)});continue}let a=_n(o);a!==null&&t.push({path:`schema/${s}`,detail:a})}return{scanned:n,unparseable:t}}async function hn(e,t,n,i={}){let r=await lr(e,n),s=new Set(r.map(u=>u.id)),o=new Map;for(let u of r){let m=o.get(u.id);m===void 0?o.set(u.id,[u.relativePath]):m.push(u.relativePath)}let a=[...o.entries()].filter(([,u])=>u.length>1).map(([u,m])=>({id:u,paths:[...m].sort((f,w)=>f.localeCompare(w))})).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=se.join(e,u.relativePath);return Ot(await re.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 ur(e,s),d=await mr(e);return{item_files_on_disk:r.length,item_ids_on_disk:s.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 pt from"node:fs/promises";import{realpathSync as As}from"node:fs";import{execFile as Ts}from"node:child_process";import F from"node:path";import{promisify as Ps}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]="6a350683-275b-5d4d-ae02-45798b115f89")}catch{}})();var fr=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:"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 validate --check-history-drift --fix-hints",summary:"Historical mutations lack attributable authorship. Configure PM_AUTHOR, pass global --author, or set author_default so future audit events are attributable."},{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_history_unknown_author_events",command:"pm config project set author_default <stable-agent-id>",summary:"Historical mutations lack attributable authorship. Set a stable default or use invocation-wide --author for future events; existing audit history remains append-only."},{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 pr(e){if(typeof e!="string")return;let t=e.trim();for(let n of fr)if(t===n.code||t.startsWith(`${n.code}:`))return n}function _r(e){let t={};for(let n of e){let i=pr(n);i!==void 0&&!Object.prototype.hasOwnProperty.call(t,i.code)&&(t[i.code]=i.command)}return t}function gn(e){return Object.values(_r(e))}import oe from"node:fs/promises";import{createHash as hr}from"node:crypto";import wn 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]="90364096-b94c-591c-9024-e697fa9322a5")}catch{}})();var kn=3,gr="history-drift-cache.json";function vn(e){return wn.join(e,"runtime",gr)}async function yr(e){try{let t=await oe.readFile(vn(e),"utf8"),n=JSON.parse(t);return n.version!==kn||typeof n.entries!="object"||n.entries===null?null:n}catch{return null}}function bn(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function wr(e,t,n,i,r){let s=Ut(e),o;try{o=await oe.stat(s)}catch(l){return bn(l,"ENOENT")||r.unreadableStreams.push(ie),!1}let a=r.missingStreams.length,c=await Sn({itemId:ie,historyPath:s,stat:o,cached:t[ie],verifyCacheHitByContent:i,accumulator:r});return c.verification?(c.verification.chainOk||r.chainMismatches.push(ie),n[ie]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,content_hash:c.verification.contentHash,latest_after_hash:c.verification.latestAfterHash,chain_ok:c.verification.chainOk},c.cacheDirty):(r.missingStreams.splice(a),c.cacheDirty)}function En(e){return hr("sha256").update(e).digest("hex")}async function kr(e){let t=await oe.readFile(e,"utf8");return En(t)}async function vr(e){let t=await oe.readFile(e,"utf8"),n=En(t);if(t.trim().length===0)return null;let i=[],r=null;for(let s of t.split(/\r?\n/)){let o=s.trim();if(o.length===0)continue;let a=JSON.parse(o);if(typeof a.after_hash!="string"||a.after_hash.trim().length===0)throw new Error("missing after_hash");i.push(a),r=a.after_hash}return r?{latestAfterHash:r,chainOk:jt(i).ok,contentHash:n}:null}function br(e,t){return e!==void 0&&e.mtime_ms===t.mtimeMs&&e.ctime_ms===t.ctimeMs&&e.size===t.size}async function yn(e,t,n){try{let i=await vr(t);return i||(n.missingStreams.push(e),null)}catch{return n.unreadableStreams.push(e),null}}async function Sn(e){let t=typeof e.cached?.content_hash=="string"&&e.cached.content_hash.length>0?e.cached.content_hash:void 0;if(!(br(e.cached,e.stat)&&t!==void 0&&e.cached!==void 0)||!e.cached)return{verification:await yn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0};let i;if(e.verifyCacheHitByContent)try{i=await kr(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},cacheDirty:!1}:{verification:await yn(e.itemId,e.historyPath,e.accumulator),cacheDirty:!0}}async function In(e,t,n={}){let i={missingStreams:[],unreadableStreams:[],hashMismatches:[],chainMismatches:[]},s=(await yr(e))?.entries??{},o={},a=!1,c=n.cacheHitVerification!=="metadata";for(let u of t){let m=xt(e,u.id),f;try{f=await oe.stat(m)}catch(E){bn(E,"ENOENT")?i.missingStreams.push(u.id):i.unreadableStreams.push(u.id);continue}let w=s[u.id],p=await Sn({itemId:u.id,historyPath:m,stat:f,cached:w,verifyCacheHitByContent:c,accumulator:i});if(a||=p.cacheDirty,!p.verification)continue;p.verification.chainOk||i.chainMismatches.push(u.id),o[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};let{body:_,...h}=u;Nt({metadata:h,body:_})!==p.verification.latestAfterHash&&i.hashMismatches.push(u.id)}let l=await wr(e,s,o,c,i);if(a||=l,a||Object.keys(s).length!==Object.keys(o).length){let u=vn(e);try{await oe.mkdir(wn.dirname(u),{recursive:!0}),await ce(u,JSON.stringify({version:kn,entries:o}))}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 Er=["metadata","resolution"],et=["metadata","resolution","estimates","lifecycle"],Sr="completed";function tt(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Rn(e){let t=e?.trim();return t!==void 0&&t.length>0?t:void 0}function xn(e){let t=[];for(let n of e){if(!n.missing_fields.includes("resolution"))continue;let i=Rn(n.close_reason)??Sr;t.push({item_id:n.id,check:"resolution",field:"resolution",kind:"set_resolution",value:i,command:`pm update ${n.id} --resolution ${tt(i)}`,gate:"resolution"})}return t}function Cn(e){let t=[];for(let n of e){let i=Rn(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 ${tt(i)}`,gate:"metadata"})}return t}function An(e,t){return e.map(n=>{let i=Bt(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 Tn(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 Pn(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 ${tt(n.path)}`})}return t}function Fn(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 y(`--fix-scope values must not be empty. Supported values: ${et.join(", ")}.`,g.USAGE);return new Set(Er)}let n=new Set;for(let i of t){let r=i.toLowerCase().replaceAll("-","_");if(et.includes(r)){n.add(r);continue}throw new y(`Unknown --fix-scope value "${i}". Supported values: ${et.join(", ")}.`,g.USAGE)}return n}function Ln(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 ge(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 Ir=/^([A-Z][A-Z0-9]*-\d+)\b/;function Rr(e){if(typeof e!="string")return null;let t=e.trim().toUpperCase();if(t.length===0)return null;let n=Ir.exec(t);return n?n[1]:null}function $n(e){return typeof e=="string"&&e.trim().length>0}function Dn(e){let t=new Map;for(let i of e){if(typeof i.title!="string"||$n(i.duplicate_of))continue;let r=Rr(i.title);if(r===null)continue;let s=t.get(r);s||(s=[],t.set(r,s)),s.some(o=>o.id===i.id)||s.push({id:i.id,title:i.title,parent:$n(i.parent)?i.parent.trim():null})}let n=[];for(let[i,r]of t){if(r.length<2)continue;let s=new Set(r.map(c=>c.id.toLowerCase())),o=r.filter(c=>c.parent===null||!s.has(c.parent.toLowerCase()));if(o.length<2)continue;let a=[...o].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 Mn(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,s)=>r.localeCompare(s))){let r=t.get(i),s={};for(let o of[...r.keys()].sort((a,c)=>a.localeCompare(c)))s[o]=r.get(o);n[i]=s}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 On=3;function Nn(e){let t=Math.max(e.lastIndexOf("/"),e.lastIndexOf("\\"));return t===-1?e:e.slice(t+1)}function jn(e,t,n=On){let i=Number.isFinite(n)&&n>=1?Math.floor(n):On,r=new Map;for(let s of t){let o=Nn(s);if(o.length===0)continue;let a=r.get(o);a?a.push(s):r.set(o,[s])}return e.map(s=>{let o=(r.get(Nn(s))??[]).filter(a=>a!==s).sort((a,c)=>a.localeCompare(c));return o.length===0?{path:s,classification:"deleted",candidates:[],candidates_truncated:!1}:{path:s,classification:"moved",candidates:o.slice(0,i),candidates_truncated:o.length>i}})}function Un(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 xr=/^[a-z][a-z0-9+.-]+:\/\//i;function ye(e){return xr.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 Cr(e,t){return e==="moved"||t==="moved"?"moved":"deleted"}function zn(e){return`${e.item_id} ${e.link_kind}`}function Bn(e,t){let n=new Map;for(let i of e){let r=n.get(i.path);r?(r.classification=Cr(r.classification,i.classification),r.owners.set(zn(i),i)):n.set(i.path,{classification:i.classification,owners:new Map([[zn(i),i]])})}return[...n.entries()].sort(([i],[r])=>i.localeCompare(r)).map(([i,r])=>({path:i,classification:r.classification,items:[...r.owners.values()].map(s=>{let o=t(s.item_id);return{id:s.item_id,type:o?.type??"Unknown",title:o?.title??"",status:o?.status??"",field:s.link_kind}}).sort((s,o)=>{let a=s.id.localeCompare(o.id);return a!==0?a:s.field.localeCompare(o.field)})}))}function Ar(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}function Gn(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="${Ar(i.title)}"`);return t}import{execFile as Tr}from"node:child_process";import{realpath as Pr}from"node:fs/promises";import Wn from"node:path";import{promisify as Fr}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 Lr=Fr(Tr),$r=32*1024*1024,Dr=1e4,Mr=["search/eval-queries.json"];function nt(e){return e.replaceAll("\\","/").replace(/\/+$/,"")}function Or(e){return`'${e.replaceAll("'","'\\''")}'`}async function Nr(e,t=Pr){return t(e).catch(()=>Wn.resolve(e))}async function qn(e){let t=await pe(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 Nr(e),i=nt(Wn.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=We.map(s=>`${i}/${nt(s)}`);try{let{stdout:s}=await Lr("git",["ls-files","-z","--",...r.map(l=>`:(literal)${l}`)],{cwd:t,encoding:"utf8",maxBuffer:$r,windowsHide:!0,timeout:Dr}),o=new Set(Mr.map(l=>`${i}/${l}`)),a=[...new Set(s.split("\0").filter(l=>l.length>0&&!o.has(nt(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=>Or(`:(literal)${l}`)).join(" ")}`}}catch{return{git_workspace_root:t,tracker_relative_root:i,tracked_paths:[],tracked_path_count:0,remediation_command:null}}}import jr from"node:fs/promises";import D from"node:path";import Ur 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 zr=["path","scope","note"],Br=["pattern","glob","path","scope","note"],Gr=["path"],Wr=["from","to"],qr=new Set(["note","scope"]);function Kn(e){let t=e??"project";if(!Oe.includes(t))throw new y(`Invalid scope "${e}". Valid scopes: ${Oe.join(", ")} (default: project).`,g.USAGE);return t}function Vn(e){return e.startsWith("```")||e.includes(`
|
|
13
|
+
`)||/^(?:[-*+]\s+)?(?:path|scope|note)\s*[:=]/i.test(e)?!0:Vt(e)}function Hr(e){return e.flatMap(t=>{let n=t.trim();return n.length===0||Vn(n)||!n.includes(",")?[t]:Jt(n)})}function Kr(e,t){return e?Hr(e).map(n=>{let i=n.trim(),r=Vn(i)?de(n,"--add"):{path:i};if(ue(r,"--add",zr),!r.path)throw new y(`--add requires path=<value> or a bare ${t} path`,g.USAGE);return{path:r.path,scope:Kn(r.scope),note:r.note?.trim()||void 0}}):[]}function Vr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--add-glob requires a glob pattern value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?(?:pattern|glob|path)\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--add-glob");ue(i,"--add-glob",Br);let r=i.pattern?.trim()||i.glob?.trim()||i.path?.trim();if(!r)throw new y("--add-glob key/value form requires pattern=<glob>",g.USAGE);return{pattern:r,scope:Kn(i.scope),note:i.note?.trim()||void 0}}return{pattern:n,scope:"project"}}):[]}function Yr(e){return e?e.map(t=>{let n=t.trim();if(!n)throw new y("--remove requires a path value",g.USAGE);if(n.includes("=")||/^(?:[-*+]\s+)?path\s*[:=]/i.test(n)||n.startsWith("```")){let i=de(n,"--remove"),r=Object.keys(i).filter(s=>qr.has(s.toLowerCase()));if(r.length>0)throw new y(`--remove identifies a linked artifact by path only and does not accept ${r.map(s=>`"${s}"`).join(", ")}. Pass just the path (path=<value>, path:<value>, or a bare path); record removal context with --message "<why removed>".`,g.USAGE);if(ue(i,"--remove",Gr),!i.path)throw new y("--remove key/value form requires path=<value>",g.USAGE);return i.path}return n}):[]}function Jr(e){return e?e.map(t=>{let n=de(t,"--migrate");ue(n,"--migrate",Wr);let i=n.from?.trim(),r=n.to?.trim();if(!i||!r)throw new y("--migrate requires from=<value> and to=<value>",g.USAGE);return{from:i,to:r}}):[]}function it(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 H(e){return e.split(D.sep).join("/")}function rt(e,t,n=process.cwd()){let i=e.trim();if(ye(i))return i;if(D.isAbsolute(i)||/^[A-Za-z]:[\\/]/.test(i))return H(i.replaceAll("\\",D.sep));let r=D.relative(t,n);return r.startsWith(`..${D.sep}`)||r===".."||D.isAbsolute(r)?H(D.normalize(i)):H(D.relative(t,D.resolve(n,i)))}async function Xr(e,t=process.cwd(),n=process.cwd()){let i=[];for(let r of e){let s=D.isAbsolute(r.pattern),o=await Ur(r.pattern,{cwd:n,absolute:s,onlyFiles:!0,dot:!0,unique:!0,followSymbolicLinks:!0}),a=[...new Set(o.map(c=>rt(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 Zr(e,t,n){if(t===void 0)return e;if(!n)throw new y("--note requires --add or --add-glob in the same invocation (the note annotates the links being added)",g.USAGE);let i=t.trim();return i.length===0?e:e.map(r=>r.note===void 0?{...r,note:i}:r)}function Qr(e){return`${e.path}::${e.scope}`}function st(e){return[...e].sort((t,n)=>{let i=t.path.localeCompare(n.path);return i!==0?i:t.scope.localeCompare(n.scope)})}function ot(e){return[...new Map(e.map(t=>[Qr(t),t])).values()].map(t=>({...t,note:t.note?.trim()||void 0}))}async function es(e,t=process.cwd()){let n=[...new Set(e)].sort((a,c)=>a.localeCompare(c)),i=[],r=[],s=[],o=[];for(let a of n){if(ye(a)){o.push(a.trim());continue}let c=D.isAbsolute(a)?a:D.resolve(t,a);try{(await jr.stat(c)).isFile()?i.push(a):s.push(a)}catch(l){if(typeof l=="object"&&l!==null&&"code"in l&&l.code==="ENOENT"){r.push(a);continue}s.push(a)}}return{checked:n.length,existing_files:i,missing_paths:r,non_file_paths:s,remote_references:o}}function ts(e,t,n,i){let r=0;for(let o=0;o<e.length;o+=1){let a=it(e[o].path,i);a!==e[o].path&&(e[o]={...e[o],path:a},r+=1)}return{adds:t.map(o=>{let a=it(o.path,i);return a!==o.path&&(r+=1),{...o,path:a}}),removes:n.map(o=>it(o,i)),count:r}}function ns(e,t,n,i){for(let s of t)e.some(o=>o.path===s.path&&o.scope===s.scope)||e.push(s);if(n.length>0)for(let s=e.length-1;s>=0;s-=1)n.includes(e[s].path)&&e.splice(s,1);let r=ot(e);return i?r:st(r)}async function Hn(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 es(t,e.workspaceRoot):void 0}}async function Ce(e,t,n,i){let{metadataKey:r}=i,s=Yt(),o=B(process.cwd(),n.path),a=le(o),c=process.cwd();if(!await L(O(o)))throw new y(`Tracker is not initialized at ${o}. Run pm init first.`,g.NOT_FOUND);let l=await $(o),d=z(l,q()),u=await s.resolveList(t.add,"--add"),m=await s.resolveList(t.addGlob,"--add-glob"),f=await s.resolveList(t.remove,"--remove"),w=await s.resolveList(t.migrate,"--migrate"),p=Kr(u,i.bareNoun).map(T=>({...T,path:rt(T.path,a,c)})),_=Vr(m),h=await Xr(_,a,c),v=Zr([...p,...h],t.note,p.length>0||_.length>0),E=Yr(f).map(T=>rt(T,a,c)),S=Jr(w);if(!(v.length>0||E.length>0||S.length>0)){let T=await ve(o,e,l.id_prefix,l.item_format,d.type_to_folder);if(!T)throw new y(`Item ${e} not found`,g.NOT_FOUND);let R=(await be(T,{schema:l.schema})).document.metadata[r]??[];return Hn({id:T.id,artifacts:R,changed:!1,options:t,workspaceRoot:a})}let W=ne(t.author,l.author_default),j=await Ee({pmRoot:o,settings:l,id:e,op:i.op,author:W,message:t.message,force:t.force,skipNoop:!0,mutate(T){let k=T.metadata,R=k[r]??[],te=[...R],Z=ts(te,v,E,S),Me=ns(te,Z.adds,Z.removes,i.supportsAppendStable&&t.appendStable===!0);Me.length>0?k[r]=Me:delete k[r];let wt=!Ct(R,Me);return{changedFields:wt?[r]:[],warnings:wt&&Z.count>0?[`path_migrations_applied:${Z.count}`]:[]}}}),b=j.item[r]??[],A=j.warnings.find(T=>T.startsWith("path_migrations_applied:")),U=A?Number(A.slice(24)):0;return Hn({id:j.item.id,artifacts:b,changed:j.changedFields.includes(r),migrationsApplied:U,options:t,workspaceRoot:a})}function Ae(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 Yn(e,t,n){let i=await Ce(e,t,n,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return Ae(i,"docs")}import Jn from"node:fs/promises";import M 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]="5e45d0f1-a1a7-50ea-a9a3-ec6283d3471d")}catch{}})();var is=32768;function at(e){return H(M.normalize(e))}async function Te(e){try{return await Jn.realpath(e)}catch{return M.resolve(e)}}function ae(e,t){let n=M.isAbsolute(e.path)?M.resolve(e.path):M.resolve(t,e.path);return`${at(n)}::${e.scope}`}function Pe(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)=>Pe(i,`${t}[${r}]`,n));return}if(typeof e=="object"&&e!==null)for(let[i,r]of Object.entries(e))Pe(r,t?`${t}.${i}`:i,n)}function rs(e){let t=[];return Pe(e.metadata,"metadata",t),Pe(e.body,"body",t),t}function ss(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 os(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 s=new Set,o=r.value.slice(0,is);for(let[a,c]of[[n,r.value],[i,o]]){a.lastIndex=0;for(let l of c.matchAll(a)){let d=ss(l[0]);!d||s.has(d)||(s.add(d),t.push({field:r.field,value:d}))}}}return t}async function as(e,t,n=t){let i=M.isAbsolute(e)?M.resolve(e):M.resolve(n,e),r;try{r=await Jn.stat(i)}catch{return}if(!r.isFile())return;let[s,o]=await Promise.all([Te(t),Te(i)]);if(Ne(s,o)){let a=M.relative(s,o);return!a||a.startsWith("..")||M.isAbsolute(a)?void 0:{path:at(a),scope:"project"}}return{path:at(i),scope:"global"}}async function cs(e,t,n=t){let i=new Set((e.metadata.files??[]).map(c=>ae(c,t))),r=new Map,s=os(rs(e)),o=new Map;await Promise.all([...new Set(s.map(c=>c.value))].map(async c=>{o.set(c,await as(c,t,n))}));let a=s.map(c=>({reference:c,resolved:o.get(c.value)}));for(let{reference:c,resolved:l}of a){if(!l)continue;let d=ae(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 Xn(e,t,n){let i=await Ce(e,t,n,{metadataKey:"files",op:"files_add",bareNoun:"file",supportsAppendStable:!0});return Ae(i,"files")}async function ls(e,t){let n=await Te(t),i=await Promise.all(e.map(async s=>{let o=s.trim();if(!o)throw new y("Files lookup paths must not be empty.",g.USAGE);if(!M.isAbsolute(o))return H(o);let a=await Te(o);return Ne(n,a)?H(M.relative(n,a)):H(a)})),r=[...new Set(i)].sort((s,o)=>s.localeCompare(o));if(r.length===0)throw new y("Files lookup requires at least one path.",g.USAGE);return r}function ds(e){for(let[i,r]of[["limit",e.limit],["offset",e.offset]])if(r!==void 0&&(!Number.isInteger(r)||r<0))throw new y(`Files lookup ${i} must be a non-negative integer.`,g.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 Zn(e){return{id:e.id,title:e.title,type:e.type,status:e.status,priority:e.priority,updated_at:e.updated_at}}async function us(e){if([e.strictRead,e.noTruncate,Pt()].includes(!0))return null;let t=await qt(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]);return t?Wt({pmRoot:e.pmRoot,expectedSourceCursor:t.source_cursor,paths:e.paths,scope:e.scope,limit:e.limit,offset:e.offset}):null}async function ms(e){let t=[],i=(await Ht(e.pmRoot,e.settings.item_format,e.typeToFolder,t,e.settings.schema)).map(o=>({item:o,files:(o.files??[]).filter(a=>e.paths.includes(H(a.path))&&(e.scope===void 0||a.scope===e.scope)).sort((a,c)=>{let l=a.path.localeCompare(c.path);return l===0?a.scope.localeCompare(c.scope):l})})).filter(o=>o.files.length>0).sort((o,a)=>{let c=o.item.priority-a.item.priority;if(c!==0)return c;let l=a.item.updated_at.localeCompare(o.item.updated_at);return l===0?o.item.id.localeCompare(a.item.id):l}),r=t.filter(o=>/^item_list_(?:item|directory)_read_failed:/u.test(o));if(e.strictRead&&r.length>0)throw new y(`Files lookup could not read every item: ${r.join("; ")}`,g.GENERIC_FAILURE);let s=i.slice(e.offset,e.limit===void 0?void 0:e.offset+e.limit);return{paths:e.paths,total:i.length,count:s.length,offset:e.offset,limit:e.limit??null,has_more:e.offset+s.length<i.length,truncated:e.offset+s.length<i.length,completeness:{status:r.length===0?"complete":"partial",source:"source_scan"},warnings:t,matches:s.map(o=>({item:Zn(o.item),files:o.files}))}}async function Mc(e,t){let n=B(process.cwd(),t.path),i=le(n);if(!await L(O(n)))throw new y(`Tracker is not initialized at ${n}. Run pm init first.`,g.NOT_FOUND);let r=await ls(e.paths,i),s=await $(n),o=z(s,q()),{offset:a,limit:c}=ds(e),l=await us({pmRoot:n,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0,noTruncate:e.noTruncate===!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:Zn(d.item),files:d.files}))}:ms({pmRoot:n,settings:s,typeToFolder:o.type_to_folder,paths:r,scope:e.scope,limit:c,offset:a,strictRead:e.strictRead===!0})}async function Oc(e,t,n){let i=B(process.cwd(),n.path),r=le(i);if(!await L(O(i)))throw new y(`Tracker is not initialized at ${i}. Run pm init first.`,g.NOT_FOUND);let s=await $(i),o=z(s,q()),a=await ve(i,e,s.id_prefix,s.item_format,o.type_to_folder);if(!a)throw new y(`Item ${e} not found`,g.NOT_FOUND);let c=await be(a,{schema:s.schema}),l=await cs(c.document,r,process.cwd()),d=l.filter(b=>b.status==="addable"),u=l.filter(b=>b.status==="already_linked"),m=t.apply===!0,f=t.note?.trim()||"discovered from item text";if(!m||d.length===0){let b=c.document.metadata.files??[];return{id:a.id,files:b,changed:!1,apply:m,count:b.length,candidate_count:l.length,addable_count:d.length,added_count:0,skipped_existing_count:u.length,candidates:l,added:[],skipped_existing:u}}let w=ne(t.author,s.author_default),p=d.map(b=>({path:b.path,scope:b.scope,note:f})),_=[],h=new Set,v=await Ee({pmRoot:i,settings:s,id:e,op:"files_discover",author:w,message:t.message??"Discover referenced file links",force:t.force,mutate(b){let A=[...b.metadata.files??[]],U=new Set(A.map(R=>ae(R,r)));_=[],h.clear();for(let[R,te]of p.entries()){let Z=ae(te,r);U.has(Z)||(A.push(te),U.add(Z),_.push(te),h.add(R))}let T=ot(A),k=t.appendStable?T:st(T);return k.length>0?b.metadata.files=k:delete b.metadata.files,{changedFields:_.length>0?["files"]:[],warnings:_.length!==p.length?[`files_discover_skipped_existing:${p.length-_.length}`]:[]}}}),E=v.item.files??[],S=new Set(_.map(b=>ae(b,r))),I=E.filter(b=>S.has(ae(b,r))),W=d.filter((b,A)=>!h.has(A)),j=[...u,...W];return{id:v.item.id,files:E,changed:I.length>0,apply:!0,count:E.length,candidate_count:l.length,addable_count:d.length,added_count:I.length,skipped_existing_count:j.length,candidates:l,added:I,skipped_existing:j}}(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]="8c4d45cf-6b97-5151-a325-db09d31962a7")}catch{}})();var fs=new Set(["get","history","restore","update","close","delete","append","claim","release","comments","notes","learnings","files","docs","deps","test"]),ct=new Set(["--pm-path","--path","--author"]),ps={get:new Set(["--depth","--fields","--tree-depth","--tree_depth","--at","--format"]),history:new Set(["--limit","--field","--format"]),restore:new Set(["--message"]),update:new Set(["--title","-t","--description","-d","--body","-b","--status","-s","--close-reason","--close_reason","--priority","-p","--type","--tags","--add-tags","--add_tags","--remove-tags","--remove_tags","--deadline","--estimated-minutes","--estimate","--estimated_minutes","--acceptance-criteria","--ac","--acceptance_criteria","--definition-of-ready","--definition_of_ready","--order","--rank","--goal","--objective","--value","--impact","--outcome","--why-now","--why_now","--message","--assignee","--parent","--reviewer","--risk","--confidence","--sprint","--release","--blocked-by","--blocked_by","--blocked-reason","--blocked_reason","--unblock-note","--unblock_note","--reporter","--severity","--environment","--repro-steps","--repro_steps","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual","--affected-version","--affected_version","--fixed-version","--fixed_version","--component","--regression","--customer-impact","--customer_impact","--dep","--dep-remove","--dep_remove","--comment","--note","--learning","--file","--test","--doc","--reminder","--event","--type-option","--type_option","--field","--unset","--body-file"]),close:new Set(["--reason","-r","--close-reason","--duplicate-of","-d","--message","-m","--validate-close","--resolution","--expected-result","--expected_result","--expected","--actual-result","--actual_result","--actual"]),delete:new Set(["--message"]),append:new Set(["--body","--text","--message"]),claim:new Set(["--assignee","--message","--type","--tag","--priority","--assignee-filter","--parent","--sprint","--release","--max-attempts"]),release:new Set(["--assignee","--message"]),comments:new Set(["--add","--body","--comment","--file","--edit","--delete","--limit","--message"]),notes:new Set(["--add","--file","--edit","--delete","--limit","--message"]),learnings:new Set(["--add","--file","--edit","--delete","--limit","--message"]),files:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),docs:new Set(["--add","--add-glob","--remove","--migrate","--note","--message"]),deps:new Set(["--format","--max-depth","--collapse","--node-limit","--edge-limit","--token-budget","--cursor","--direction","--kind"]),test:new Set(["--add","--add-json","--remove","--match","--only-index","--timeout","--env-set","--env-clear","--pm-context","--message"])},_s=new Set(["-p","--package"]),hs=new Set(["-c","--call"]),gs=new Set(["-c","-C","--config","--dir","--filter","--workspace-dir"]),ys=new Set(["-C","--prefix","--userconfig","--cache"]),jc=new Set(["--cwd"]),Uc=new Set(["--cwd"]),ws=new Set(["exec","x"]),zc=new Set(["run","run-script"]),Bc=new Set(["-C","--dir","--cwd","-w","--workspace","--filter"]);function ks(e){return e.split(/&&|\|\||\||;/).map(t=>t.trim()).filter(t=>t.length>0)}function vs(e){let t=bs(e.split(" ").filter(s=>s.length>0));if(t.length===0)return null;let[n,...i]=t;if(Qn(n)||ei(n))return i;if(n==="node"&&i[0]&&ei(i[0]))return i.slice(1);let r=n==="npx"||n==="bunx"?lt(i):n==="pnpm"?Is(i):n==="npm"?Rs(i):null;return r&&(Qn(r.command)||Ss(r.command))?r.args:null}var ti=(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 s=e.trim().replaceAll("\\","/").replaceAll('"',"").replaceAll("'","").replaceAll(/\s+/g," ").toLowerCase(),o=new Set;for(let a of ks(s)){let c=vs(a),l=c?xs(c):null,d=l&&fs.has(l.subcommand)?Cs(l.remaining,ps[l.subcommand]):void 0,u=d?.trim().toLowerCase();u?.startsWith(`${r}-`)===!0&&u.length>r.length+1&&o.add(d)}return[...o].sort((a,c)=>a.localeCompare(c))};function bs(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 Gc(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ct.has(n)){t+=2;continue}t+=1;continue}return n}}function Qn(e){return e==="pm"||e==="pm.cmd"||e==="pm.exe"||e.endsWith("/pm")||e.endsWith("/pm.cmd")||e.endsWith("/pm.exe")}function Es(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 Ss(e){let t=Es(e);return t==="pm-cli"||t.endsWith("/pm-cli")||e==="pm-cli"||e.endsWith("/pm-cli")}function ei(e){return e==="dist/cli.js"||e==="./dist/cli.js"||e.endsWith("/dist/cli.js")}function lt(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 s=r[1];return s?{command:s,args:e.slice(t+1)}:null}if(hs.has(i)){t+=1;break}t+=_s.has(i)&&!i.includes("=")?2:1}let n=e[t];return n?{command:n,args:e.slice(t+1)}:null}function ni(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 Is(e){let t=ni(e,gs);return t?.subcommand!=="dlx"?null:lt(t.args)}function Rs(e){let t=ni(e,ys);return!t||!ws.has(t.subcommand)?null:lt(t.args)}function xs(e){let t=0;for(;t<e.length;){let n=e[t];if(n==="--"){t+=1;continue}if(n.startsWith("-")){if(ct.has(n)){t+=2;continue}t+=1;continue}return{subcommand:n,remaining:e.slice(t+1)}}return null}function Cs(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("=")&&(ct.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]="f8048210-9e9f-585b-b0df-a34eca521cc3")}catch{}})();var Fs=["src","tests","docs"],Ls=["README.md","PRD.md","CHANGELOG.md","AGENTS.md","CONTRIBUTING.md","SECURITY.md","CODE_OF_CONDUCT.md","LICENSE"],$s=new Set(["node_modules",".git",".cursor",".agents","dist","coverage"]),Ds=["resolution","expected_result","actual_result"],Ms=["default","tracked-all","tracked-all-strict"],ii=["core","strict","custom"],Le=["off","warn","error"];var ut=["author","acceptance_criteria","estimated_minutes","close_reason"],ci=[...ut,"reviewer","risk","confidence","sprint","release"],_t=Array.from(new Set(ci)),Os={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"},Ns={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"},js={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"},Us={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"},zs={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"},Bs=32*1024*1024,Gs=1e4,li=40,V=5,Ws=4096,qs=255,Hs=Ps(Ts);function di(e){let t={};for(let[n,i]of Object.entries(e))Array.isArray(i)||(t[n]=typeof i=="object"&&i!==null?di(i):i);return t}function Ks(e){return{...e,checks:e.checks.map(t=>({...t,details:di(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 ee(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/^\/+/,"")}function ri(e){return ee(e).replace(/\/+$/,"")}function N(e){let t=P(e);if(!t)return;let n=t.toLowerCase();if(!(n==="none"||n==="null"||n==="n/a"||n==="na"))return t}function De(e,t){return Mt(e,t)??e}function we(e,t){return t.terminal_statuses.has(De(e,t))}function J(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Fe(e,t){return e.length!==t.length?!1:e.every((n,i)=>n===t[i])}function Vs(e){let t=J(vt),n={blocked_reason:J(ke.blocked_reason),resolution:J(ke.resolution),actual_result:J(ke.actual_result)},i=J(e.validation.lifecycle_stale_blocker_reason_patterns),r={blocked_reason:J(e.validation.lifecycle_closure_like_blocked_reason_patterns),resolution:J(e.validation.lifecycle_closure_like_resolution_patterns),actual_result:J(e.validation.lifecycle_closure_like_actual_result_patterns)};return{stale_blocker_reason_patterns:i,stale_blocker_reason_pattern_source:Fe(i,t)?"default":"settings",closure_like_metadata_field_patterns:r,closure_like_metadata_field_pattern_sources:{blocked_reason:Fe(r.blocked_reason,n.blocked_reason)?"default":"settings",resolution:Fe(r.resolution,n.resolution)?"default":"settings",actual_result:Fe(r.actual_result,n.actual_result)?"default":"settings"}}}function ui(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"core";if(ii.includes(t))return t;throw new y(`Unknown --metadata-profile value "${e}". Supported values: ${ii.join(", ")}.`,g.USAGE)}function mi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Le.includes(t))return t;throw new y(`Unknown --dependency-cycle-severity value "${e}". Supported values: ${Le.join(", ")}.`,g.USAGE)}function fi(e){let t=e?.trim().toLowerCase();if(!t||t.length===0)return"warn";if(Le.includes(t))return t;throw new y(`Unknown --parent-cycle-severity value "${e}". Supported values: ${Le.join(", ")}.`,g.USAGE)}function Ys(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].map(n=>Os[n]).filter(n=>n!==void 0).sort((n,i)=>n.localeCompare(i))}function Js(e,t,n){let i=Ys(n);return e==="core"?{profile:e,profile_source:t,required_fields:[...ut],configured_custom_fields:i,fallback_to_core:!1,warnings:[]}:e==="strict"?{profile:e,profile_source:t,required_fields:[...ci],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:[...ut],configured_custom_fields:i,fallback_to_core:!0,warnings:["validate_metadata_custom_profile_missing_required_fields:0"]}}var Xs=new Set(["acceptance_criteria","estimated_minutes"]);function pi(e,t,n,i){return!i&&Xs.has(t)&&we(e.status,n)?!1:t==="author"?!P(e.author):t==="acceptance_criteria"?!P(e.acceptance_criteria):t==="estimated_minutes"?!Number.isFinite(e.estimated_minutes):t==="close_reason"?De(e.status,n)===n.close_status&&!P(e.close_reason):t==="reviewer"?!P(e.reviewer):t==="risk"?!P(e.risk):t==="confidence"?typeof e.confidence=="number"?!Number.isFinite(e.confidence):!P(e.confidence):t==="sprint"?!P(e.sprint):!P(e.release)}function _i(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 y(`Unknown --scan-mode value "${e}". Supported values: ${Ms.join(", ")}.`,g.USAGE)}function hi(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim();if(t)return F.resolve(t);let n=F.resolve(e);if(n.replaceAll("\\","/").endsWith("/.agents/pm"))return F.dirname(F.dirname(n));let r=F.resolve(process.cwd()),s=si(n),o=si(r),a=F.relative(s,o);return a.length===0||!a.startsWith("..")&&!F.isAbsolute(a)?n:r}function si(e){try{return As.native(e)}catch{return F.resolve(e)}}function gi(e,t){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"&&t.includes(e.code)}async function ht(e,t,n){let i=t.length>0?F.join(e,t):e,r;try{r=await pt.readdir(i,{withFileTypes:!0})}catch(s){if(gi(s,["ENOENT"]))return;throw s}for(let s of r){if(s.name.startsWith("."))continue;let o=t.length>0?F.join(t,s.name):s.name;if(s.isDirectory()){if($s.has(s.name))continue;await ht(e,o,n);continue}s.isFile()&&n.push(ee(o))}}async function mt(e){let t=[];for(let n of Fs)await ht(e,n,t);for(let n of Ls){let i=F.join(e,n);try{(await pt.stat(i)).isFile()&&t.push(ee(n))}catch{}}return[...new Set(t)].sort((n,i)=>n.localeCompare(i))}async function yi(e){try{let{stdout:t}=await Hs("git",["ls-files","-z"],{cwd:e,encoding:"utf8",maxBuffer:Bs,windowsHide:!0,timeout:Gs}),n=t.split("\0").map(i=>ee(i)).filter(i=>i.length>0);return[...new Set(n)].sort((i,r)=>i.localeCompare(r))}catch{return null}}function Zs(e,t){let n=new Set,i=ri(kt);i.length>0&&n.add(i);let r=ri(F.relative(t,e));return r.length>0&&!r.startsWith("..")&&n.add(r),[...n].sort((s,o)=>s.localeCompare(o))}function oi(e,t){for(let n of t)if(e===n||e.startsWith(`${n}/`))return!0;return!1}async function Qs(e,t){if(t==="tracked-all"||t==="tracked-all-strict"){let i=await yi(e);if(i)return{requestedMode:t,appliedMode:t,source:"tracked-git",candidateFiles:i,candidateTotal:i.length,candidateScanned:i.length};let r=await mt(e);return{requestedMode:t,appliedMode:"default",source:"tracked-all-fallback-default",candidateFiles:r,candidateTotal:r.length,candidateScanned:r.length}}let n=await mt(e);return{requestedMode:t,appliedMode:"default",source:"default-curated",candidateFiles:n,candidateTotal:n.length,candidateScanned:n.length}}function C(e,t=V){return e.length<=t?{values:e,truncated:!1}:{values:e.slice(0,t),truncated:!0}}function X(e,t){if(t)return{values:e,truncated:!1,total:e.length};let n=C(e,li);return{values:n.values,truncated:n.truncated,total:e.length}}var eo={resolution:"--resolution",expected_result:"--expected-result",actual_result:"--actual-result"},to={resolution:"Describe how this item was resolved",expected_result:"Describe the expected result",actual_result:"Describe the actual result"};function no(e){let t=e.missing_fields.map(n=>`${eo[n]} "${to[n]}"`).join(" ");return`pm update ${e.id} ${t} --message "Backfill resolution metadata"`}function wi(e,t){let n=e.details?.missing_resolution_remediation_hints,i=Array.isArray(n)&&n.length>0,r=i?n.filter(o=>typeof o=="string"):gn(t);if(r.length===0)return;let s=i&&e.details?.missing_resolution_remediation_hints_truncated===!0;e.details={...e.details,fix_hints:r,...s?{fix_hints_truncated:!0}:{}}}function ki(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 io="validate_metadata_duplicate_issue_codes";function vi(e,t){if(e.length===0)return{rows:[],truncated:!1,warnings:[]};let n=t?e.length:V,i=e.slice(0,n);return{rows:i.map(s=>({code:s.code,count:s.count,ids:s.ids,titles:s.titles,remediation_hint:`Items ${s.ids.join(", ")} share issue code "${s.code}"; rename or merge so each logical code maps to one item.`})),truncated:i.length<e.length,warnings:[`${io}:${e.length}`]}}function ro(){return Object.fromEntries(_t.map(e=>[e,[]]))}function so(e,t,n){let i=ro();for(let r of e)for(let s of _t)pi(r,s,t,n)&&i[s].push(r.id);return i}function oo(e,t,n){let i=[...e.warnings];for(let r of e.required_fields){let s=t[r];s.length>0&&i.push(`${Ns[r]}:${s.length}`)}return i.push(...n),i}function bi(e,t){let n={};for(let i of e.required_fields){let r=t[i],s=r?r.length:0,o=js[i];s>0&&o&&(n[o]=s)}return n}function Ei(e,t,n){let i=[];for(let r of e.required_fields){let s=t[r];if(s)for(let o of s){let a=n.get(o)?.type,c=typeof a=="string"&&a.length>0?a:"Unknown";i.push({item_type:c,field:r})}}return i}function ao(e,t,n,i){for(let r of t.required_fields){let s=n[r];if(!s||s.length===0)continue;let o=Us[r],a=zs[r];if(!o||!a)continue;let c=C(s,i?s.length:V);e[o]=c.values,e[a]=c.truncated}}function Si(e,t,n){if(!e.required_fields.includes("close_reason"))return[];let i=t.close_reason;return i?i.map(r=>({id:r,resolution:P(n.get(r)?.resolution)})):[]}function Ii(e,t,n){if(!e.required_fields.includes("estimated_minutes"))return[];let i=t.estimated_minutes;return i?i.map(r=>({id:r,type:P(n.get(r)?.type)})):[]}function co(e,t,n,i){let r=new Map(e.map(_=>[_.id,_])),s=t.profile==="strict",o=so(e,n,s),a=Dn(e),c=vi(a,i),l=oo(t,o,c.warnings),d=bi(t,o),u=Ei(t,o,r),m=Mn(u),f={checked_items:e.length,metadata_profile:t.profile,metadata_profile_source:t.profile_source,metadata_profile_fallback_to_core:t.fallback_to_core,required_fields:[...t.required_fields],supported_required_fields:[..._t],counts:d,missing_by_type:m,duplicate_issue_codes_count:a.length,duplicate_issue_codes:c.rows,duplicate_issue_codes_truncated:c.truncated};t.configured_custom_fields.length>0&&(f.configured_custom_required_fields=[...t.configured_custom_fields]),ao(f,t,o,i);let w=Si(t,o,r),p=Ii(t,o,r);return{check:{name:"metadata",status:l.length===0?"ok":"warn",details:f},warnings:l,closeReasonBackfillRows:w,estimateBackfillRows:p}}function lo(e,t,n){let i=new Set(t.terminal_done_statuses);i.add(t.close_status);let r=e.filter(m=>i.has(De(m.status,t))),s=[],o=[];for(let m of r){let f=Ds.filter(w=>!P(m[w]));f.length!==0&&(s.push({id:m.id,missing_fields:f}),o.push({id:m.id,missing_fields:f,close_reason:P(m.close_reason)}))}let a=s.length>0?[`validate_resolution_missing_fields:${s.length}`]:[],c=n?Number.POSITIVE_INFINITY:V,l=C(s.map(m=>`${m.id}:${m.missing_fields.join(",")}`),c),d=s.map(m=>no(m)),u=C(d,c);return{check:{name:"resolution",status:a.length===0?"ok":"warn",details:{checked_closed_items:r.length,missing_resolution_items:s.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:o}}function Ri(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function xi(e,t="pm",n=je()){let i=new Set(e.map(s=>s.id)),r=[...e].sort((s,o)=>s.id.localeCompare(o.id));return new Map(r.map(s=>{let o=new Set,a=N(s.blocked_by);a&&i.has(a)&&o.add(a),(s.dependencies??[]).filter(l=>{let d=N(l.kind);return d!==void 0&&n.resolve(d)?.ordering===!0}).map(l=>N(l.id)).filter(l=>l!==void 0&&i.has(l)).forEach(l=>o.add(l));let c=N(s.definition_of_ready);return Ai(c??"",t).filter(l=>i.has(l)).forEach(l=>o.add(l)),[s.id,[...o].sort((l,d)=>l.localeCompare(d))]}))}function Ci(e,t,n){let i=Xt(e,n?d=>we(d,n):void 0),r=i.active.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}`),s=i.legacy_terminal.map(d=>`${d.holder_id}:${d.target_id}:${d.kind}:${d.holder_status}`),o=t?Number.POSITIVE_INFINITY:V,a=C(r,o),c=C(s,o),l=C(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>'`),o);return{check:{name:"dependency_references",status:r.length===0?"ok":"warn",details:{checked_items:e.length,dangling_reference_count:r.length+s.length,active_dangling_reference_count:r.length,dangling_reference_rows:a.values,dangling_reference_rows_truncated:a.truncated,legacy_terminal_dangling_reference_count:s.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 Ai(e,t="pm"){let n=(t.trim().toLowerCase()||"pm").replace(/-+$/g,""),i=new RegExp(`(?:^|[^a-z0-9-])(${Ri(n)}-[a-z0-9][a-z0-9-]*)`,"gi");return[...new Set([...e.matchAll(i)].map(r=>r[1].toLowerCase()))].sort((r,s)=>r.localeCompare(s))}function gt(e){let t=0,n=new Map,i=new Map,r=[],s=new Set,o=[],a=d=>{n.set(d,t),i.set(d,t),t+=1,r.push(d),s.add(d);for(let m of e.get(d)??[])n.has(m)?s.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(s.delete(m),u.push(m),m===d)break}u.sort((m,f)=>m.localeCompare(f)),o.push(u)},c=[...e.keys()].sort((d,u)=>d.localeCompare(u));for(let d of c)n.has(d)||a(d);return o.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 yt(e,t){let n=e[0];if(e.length===1)return[n,n];let i=new Set(e),r=[n],s=new Set([n]),o=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(!s.has(l)){if(s.add(l),r.push(l),o(l))return!0;r.pop(),s.delete(l)}}return!1};return o(n)?[...r]:[...e,n]}function Ti(e,t="pm"){let n=xi(e,t),i=gt(n),r=[...new Set(i.flat())].sort((o,a)=>o.localeCompare(a)),s=i.map(o=>yt(o,n).join("->"));return{cycle_count:i.length,cycle_item_ids:r,cycle_sample_paths:s}}function Pi(e,t=je()){let n=new Map(e.map(s=>[s.id.toLowerCase(),s.id])),i=new Map(e.map(s=>[s.id,[]]));return[...e].sort((s,o)=>s.id.localeCompare(o.id)).forEach(s=>{let o=i.get(s.id),a=N(s.parent),c=a?n.get(a.toLowerCase()):void 0;c&&o.push(c),(s.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(s.id):o.push(u))})}),i.forEach((s,o)=>{i.set(o,[...new Set(s)].sort((a,c)=>a.localeCompare(c)))}),i}function Fi(e){let t=Pi(e),n=gt(t),i=[...new Set(n.flat())].sort((s,o)=>s.localeCompare(o)),r=n.map(s=>yt(s,t).join("->"));return{cycle_count:n.length,cycle_item_ids:i,cycle_sample_paths:r}}function Li(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 $e(e){let t=e.lastIndexOf("/");return t===-1?"":e.slice(0,t)}function $i(e,t){let n=$e(e).split("/").filter(Boolean),i=$e(t).split("/").filter(Boolean),r=0;for(;r<n.length&&r<i.length&&n[r]===i[r];)r+=1;return r}function uo(e,t){let n=$e(t),i=$e(e),r=t.endsWith("/")?t:`${t}/`,s=e.startsWith(r),o=n.length>0&&n===i,a=$i(e,t);return!s&&!o&&a===0?null:s?{score:t.length+1e3,confidence:"path_prefix"}:o?{score:a+500,confidence:"same_directory"}:{score:a,confidence:"shared_directory"}}function mo(e,t,n){return e===void 0||n>e.score||n===e.score&&t.id.localeCompare(e.item.id)<0}function fo(e,t,n){let i=t==="docs_unowned"?"docs":"files",r;return n.flatMap(s=>(i==="docs"?s.docs??[]:s.files??[]).map(o=>({item:s,link:o}))).forEach(({item:s,link:o})=>{if(o.scope!=="project")return;let a=ee(o.path);if(a.length===0||a===e)return;let c=uo(e,a);c!==null&&mo(r,s,c.score)&&(r={item:s,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 Di(e,t){return e.map(n=>{let i=Li(n),r=i==="docs_unowned"?"docs":"files",s=fo(n,i,t),o=s?.id??"<id>";return{path:n,classification:i,owner_candidate:s,remediation_hint:`pm ${r} ${o} --add path=${n},scope=project,note="<why this artifact belongs to the item>"`}})}function Mi(e){return e.map(t=>`${t.path}:${t.classification} owner_candidate=${t.owner_candidate?.id??"unowned"} hint=${JSON.stringify(t.remediation_hint)}`)}function po(e,t){return Object.entries(t.closure_like_metadata_field_patterns).filter(([n,i])=>{let r=N(e[n]);return r?i.some(s=>r.toLowerCase().includes(s)):!1}).map(([n])=>n).sort((n,i)=>n.localeCompare(i))}function _o(e,t,n,i,r){let s=N(t.parent),o=s?n.get(i.get(s.toLowerCase())??s):void 0;return{id:e.id,parent_id:t.id,grandparent_id:o?.id,grandparent_active:o!==void 0&&!we(o.status,r)}}function ho(e,t,n,i){let r=N(e.blocked_by),s=N(e.blocked_reason),o=s?.toLowerCase(),a=De(e.status,n),c=[];return t.has(a)?(!r&&!s&&c.push("blocked_status_missing_blocker_context"),o?.includes("no active blocker")&&c.push("blocked_status_reason_reports_no_active_blocker"),o&&i.stale_blocker_reason_patterns.some(l=>o.includes(l))&&c.push("blocked_status_reason_matches_stale_pattern"),c):(r&&c.push("non_blocked_status_has_blocked_by"),s&&c.push("non_blocked_status_has_blocked_reason"),c)}function go(e,t,n,i){let r=new Map(e.map(c=>[c.id,c])),s=new Map(e.map(c=>[c.id.toLowerCase(),c.id])),o=n.blocked_statuses.size>0?n.blocked_statuses:new Set(["blocked"]),a={activeItems:e.filter(c=>!we(c.status,n)),closureLikeRows:[],terminalParentRows:[],terminalParentFixRows:[],staleBlockerRows:[]};for(let c of a.activeItems){let l=po(c,i);l.length>0&&a.closureLikeRows.push({id:c.id,fields:l});let d=N(c.parent),u=d?r.get(s.get(d.toLowerCase())??d):void 0;if(u&&we(u.status,n)&&(a.terminalParentRows.push({id:c.id,parent_id:u.id,parent_status:u.status}),a.terminalParentFixRows.push(_o(c,u,r,s,n))),t){let m=ho(c,o,n,i);m.length>0&&a.staleBlockerRows.push({id:c.id,status:c.status,reasons:[...new Set(m)].sort((f,w)=>f.localeCompare(w))})}}return a}function yo(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 ai(e,t,n){return n<=0||t==="off"?null:`${t==="error"?`${e}_error`:e}:${n}`}function wo(e,t,n,i,r,s){let o=[];e.closureLikeRows.length>0&&o.push(`validate_lifecycle_active_closure_like_metadata:${e.closureLikeRows.length}`),e.terminalParentRows.length>0&&o.push(`validate_lifecycle_active_terminal_parent:${e.terminalParentRows.length}`),t&&e.staleBlockerRows.length>0&&o.push(`validate_lifecycle_stale_blockers:${e.staleBlockerRows.length}`);let a=ai("validate_lifecycle_dependency_cycles",n,r),c=ai("validate_hierarchy_parent_cycle",i,s);return[...o,...a?[a]:[],...c?[c]:[]]}function Oi(e){let t=ee(e);return t.length>Ws||t.split(/[\\/]/).some(n=>n.length>qs)}async function ko(e,t){let n=F.isAbsolute(t)?t:F.resolve(e,t);if(Oi(n))return!1;try{let i=await pt.stat(n);return!i.isFile()&&!i.isDirectory()}catch(i){return gi(i,["ENOENT","ENOTDIR"])}}async function vo(e,t){let n={linkedProjectPaths:new Set,remoteLinkedPaths:new Set,missingLinkedPaths:[],staleLinkRows:[]},i=e.flatMap(r=>[...(r.files??[]).map(s=>({item:r,artifact:s,link_kind:"files"})),...(r.docs??[]).map(s=>({item:r,artifact:s,link_kind:"docs"}))]);for(let{item:r,artifact:s,link_kind:o}of i){if(s.scope!=="project")continue;if(ye(s.path)){n.remoteLinkedPaths.add(s.path.trim());continue}let a=ee(s.path);a.length!==0&&(n.linkedProjectPaths.add(a),await ko(t,s.path)&&(n.missingLinkedPaths.push(a),n.staleLinkRows.push({item_id:r.id,path:a,link_kind:o})))}return n}function bo(e,t,n,i,r,s){let o=i==="tracked-all-strict",a=o&&!r,c=r||o,l=c?[]:Zs(t,n),d=l.length===0?[]:e.candidateFiles.filter(f=>oi(f,l)),u=l.length===0?e.candidateFiles:e.candidateFiles.filter(f=>!oi(f,l)),m={};if(d.length>0){let f=X(d,s);m.pm_internals={count:d.length,paths:f.values,paths_truncated:f.truncated,paths_total:f.total}}return{strictTrackedAllMode:o,strictModeForcesPmInternals:a,includePmInternalsEffective:c,pmInternalCandidatePrefixes:l,excludedPmInternalPaths:d,candidateFiles:u,excludedByReason:m}}function Ni(e,t,n,i,r,s,o,a="pm"){let c=go(e,t,r,s);yo(c);let l=Ti(c.activeItems,a),d=Fi(e),u=wo(c,t,n,i,l.cycle_count,d.cycle_count),m=o?Number.POSITIVE_INFINITY:V,f=C(c.closureLikeRows.map(I=>`${I.id}:${I.fields.join(",")}`),m),w=C(c.terminalParentRows.map(I=>`${I.id}:${I.parent_id}:${I.parent_status}`),m),p=C(c.staleBlockerRows.map(I=>`${I.id}:${I.status}:${I.reasons.join(",")}`),m),_=C(l.cycle_item_ids,m),h=C(l.cycle_sample_paths,m),v=C(d.cycle_item_ids,m),E=C(d.cycle_sample_paths,m);return{check:{name:"lifecycle",status:l.cycle_count>0&&n==="error"||d.cycle_count>0&&i==="error"?"error":u.length===0?"ok":"warn",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:w.values,active_terminal_parent_rows_truncated:w.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:_.values,dependency_cycle_item_ids_truncated:_.truncated,dependency_cycle_sample_paths:h.values,dependency_cycle_sample_paths_truncated:h.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:E.values,parent_cycle_sample_paths_truncated:E.truncated,stale_blocker_reason_patterns:[...s.stale_blocker_reason_patterns],stale_blocker_reason_pattern_source:s.stale_blocker_reason_pattern_source,closure_like_blocked_reason_patterns:[...s.closure_like_metadata_field_patterns.blocked_reason],closure_like_blocked_reason_pattern_source:s.closure_like_metadata_field_pattern_sources.blocked_reason,closure_like_resolution_patterns:[...s.closure_like_metadata_field_patterns.resolution],closure_like_resolution_pattern_source:s.closure_like_metadata_field_pattern_sources.resolution,closure_like_actual_result_patterns:[...s.closure_like_metadata_field_patterns.actual_result],closure_like_actual_result_pattern_source:s.closure_like_metadata_field_pattern_sources.actual_result}},warnings:u,terminalParentFixRows:c.terminalParentFixRows}}async function ji(e,t,n,i,r,s){let o=await vo(e,t),a=new Map(e.map(k=>[k.id,k])),c=[...new Set(o.missingLinkedPaths)].sort((k,R)=>k.localeCompare(R)),l=await Qs(t,i),d=bo(l,n,t,i,r,s),u=d.candidateFiles.filter(k=>!o.linkedProjectPaths.has(k)),m=Di(u,e),f=jn(c,d.candidateFiles),w=new Map(f.map(k=>[k.path,k.classification])),p=f.filter(k=>k.classification==="moved").length,_=o.staleLinkRows.map(k=>({...k,classification:w.get(k.path)??"deleted"})).sort((k,R)=>k.item_id.localeCompare(R.item_id)||k.path.localeCompare(R.path)||k.link_kind.localeCompare(R.link_kind)),h=[];d.strictModeForcesPmInternals&&h.push("validate_files_tracked_all_strict_forces_pm_internals"),c.length>0&&h.push(`validate_files_missing_linked_paths:${c.length}`),u.length>0&&h.push(`validate_files_orphaned_paths:${u.length}`);let v=[...o.remoteLinkedPaths].sort((k,R)=>k.localeCompare(R)),E=X(v,s),S=X(c,s),I=X(u,s),W=X(m.map(k=>`${k.path}:${k.classification}:owner_candidate=${k.owner_candidate?.id??"unowned"}`),s),j=s?m:X(Mi(m),!1).values,b=X(Un(f),s),A=_.map(k=>({item_id:k.item_id,path:k.path,link_kind:k.link_kind,classification:k.classification})),U=Bn(A,k=>{let R=a.get(k);return R?{type:R.type,title:R.title,status:R.status}:void 0}),T=s?U:X(Gn(U),!1).values;return{check:{name:"files",status:h.length===0?"ok":"warn",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:s?"full":"summary",file_list_summary_limit:li,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:o.linkedProjectPaths.size,remote_linked_paths_count:v.length,remote_linked_paths_total:E.total,remote_linked_paths:E.values,remote_linked_paths_truncated:E.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:b.values,missing_linked_path_classifications_truncated:b.truncated,missing_linked_path_rows_count:U.length,missing_linked_path_rows:T,orphaned_paths_count:u.length,orphaned_paths_total:I.total,orphaned_paths:I.values,orphaned_paths_truncated:I.truncated,orphaned_path_classifications:W.values,orphaned_path_classifications_truncated:W.truncated,orphaned_path_rows_count:m.length,orphaned_path_rows:j}},warnings:h,staleLinkPruneRows:_}}async function Eo(e,t,n){let{missingStreams:i,unreadableStreams:r,hashMismatches:s,chainMismatches:o,driftedItems:a}=await In(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}`),s.length>0&&c.push(`validate_history_drift_hash_mismatches:${s.length}`),o.length>0&&c.push(`validate_history_drift_chain_mismatches:${o.length}`);let l=n?Number.POSITIVE_INFINITY:V,d=C(a,l);return{check:{name:"history_drift",status:c.length===0?"ok":"warn",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:s.length,chain_mismatches:o.length}}},warnings:c}}function So(e,t,n){let i=n.trim().replaceAll(/\s+/g," "),r=i.length>120?`${i.slice(0,117)}...`:i;return`${e}:${t}:${r}`}function Ui(e,t,n){let i=new Set(e.map(_=>_.id.toLowerCase())),r=0,s=0,o=new Set,a=[],c=e.flatMap(_=>(_.tests??[]).map(h=>({item:_,linkedTest:h})));for(let{item:_,linkedTest:h}of c){if(typeof h.command!="string"||h.command.trim().length===0)continue;r+=1;let v=ti(h.command,t);if(v.length!==0){s+=v.length;for(let E of v)o.add(E),i.has(E.toLowerCase())||a.push(So(_.id,E,h.command))}}let l=[...new Set(a)].sort((_,h)=>_.localeCompare(h)),d=[...new Set(l.map(_=>_.split(":")[1]??""))].filter(_=>_.length>0).sort((_,h)=>_.localeCompare(h)),u=l.length>0?[`validate_command_references_stale_pm_ids:${l.length}`]:[],m=n?Number.POSITIVE_INFINITY:V,f=C(l,m),w=C(d,m),p=C([...o].sort((_,h)=>_.localeCompare(h)),m);return{check:{name:"command_references",status:u.length===0?"ok":"warn",details:{checked_items:e.length,linked_commands_scanned:r,referenced_pm_ids_count:s,unique_referenced_pm_ids_count:o.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:w.values,stale_pm_ids_truncated:w.truncated,stale_pm_id_reference_rows:f.values,stale_pm_id_reference_rows_truncated:f.truncated}},warnings:u}}function Io(e,t){let n=Dt(e.map(c=>({ref:c.id,version:$t(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:V,s=C(n.outdated,r),o=C(n.ahead,r);return{check:{name:"format_version",status:n.ahead.length>0?"error":n.outdated.length>0?"warn":"ok",details:{checked_items:e.length,current_format_version:Lt,outdated_items_count:n.outdated.length,outdated_items:s.values,outdated_items_truncated:s.truncated,ahead_items_count:n.ahead.length,ahead_items:o.values,ahead_items_truncated:o.truncated}},warnings:i}}var ft="pm validate auto-fix";async function zi(e,t,n){switch(e.kind){case"set_resolution":case"set_close_reason":case"set_estimate":case"reparent":case"unset_parent":{let i={message:ft};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 y("Applying validate metadata/lifecycle fixes requires a runUpdate mutation service.",g.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 Bi(e,t,n){let i=[],r=[],s=new Map;for(let o of e.filter(a=>dt(a)===null))try{await zi(o,t,n),i.push(o)}catch(a){r.push({fix:o,error:a})}for(let o of e.filter(a=>dt(a)!==null)){let a=dt(o),c=s.get(a);c?c.push(o):s.set(a,[o])}for(let o of s.values()){let a=o[0];if(!a)continue;let c=o.map(l=>l.path).filter(l=>typeof l=="string"&&l.length>0);try{a.kind==="prune_file_link"?await Xn(a.item_id,{remove:c,message:ft},t):await Yn(a.item_id,{remove:c,message:ft},t),i.push(...o)}catch(l){r.push(...o.map(d=>({fix:d,error:l})))}}return{applied:i,failed:r}}var Al={applyValidateFix:zi,applyValidateFixes:Bi,attachValidateFixHints:wi,buildCommandReferencesCheck:Ui,buildDependencyReferencesCheck:Ci,buildCloseReasonBackfillRows:Si,buildFilesCheck:ji,buildLifecycleCheck:Ni,buildLifecycleDependencyGraph:xi,buildLifecycleParentGraph:Pi,buildEstimateBackfillRows:Ii,buildMetadataCounts:bi,buildMissingFieldOccurrences:Ei,buildOrphanedPathRows:Di,classifyOrphanedPath:Li,collectDefaultProjectFileCandidates:mt,collectTrackedGitFileCandidates:yi,detectLifecycleDependencyCycles:Ti,detectLifecycleParentCycles:Fi,escapeRegExp:Ri,extractItemIds:Ai,findLifecycleDependencyCycleComponents:gt,isMetadataFieldMissing:pi,linkedArtifactPathExceedsFilesystemLimits:Oi,listFilesRecursive:ht,resolveDependencyCycleSeverity:mi,resolveParentCycleSeverity:fi,resolveFileScanMode:_i,resolveLifecycleDependencyCycleSamplePath:yt,resolveRequestedChecks:ki,resolveValidateMetadataProfile:ui,resolveWorkspaceRoot:hi,sharedDirectoryPrefixLength:$i,summarizeOrphanedPathRows:Mi,summarizeDuplicateIssueCodes:vi,toMeaningfulString:N};async function Ro(e,t,n,i){let r=await hn(e,new Set(t.map(m=>m.id)),n,{schema:i.schema,extensionFieldNames:bt(q())}),s=[];r.unreadable_item_files.length>0&&s.push(`validate_storage_unreadable_items:${r.unreadable_item_files.length}`),r.duplicate_item_ids.length>0&&s.push(`validate_storage_duplicate_item_ids:${r.duplicate_item_ids.length}`),r.history_conflict_marker_streams.length>0&&s.push(`validate_storage_history_conflict_markers:${r.history_conflict_marker_streams.length}`),r.history_unparseable_streams.length>0&&s.push(`validate_storage_unparseable_history:${r.history_unparseable_streams.length}`),r.resurrected_items.length>0&&s.push(`validate_storage_resurrected_items:${r.resurrected_items.length}`),r.unparseable_config_files.length>0&&s.push(`validate_storage_unparseable_config:${r.unparseable_config_files.length}`);let o=s.length,a=await qn(e);a.tracked_path_count>0&&s.push(`validate_storage_tracked_runtime_cache_files:${a.tracked_path_count}`);let c=await ln(e,Ie(i));c.status==="drift"&&s.push(`validate_merge_fence_drift:${c.missing_patterns.length+c.stale_patterns.length}`);let l=await pe(e),d=l===null?null:await dn(l);d!==null&&d.status!=="ok"&&s.push(`validate_merge_driver_configuration:${d.missing_keys.length+d.drifted_keys.length}`);let u=l===null?[]:await Ze(l);return u.length>0&&s.push(`validate_merge_decisions_unreviewed:${u.length}`),{check:{name:"storage_integrity",status:o>0?"error":s.length>0?"warn":"ok",details:{...r,merge_fence:c,merge_driver_configuration:d,pending_merge_decision_count:u.length,pending_merge_decision_items:[...new Set(u.map(m=>m.item_id))].sort((m,f)=>m.localeCompare(f)),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:s}}function K(e,t,n){n&&wi(t.check,t.warnings),e.checks.push(t.check),e.warnings.push(...t.warnings)}async function xo(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=co(e.items,e.metadataPolicy,e.statusRegistry,i);t.closeReasonBackfillRows=r.closeReasonBackfillRows,t.estimateBackfillRows=r.estimateBackfillRows,K(t,r,n)}if(e.requestedChecks.has("resolution")){let r=lo(e.items,e.statusRegistry,i);t.resolutionBackfillRows=r.resolutionBackfillRows,K(t,r,n)}if(e.requestedChecks.has("lifecycle")){let r=Ni(e.items,!!e.options.checkStaleBlockers,e.dependencyCycleSeverity,e.parentCycleSeverity,e.statusRegistry,e.lifecyclePatternPolicy,i,e.settings.id_prefix);t.terminalParentFixRows=r.terminalParentFixRows,K(t,r,n),K(t,Ci(e.items,i,e.statusRegistry),n)}if(e.requestedChecks.has("files")){let r=await ji(e.items,e.workspaceRoot,e.pmRoot,e.fileScanMode,!!e.options.includePmInternals,!!e.options.verboseFileLists);t.staleLinkPruneRows=r.staleLinkPruneRows,K(t,r,n)}return e.requestedChecks.has("command_references")&&K(t,Ui(e.items,e.settings.id_prefix,i),n),e.requestedChecks.has("history_drift")&&K(t,await Eo(e.pmRoot,e.items,i),n),e.requestedChecks.has("format_version")&&K(t,Io(e.items,i),n),e.requestedChecks.has("storage_integrity")&&K(t,await Ro(e.pmRoot,e.items,z(e.settings,q()).type_to_folder,e.settings),n),t}function Co(e,t,n){let i=[];return e.autoFix===!0&&(i.push(...Cn(t.closeReasonBackfillRows)),i.push(...xn(t.resolutionBackfillRows)),i.push(...An(t.estimateBackfillRows,n.validation.estimate_defaults_by_type)),i.push(...Tn(t.terminalParentFixRows))),e.pruneMissing===!0&&i.push(...Pn(t.staleLinkPruneRows)),i}async function Ao(e,t,n,i,r,s){if(e.autoFix!==!0&&e.pruneMissing!==!0)return;let o=Co(e,t,n),{applicable:a,gated:c}=Ln(o,i),l=e.dryRun===!0,d=[],u=[];if(!l){let m=await Bi(a,r,s);d.push(...m.applied.map(ge)),u.push(...m.failed.map(({fix:f,error:w})=>({...ge(f),error:w instanceof Error?w.message:String(w)})))}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:o.length,applied_count:d.length,gated_count:c.length,failed_count:u.length,planned_fixes:o.map(ge),applied_fixes:d,gated_fixes:c.map(m=>({...ge(m),gate_hint:`Withheld: re-run with --fix-scope ${m.gate} to apply.`})),failed_fixes:u}}async function Tl(e,t,n={}){Tt(e.counts===!0,e.full===!0,"--counts");let i=e.autoFix===!0||e.pruneMissing===!0;if(e.dryRun===!0&&!i)throw new y("--dry-run requires --auto-fix or --prune-missing (there is nothing to preview otherwise).",g.USAGE);if(e.fixScope!==void 0&&e.fixScope.length>0&&e.autoFix!==!0)throw new y("--fix-scope requires --auto-fix.",g.USAGE);let r=Fn(e.fixScope),s=B(process.cwd(),t.path);if(!await L(O(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,g.NOT_FOUND);let o=await $(s),a=At(o.schema),c=z(o,q()),l=[],d=await Kt(s,o.item_format,c.type_to_folder,l,o.schema),u=ki(e);if(u.has("history_drift")){let A=await Je(s);A.actionable_unknown_event_count>0&&l.push(`validate_history_unknown_author_events:${A.actionable_unknown_event_count}`)}let m=typeof e.metadataProfile=="string"?"option":"settings",f=ui(typeof e.metadataProfile=="string"?e.metadataProfile:o.validation.metadata_profile),w=Js(f,m,o.validation.metadata_required_fields),p=Vs(o),_=mi(e.dependencyCycleSeverity),h=fi(e.parentCycleSeverity),v=_i(e.scanMode),E=hi(s),S=await xo({requestedChecks:u,options:e,global:t,pmRoot:s,workspaceRoot:E,settings:o,items:d,statusRegistry:a,metadataPolicy:w,lifecyclePatternPolicy:p,dependencyCycleSeverity:_,parentCycleSeverity:h,fileScanMode:v,initialWarnings:[...new Set(l)]}),I=i?await Ao(e,S,o,r,t,n):void 0,W=[...new Set(S.warnings)].sort((A,U)=>A.localeCompare(U)),b={ok:!S.checks.some(A=>A.status==="error"),has_warnings:W.length>0,checks:S.checks,warnings:W,...I!==void 0?{fixes:I}:{},generated_at:Y(),projection:{mode:"full",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:["diagnostic_rows"]}};return e.counts!==!0?b:{...Ks(b),projection:{mode:"counts",declared_field_groups:[{name:"diagnostic_rows",restore_with:"--full"}],included_field_groups:[]}}}export{$o as a,Q as b,fe as c,pe as d,Ye as e,Ie as f,ln as g,dn as h,Xo as i,Zo as j,Zi as k,In as l,_r as m,Qi as n,mn as o,oa as p,Je as q,aa as r,qn as s,ga as t,ya as u,Ze as v,wa as w,ka as x,hn as y,Yn as z,Xn as A,Mc as B,Oc as C,gs as D,ys as E,jc as F,Uc as G,zc as H,Bc as I,ks as J,vs as K,bs as L,Gc as M,Qn as N,Ss as O,ei as P,lt as Q,ni as R,Is as S,Rs as T,xs as U,Ks as V,Al as W,Tl as X};
|
|
14
|
+
//# sourceMappingURL=chunk-DQ6FKGL3.js.map
|