@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,2 +1,2 @@
|
|
|
1
|
-
import{b as I,d as T,e as x,h as H}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{b as I,d as T,e as x,h as H}from"./chunk-PD3225AM.js";import{A as c,Ad as y,C as f,Da as l,La as p,Nf as E,Oa as u,b as h,hf as _,if as w,lc as g,pf as b,tf as v}from"./chunk-D4FPS43D.js";(function(){try{var t=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},r=new t.Error().stack;r&&(t._sentryDebugIds=t._sentryDebugIds||{},t._sentryDebugIds[r]="bccbd81b-988f-569d-8dbf-c0998d813953")}catch{}})();function G(t,r){let n=v(t),i=t.length>0?t[t.length-1].after_hash:w(),o=r===void 0?void 0:_(r),d=o===void 0?void 0:o===i,e=[...n.errors];return d===!1&&e.push("verify_failed:current_item_hash_mismatch"),{ok:e.length===0,entries:t.length,errors:e,latest_after_hash:t.length>0?t[t.length-1].after_hash:void 0,current_item_hash:o,current_matches_latest:d}}async function X(t,r,n={}){let i=p(n.cwd??process.cwd(),n.pmRoot);if(!await h(u(i)))throw new f(`Tracker is not initialized at ${i}. Run pm init first.`,c.NOT_FOUND);let o=await E(i),d=l(o,g()),e=await H(i,t,o,d.type_to_folder),s=await y(e.historyPath,e.id);if(s.length===0)throw new f(`No history exists for ${e.id}; point-in-time reads are unavailable.`,c.NOT_FOUND);let a=I(r,s),R=x(T(s,a.historyIndex),a),m=b(R,{schema:o.schema});if(m.metadata.id!==e.id)throw new f(`History target resolved to item ${m.metadata.id}, expected ${e.id}.`,c.GENERIC_FAILURE);let D=s[a.historyIndex];return{document:m,reconstructed:!0,as_of_version:a.historyIndex+1,as_of_timestamp:D.ts,target:a,history_length:s.length}}export{G as a,X as b};
|
|
2
|
+
//# sourceMappingURL=chunk-B4KLBBMN.js.map
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{s as ut}from"./chunk-
|
|
2
|
-
`)}function gn(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function X(e){return Object.assign(Object.create(null),e)}function wn(e,t){try{let o=JSON.stringify(e,(n,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(o)}catch(o){throw new TypeError(`${t} must be JSON serializable`,{cause:o})}}function Fe(e,t){return e===void 0?void 0:wn(e,t)}function Pe(e,t,o,n){let r=Fe(o,n);r===void 0?delete e[t]:e[t]=r}function yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gt(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(o=>typeof o=="string"&&t.includes(o))}function _n(e,t){if(!gt(e.startedStepIds,t)||!gt(e.completedStepIds,t)||!yt(e.results)||!yt(e.compensationData))return!1;let o=e.startedStepIds,n=new Set(o),r=e.completedStepIds,i=new Set(r);return Object.keys(e.compensationData).some(s=>!n.has(s))||Object.keys(e.results).some(s=>!i.has(s))?!1:e.status==="committed"?t.every(s=>i.has(s)):e.status!=="compensated"||i.size===0&&n.size===0}function Sn(e,t,o){let n;try{n=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=n,i=r.schemaVersion===1&&r.transactionId===t,s=Array.isArray(r.stepIds)&&r.stepIds.length===o.length&&r.stepIds.every((f,d)=>f===o[d]),a=_n(r,o),c=gn(r),l=["applying","compensating","compensated","committed"].includes(String(r.status));if(!i||!s||!a||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:X(r.results),compensationData:X(r.compensationData)}}async function kn(e,t,o,n,r){let i=r,s=i!==void 0;if(i?.status==="compensating"&&await St(e,i),i===void 0||i.status==="compensated"){let a=k();i={schemaVersion:1,transactionId:t,author:o,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??a,updatedAt:a,stepIds:n,startedStepIds:[],completedStepIds:[],results:X(),compensationData:X()},await
|
|
1
|
+
import{s as ut}from"./chunk-NFLJ3FHD.js";import{a as rt,b as pe,c as me,d as it,e as st,f as z,g as _e,h as at,i as J}from"./chunk-KZ4X3DGU.js";import{$f as Z,A as h,Ba as et,Bf as Re,C as y,Ca as tt,Da as x,Ef as ot,H as Xe,Hc as P,Ic as nt,Jc as v,Kc as M,Kf as N,La as A,Nc as ue,Nf as b,O as Ve,Oa as ne,Pc as we,Pf as ct,R as k,Vf as lt,Yf as dt,Z as Qe,Zf as ft,b as j,c as I,d as Y,da as Ie,dg as ve,ea as Ae,fa as xe,lc as R,uc as D,v as Ze,yf as F,zd as C}from"./chunk-D4FPS43D.js";import{mkdir as fn,readFile as un}from"node:fs/promises";import wt 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]="d49ec604-c10c-5706-9d87-510845e55e1a")}catch{}})();var Ce=class extends Error{constructor(t="Workspace transaction interrupted"){super(t),this.name="WorkspaceTransactionInterruptedError"}},pn="sdk-workspace-transaction",mn=/^[a-zA-Z0-9._-]+$/,hn=30,yn=3e3;function pt(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let o=e.trim();if(!o||!mn.test(o))throw new TypeError(`${t} must match [a-zA-Z0-9._-]+`);return o}function mt(e,t){if(typeof e!="string")throw new TypeError(`${t} must be a string`);let o=e.trim();if(!o)throw new TypeError(`${t} must be non-empty`);return o}function ht(e,t,o){let n=e??t;if(!Number.isInteger(n)||n<=0)throw new TypeError(`${o} must be a positive integer`);return n}function _t(e,t){return wt.join(e,"transactions","sdk",`${t}.json`)}async function H(e,t){t.updatedAt=k();let o=_t(e,t.transactionId);await fn(wt.dirname(o),{recursive:!0}),await Y(o,`${JSON.stringify(t,null,2)}
|
|
2
|
+
`)}function gn(e){return Number.isInteger(e.attempt)&&typeof e.author=="string"&&typeof e.createdAt=="string"&&typeof e.updatedAt=="string"}function X(e){return Object.assign(Object.create(null),e)}function wn(e,t){try{let o=JSON.stringify(e,(n,r)=>{if(typeof r=="number"&&!Number.isFinite(r))throw new TypeError(`${t} contains a non-finite number`);if(r===void 0||typeof r=="function"||typeof r=="symbol")throw new TypeError(`${t} contains a non-JSON value`);return r});return JSON.parse(o)}catch(o){throw new TypeError(`${t} must be JSON serializable`,{cause:o})}}function Fe(e,t){return e===void 0?void 0:wn(e,t)}function Pe(e,t,o,n){let r=Fe(o,n);r===void 0?delete e[t]:e[t]=r}function yt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function gt(e,t){return Array.isArray(e)&&new Set(e).size===e.length&&e.every(o=>typeof o=="string"&&t.includes(o))}function _n(e,t){if(!gt(e.startedStepIds,t)||!gt(e.completedStepIds,t)||!yt(e.results)||!yt(e.compensationData))return!1;let o=e.startedStepIds,n=new Set(o),r=e.completedStepIds,i=new Set(r);return Object.keys(e.compensationData).some(s=>!n.has(s))||Object.keys(e.results).some(s=>!i.has(s))?!1:e.status==="committed"?t.every(s=>i.has(s)):e.status!=="compensated"||i.size===0&&n.size===0}function Sn(e,t,o){let n;try{n=JSON.parse(e)}catch{throw new TypeError(`Workspace transaction ${t} journal is invalid JSON`)}if(!n||typeof n!="object"||Array.isArray(n))throw new TypeError(`Workspace transaction ${t} journal is invalid`);let r=n,i=r.schemaVersion===1&&r.transactionId===t,s=Array.isArray(r.stepIds)&&r.stepIds.length===o.length&&r.stepIds.every((f,d)=>f===o[d]),a=_n(r,o),c=gn(r),l=["applying","compensating","compensated","committed"].includes(String(r.status));if(!i||!s||!a||!c||!l)throw new TypeError(`Workspace transaction ${t} journal does not match the supplied plan`);return{...r,results:X(r.results),compensationData:X(r.compensationData)}}async function kn(e,t,o,n,r){let i=r,s=i!==void 0;if(i?.status==="compensating"&&await St(e,i),i===void 0||i.status==="compensated"){let a=k();i={schemaVersion:1,transactionId:t,author:o,status:"applying",attempt:(i?.attempt??0)+1,createdAt:i?.createdAt??a,updatedAt:a,stepIds:n,startedStepIds:[],completedStepIds:[],results:X(),compensationData:X()},await H(e.pmRoot,i),await G(e,i,"prepared")}return{journal:i,recovered:s}}async function bn(e,t,o){try{await Tn(t,e.steps),await H(e.pmRoot,t);let n=new Set(t.completedStepIds),r=new Set(t.startedStepIds);for(let i of e.steps){if(n.has(i.id))continue;let s=await i.inspect(),a=Fe(s.result,`Step ${i.id} result`);if(s.state!=="applied"){let c=await i.prepareCompensation?.();Pe(t.compensationData,i.id,c,`Step ${i.id} compensation data`),r.add(i.id),t.startedStepIds=e.steps.map(f=>f.id).filter(f=>r.has(f)),await H(e.pmRoot,t);let l=await i.apply();a=Fe(l,`Step ${i.id} result`)}await G(e,t,"step_applied",i.id),n.add(i.id),t.completedStepIds=e.steps.map(c=>c.id).filter(c=>n.has(c)),Pe(t.results,i.id,a,`Step ${i.id} result`),await H(e.pmRoot,t),await G(e,t,"step_recorded",i.id)}return await G(e,t,"committing"),t.status="committed",await H(e.pmRoot,t),await G(e,t,"committed"),{transactionId:t.transactionId,status:"committed",recovered:o,results:X(t.results)}}catch(n){if(n instanceof Ce||t.status==="committed")throw n;try{await St(e,t)}catch(r){throw new AggregateError([n,r],`Workspace transaction failed and compensation failed: ${String(r)}`,{cause:r})}throw n}}async function En(e,t,o){try{return Sn(await un(_t(e,t),"utf8"),t,o)}catch(n){if(n!==null&&typeof n=="object"&&"code"in n&&n.code==="ENOENT")return;throw n}}async function G(e,t,o,n){await e.onTransition?.({transactionId:t.transactionId,attempt:t.attempt,transition:o,...n===void 0?{}:{stepId:n}})}async function Tn(e,t){let o=new Set,n=X();for(let r of t){let i=await r.inspect();i.state==="applied"&&(o.add(r.id),Pe(n,r.id,i.result,`Step ${r.id} result`))}e.results=n,e.completedStepIds=t.map(r=>r.id).filter(r=>o.has(r))}async function St(e,t){t.status="compensating",await H(e.pmRoot,t),await G(e,t,"compensating");let o=new Set(t.completedStepIds),n=new Set(t.startedStepIds);for(let r of[...e.steps].reverse()){if(!n.has(r.id)&&!o.has(r.id))continue;let i;try{i=n.has(r.id)&&(await r.inspect()).state==="applied"}catch{i=n.has(r.id)}i&&(await G(e,t,"step_compensating",r.id),await r.compensate(t.compensationData[r.id])),o.delete(r.id),n.delete(r.id),t.completedStepIds=e.steps.map(s=>s.id).filter(s=>o.has(s)),t.startedStepIds=e.steps.map(s=>s.id).filter(s=>n.has(s)),delete t.results[r.id],delete t.compensationData[r.id],await H(e.pmRoot,t),await G(e,t,"step_compensated",r.id)}t.status="compensated",await H(e.pmRoot,t),await G(e,t,"compensated")}async function kt(e){let t=mt(e.pmRoot,"Transaction pmRoot"),o=pt(e.transactionId,"Transaction id"),n=mt(e.author,"Transaction author"),r=ht(e.lockTtlSeconds,hn,"Transaction lock TTL"),i=ht(e.lockWaitMs,yn,"Transaction lock wait"),s=[...e.steps];if(s.length===0)throw new TypeError("Workspace transaction requires at least one step");let a=s.map(f=>{let d=pt(f.id,"Transaction step id");if(d!==f.id)throw new TypeError("Transaction step id must not contain surrounding whitespace");return d});if(new Set(a).size!==a.length)throw new TypeError("Workspace transaction step ids must be unique");let c={...e,pmRoot:t,transactionId:o,author:n,steps:s,lockTtlSeconds:r,lockWaitMs:i},l=await F(t,pn,r,n,!1,!1,i);try{let f=await En(t,o,a),d=f!==void 0;if(f?.status==="committed")return{transactionId:o,status:"committed",recovered:!0,results:X(f.results)};let g=await kn(c,o,n,a,f);return await bn(c,g.journal,d||g.recovered)}finally{await l()}}import{readFile as $n,writeFile as In}from"node:fs/promises";import he from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="bbfa5b19-d801-582a-98e8-0c4925dd57c0")}catch{}})();var Et="# pm-cli:runtime-cache:start",Oe="# pm-cli:runtime-cache:end",Tt=".agents/pm",An=["runtime/","search/","locks/","transactions/","checkpoints/"],xn=["search/eval-queries.json"];async function bt(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.",h.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 $t(e){return e.replaceAll("\\","/").replace(/^\.\/+/,"").replace(/\/+$/,"")}function Ne(e){let t=e.replaceAll("\\","/");return he.isAbsolute(e)||t===".."||t.startsWith("../")}function Rn(e=Tt){let t=$t(e);return[Et,...An.map(o=>o==="search/"?`${t}/${o}*`:`${t}/${o}`),...xn.map(o=>`!${t}/${o}`),Oe].join(`
|
|
3
3
|
`)}async function Yo(e,t={}){let o=he.join(e,".gitignore"),n=Tt;if(t.pmRoot!==void 0){let f=$t(he.relative(he.resolve(e),he.resolve(t.pmRoot)));if(Ne(f))return{path:o,changed:!1};f.length>0&&(n=f)}let r="";try{r=await bt(()=>$n(o,"utf8"))}catch(f){if(!(f instanceof Error&&"code"in f&&f.code==="ENOENT"))throw f}let i=r.indexOf(Et),s=r.indexOf(Oe),c=(i>=0&&s>=i?`${r.slice(0,i)}${r.slice(s+Oe.length)}`:r).trimEnd(),l=`${c.length>0?`${c}
|
|
4
4
|
|
|
5
|
-
`:""}${
|
|
6
|
-
`;return l===r?{path:o,changed:!1}:(await bt(()=>In(o,l,"utf8")),{path:o,changed:!0})}import{readFile as Se,realpath as Le,writeFile as
|
|
5
|
+
`:""}${Rn(n)}
|
|
6
|
+
`;return l===r?{path:o,changed:!1}:(await bt(()=>In(o,l,"utf8")),{path:o,changed:!0})}import{readFile as Se,realpath as Le,writeFile as vn}from"node:fs/promises";import{execFile as Cn}from"node:child_process";import S from"node:path";import{promisify as Fn}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]="a250384a-0279-5d01-ade4-f64be3119ed9")}catch{}})();var De=Fn(Cn),V="# pm-cli:merge-drivers:start",ye="# pm-cli:merge-drivers:end",Pn="merge-fence";function It(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function xt(){let e=Qe(import.meta.url,["../../.."]);return`${It(process.execPath)} ${It(S.join(e,"dist","cli.js"))}`}var Rt=[{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 On(e){try{let{stdout:t}=await De("git",["rev-parse","--show-toplevel"],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4});return await Le(t.trim())}catch{return null}}async function vt(e){let t=await On(e);if(t===null)throw new y("pm merge install requires a git repository (merge drivers are git configuration).",h.USAGE);return t}function Me(e,t){return S.relative(e,t).replaceAll("\\","/")}function U(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function At(e,t){if(e[t]!=="'")return null;let o="";for(let n=t+1;n<e.length;n+=1){if(e.startsWith(`'"'"'`,n)){o+="'",n+=4;continue}if(e[n]==="'")return{value:o,nextOffset:n+1};o+=e[n]}return null}async function Nn(e,t){let o=At(e,0);if(o===null||e[o.nextOffset]!==" ")return!1;let n=At(e,o.nextOffset+1);if(n===null||e.slice(n.nextOffset)!==t||!/^node(?:\.exe)?$/iu.test(S.basename(o.value))||S.basename(n.value)!=="cli.js"||S.basename(S.dirname(n.value))!=="dist"||!await j(o.value)||!await j(n.value))return!1;try{let r=S.dirname(S.dirname(n.value)),i=JSON.parse(await Se(S.join(r,"package.json"),"utf8")),s=typeof i.bin=="object"&&i.bin!==null&&"pm"in i.bin?i.bin.pm:void 0;return i.name==="@unbrained/pm-cli"&&(i.bin==="dist/cli.js"||s==="dist/cli.js")}catch{return!1}}function Ue(e,t){let o=e.length>0?`${e}/`:"",n=[`${U(`${o}**/*.toon`)} merge=pm-item-toon`,`${U(`${o}**/*.md`)} merge=pm-item-markdown`];for(let r of t)n.push(`${U(`${o}${r}/*.toon`)} merge=pm-item-toon`),n.push(`${U(`${o}${r}/*.md`)} merge=pm-item-markdown`);return n.push(`${U(`${o}**/*.jsonl`)} merge=pm-relationship`),n.push(`${U(`${o}history/*.jsonl`)} merge=pm-history`),n.push(`${U(`${o}settings.json`)} merge=pm-json`),n.push(`${U(`${o}**/*.json`)} merge=pm-json`),n.push(`${U(`${o}extensions/**`)} -merge`),n.push(`${U(`${o}extensions/.managed-extensions.json`)} merge=pm-json`),n}async function Ct(e,t,o){let n=S.join(e,".gitattributes"),r="";try{r=await Se(n,"utf8")}catch(d){if(!(d instanceof Error&&"code"in d&&d.code==="ENOENT"))throw d}let i=[V,...t,ye].join(`
|
|
7
7
|
`),s=r.indexOf(V),a=r.indexOf(ye),l=(s>=0&&a>s?`${r.slice(0,s)}${r.slice(a+ye.length)}`:r.replace(V,"").replace(ye,"")).trimEnd(),f=`${l.length>0?`${l}
|
|
8
8
|
|
|
9
9
|
`:""}${i}
|
|
10
|
-
`;return f===r?{path:n,changed:!1}:(o||await
|
|
11
|
-
`).map(p=>p.trim()).filter(p=>p.length>0):[],f=Ue(Me(n,o),t),d=new Set(l),g=new Set(f),m=f.filter(p=>!d.has(p)),u=l.filter(p=>!g.has(p));return{status:m.length>0||u.length>0?"drift":"ok",path:s,missing_patterns:m,stale_patterns:u,schema_scope:"project"}}async function pr(e){let t=
|
|
10
|
+
`;return f===r?{path:n,changed:!1}:(o||await vn(n,f,"utf8"),{path:n,changed:!0})}function Ft(e){let t=x(e,null);return[...new Set(Object.values(t.type_to_folder))].sort((o,n)=>o.localeCompare(n))}async function ur(e,t){let o=S.resolve(e),n=null,r="",i=o;for(let p=0;p<8;p+=1){let w=S.join(i,".gitattributes");try{let _=await Se(w,"utf8");if(_.includes(V)){n=i,r=_;break}}catch{}let E=S.dirname(i);if(E===i)break;i=E}if(n===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let s=S.join(n,".gitattributes"),a=r.indexOf(V),c=r.indexOf(ye),l=c>a?r.slice(a+V.length,c).split(`
|
|
11
|
+
`).map(p=>p.trim()).filter(p=>p.length>0):[],f=Ue(Me(n,o),t),d=new Set(l),g=new Set(f),m=f.filter(p=>!d.has(p)),u=l.filter(p=>!g.has(p));return{status:m.length>0||u.length>0?"drift":"ok",path:s,missing_patterns:m,stale_patterns:u,schema_scope:"project"}}async function pr(e){let t=xt(),o=[],n=[];for(let r of Rt){let i=`merge.${r.key}.driver`,s=` merge driver ${r.artifact} "%O" "%A" "%B"${r.itemPath===void 0?"":` --item-path ${r.itemPath}`}`,a=`${t}${s}`;try{let{stdout:c}=await De("git",["config","--local","--get",i],{cwd:e,encoding:"utf8",windowsHide:!0,timeout:1e4}),l=c.trim();l!==a&&!await Nn(l,s)&&n.push(i)}catch{o.push(i)}}return{status:o.length>0?"missing":n.length>0?"drift":"ok",missing_keys:o,drifted_keys:n}}async function Pt(e){let t;try{t=await vt(S.resolve(e))}catch{return{status:"no_git"}}let o=Me(t,S.resolve(e)),n=await b(e),r=C(void 0,n.author_default),i=await F(e,Pn,n.locks.ttl_seconds,r,!1,N(n).force_required_for_stale_lock,n.locks.wait_ms);try{let s=S.join(t,".gitattributes"),a;try{a=await Se(s,"utf8")}catch(d){if(d instanceof Error&&"code"in d&&d.code==="ENOENT")return{status:"not_installed",path:s};throw d}if(!a.includes(V))return{status:"not_installed",path:s};let c=await b(e),l=Ft(c),f=await Ct(t,Ue(o,l),!1);return{status:f.changed?"refreshed":"unchanged",path:f.path}}finally{await i()}}async function mr(e,t){let o=t.path?.trim(),n=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim(),r=process.env.PM_SOURCE_PM_PATH?.trim(),i=o===void 0&&n!==void 0&&n.length>0&&r!==void 0&&r.length>0,s=o!==void 0?A(process.cwd(),o):i?S.resolve(r):A(process.cwd());if(!await j(ne(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,h.NOT_FOUND);let a=await vt(o!==void 0?s:i?S.resolve(n):process.cwd());return Ln({pmRoot:s,workspaceRoot:a,dryRun:e.dryRun===!0})}async function Ln(e){let t=S.resolve(e.pmRoot),o=S.resolve(e.workspaceRoot),n=e.dryRun===!0,r,i;try{[r,i]=await Promise.all([Le(t),Le(o)])}catch(m){throw new y(`Cannot resolve tracker root ${t} or workspace root ${o}: ${String(m)}`,h.NOT_FOUND,{code:"merge_root_not_found",nextSteps:["Initialize the tracker and ensure both paths are accessible.",'Retry "pm merge install" from the repository workspace.']})}let s=Me(i,r);if(Ne(s))throw new y(`Tracker root ${t} is outside the git repository ${o}; there is nothing to configure for this repository.`,h.USAGE);let a=await b(r),c=Ft(a),l=Ue(s,c),f=[],d=xt();for(let m of Rt)f.push({key:`merge.${m.key}.name`,value:m.name}),f.push({key:`merge.${m.key}.driver`,value:`${d} merge driver ${m.artifact} "%O" "%A" "%B"${m.itemPath===void 0?"":` --item-path ${m.itemPath}`}`});if(!n)try{for(let m of f)await De("git",["config","--local",m.key,m.value],{cwd:i,encoding:"utf8",windowsHide:!0,timeout:1e4})}catch{throw new y(`Cannot install repository-local merge drivers in ${i}. Ensure the repository Git config is writable and no other Git process holds its lock, then retry.`,h.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 g=await Ct(i,l,n);return{ok:!0,dry_run:n,workspace_root:i,pm_root:r,gitattributes:{path:g.path,changed:g.changed,patterns:l,schema_scope:"project"},git_config:f,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:k()}}import{createHash as Kt}from"node:crypto";import ee from"node:fs/promises";import le 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]="79b35844-ab8e-5b6f-9975-4dd85b210bcb")}catch{}})();var Dn=new Set(Ae),Mn=new Set(xe),Ot=new Set([...Ze.filter(e=>e!=="severity"),"id","title","type","status","priority","tags","assignee","parent","description","body","created_at","updated_at","closed_at","completed_at","author","deadline","estimate","sprint","release","risk","confidence","reviewer","resolution","expected","actual"]),Un=["create","update"];function L(e){return typeof e=="string"?e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_"):""}function Mt(e){if(typeof e!="string")return"";let t=e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-");return t.startsWith("--")?t.slice(2):t}function Nt(e){return e.replaceAll("_","-")}function jn(e,t){let o=new Set;for(let n of e){let r=Mt(n);r.length>0&&r!==t&&o.add(r)}return[...o].sort((n,r)=>n.localeCompare(r))}function zn(e){let t=new Set;for(let o of e??[]){let n=o.trim();n.length>0&&t.add(n)}return[...t].sort((o,n)=>o.localeCompare(n))}function Gn(e){let t=new Set,o=[];for(let n of e??[]){let r=n.trim().toLowerCase();if(r.length!==0){if(!Mn.has(r))throw new Error(`Invalid field command "${n}". Allowed: ${xe.join(", ")}.`);t.has(r)||(t.add(r),o.push(r))}}return e===void 0||o.length===0?[...Un]:o}function Ut(e){let t=L(e.key);if(t.length===0)throw new Error("Field key must not be empty.");if(Ot.has(t))throw new Error(`Cannot define custom field "${t}": custom schema field "${t}" collides with built-in item metadata "${t}". Rename the custom field with a project-specific prefix. Reserved fields: ${[...Ot].sort((f,d)=>f.localeCompare(d)).join(", ")}.`);let o=typeof e.type=="string"&&e.type.trim().length>0?e.type.trim().toLowerCase():"string";if(!Dn.has(o))throw new Error(`Invalid field type "${e.type}". Allowed: ${Ae.join(", ")}.`);let n=o,r=Gn(e.commands),i=Mt(e.cliFlag),s=i.length>0&&i!==Nt(t)?i:void 0,a=s??Nt(t),c=jn(e.aliases??[],a),l=e.description?.trim();return{key:t,type:n,commands:r,description:l&&l.length>0?l:void 0,cliFlag:s,cliAliases:c,required:e.required===!0,requiredOnCreate:e.requiredOnCreate===!0,allowUnset:e.allowUnset!==!1,requiredTypes:zn(e.requiredTypes)}}function qn(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function Jn(e){let t=qn(e);if(!t)return[];let o=[];for(let n of t){if(typeof n!="object"||n===null||Array.isArray(n))continue;let r=n;typeof r.key!="string"||r.key.trim().length===0||o.push(r)}return o}function oe(e){if(e==null||e.trim().length===0)return{fields:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/fields.json contains invalid JSON.")}return{fields:Jn(t)}}function re(e){return`${JSON.stringify({fields:e.fields},null,2)}
|
|
12
12
|
`}function jt(e,t){let o=e.fields.find(s=>L(s.key)===t.key),n=o!==void 0,r=e.fields.filter(s=>L(s.key)!==t.key),i={...o,key:t.key,type:t.type,commands:[...t.commands]};return Lt(i,"description",t.description),Lt(i,"cli_flag",t.cliFlag),t.cliAliases.length>0?i.cli_aliases=[...t.cliAliases]:delete i.cli_aliases,Dt(i,"required",t.required),Dt(i,"required_on_create",t.requiredOnCreate),t.allowUnset===!1?i.allow_unset=!1:delete i.allow_unset,t.requiredTypes.length>0?i.required_types=[...t.requiredTypes]:delete i.required_types,r.push(i),r.sort((s,a)=>L(s.key).localeCompare(L(a.key))),{file:{fields:r},definition:i,replaced:n}}function zt(e,t){let o=L(t);if(o.length===0)throw new Error("Field key must not be empty.");let n=[],r=e.fields.filter(i=>L(i.key)===o?(n.push(i),!1):!0);return n.length===0?{file:{fields:r},removed:!1}:{file:{fields:r},removed:!0,definition:n[0]}}function Lt(e,t,o){let n=e;o!==void 0&&o.length>0?n[t]=o:delete n[t]}function Dt(e,t,o){let n=e;o?n[t]=!0:delete n[t]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f81297bd-06ac-5aa4-9e1b-802fb50c9cd0")}catch{}})();var Hn=new Set(Ie),Wn=2e3,ke=new Map,Q=new Set(nt.map(e=>T(e.id)).filter(e=>e.length>0));function T(e){if(typeof e!="string")return"";let t=ke.get(e);if(t!==void 0)return t;let o=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return ke.size>=Wn&&Ve(ke),ke.set(e,o),o}function Kn(e){let t=new Set;for(let o of e){let n=T(o);n.length>0&&t.add(n)}return[...t].sort((o,n)=>o.localeCompare(n))}function Gt(e){let t=T(e.id);if(t.length===0)throw new Error("Status id must not be empty.");if(Q.has(t))throw new Error(`Cannot add-status the built-in status "${t}". Built-in statuses are reserved: ${[...Q].join(", ")}.`);let o;if(e.roles!==void 0){o=[];let s=new Set;for(let a of e.roles){let c=typeof a=="string"?a.trim().toLowerCase():"";if(c.length!==0){if(!Hn.has(c))throw new Error(`Invalid status role "${a}". Allowed roles: ${Ie.join(", ")}.`);s.has(c)||(s.add(c),o.push(c))}}}let n=e.aliases===void 0?void 0:Kn(e.aliases).filter(s=>s!==t),r=e.description?.trim(),i=typeof e.order=="number"&&Number.isFinite(e.order)?Math.trunc(e.order):void 0;return{id:t,roles:o,aliases:n,description:r&&r.length>0?r:void 0,order:i}}function Bn(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function Yn(e){let t=Bn(e);if(!t)return[];let o=[];for(let n of t){if(typeof n!="object"||n===null||Array.isArray(n))continue;let r=n;typeof r.id!="string"||r.id.trim().length===0||o.push(r)}return o}function ie(e){if(e==null||e.trim().length===0)return{statuses:[]};let t;try{t=JSON.parse(e)}catch{throw new Error("schema/statuses.json contains invalid JSON.")}return{statuses:Yn(t)}}function se(e){return`${JSON.stringify({statuses:e.statuses},null,2)}
|
|
13
|
-
`}function qt(e,t,o){let n=e.statuses.slice(),r=n.findIndex(a=>T(a.id)===t.id),i=r>=0?n[r]:o,s={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?s.roles=[...t.roles]:s.roles!==void 0&&delete s.roles),t.aliases!==void 0&&(t.aliases.length>0?s.aliases=[...t.aliases]:s.aliases!==void 0&&delete s.aliases),t.description!==void 0&&(s.description=t.description),t.order!==void 0&&(s.order=t.order),r>=0?n[r]=s:n.push(s),{file:{statuses:n},definition:s,replaced:i!==void 0}}function Jt(e,t){let o=T(t);if(o.length===0)throw new Error("Status id must not be empty.");if(Q.has(o))throw new Error(`Cannot remove built-in status "${o}". Built-in statuses are reserved: ${[...Q].join(", ")}.`);let n=e.statuses.slice(),r=n.findIndex(s=>T(s.id)===o);if(r<0)return{file:{statuses:n},removed:!1};let[i]=n.splice(r,1);return{file:{statuses:n},removed:!0,definition:i}}function je(e,t){let o=[e.id,...e.aliases??[]];for(let n of o){let r=T(n);if(r.length===0)continue;let i=t.get(r);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${r}" already belongs to status "${i}". Choose a different id/alias to avoid shadowing it.`)}}(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]="c4b4af3b-6ce6-56f7-9665-9e6b2f3d9630")}catch{}})();function ae(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Bt(e){let t=ae(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Yt(e,t){let o=Ge(e),n=ae(t,"migrationScope");return`auto-${Kt("sha256").update(JSON.stringify({scope:n,request:o})).digest("hex").slice(0,20)}`}function Ge(e){let t=n=>ae(n,"source or target").toLowerCase().replaceAll(/[\s-]+/g,"_"),o=e.kind==="rename-type"?{kind:e.kind,from:ae(e.from,"source"),to:ae(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:t(e.from),to:t(e.to),...e.type===void 0?{}:{type:ae(e.type,"type")}}:{kind:e.kind,from:t(e.from),to:t(e.to)};if(o.from.toLowerCase()===o.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return o}function Zn(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Xn(e,t,o){let n=
|
|
14
|
-
`}function Vt(e,t){if(t.kind==="rename-type"){let n=
|
|
15
|
-
`)}function uo(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function po(e){let t=await dt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await ft(t,{schema:e.settings.schema})).document.metadata}function Ht(e,t,o){let n=o==="forward"?t.from:t.to,r=o==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==n.toLowerCase())throw new TypeError(`Schema migration expected type "${n}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==n.toLowerCase())throw new TypeError(`Schema migration expected status "${n}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,r)&&!Object.prototype.hasOwnProperty.call(i,n))return[];if(!Object.prototype.hasOwnProperty.call(i,n)||Object.prototype.hasOwnProperty.call(i,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[r]=i[n],delete i[n],[n,r]}function Wt(e){return{id:e.id,inspect:async()=>{let t=await ce(e.filePath),o=Vt(t.raw,e.request),n=e.phase==="stage"?o.source&&o.target:!o.source&&o.target;return{state:n?"applied":"pending",...n?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await ce(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await ce(e.filePath);return await Y(e.filePath,to(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Xt(e.filePath,{exists:t.exists,raw:t.raw})}}}function mo(e){return{id:e.stepId,inspect:async()=>{let t=await ce(e.filePath);return{state:ze(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await ce(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await ce(e.filePath);return await Y(e.filePath,ze(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Xt(e.filePath,{exists:t.exists,raw:t.raw})}}}function ho(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await b(e.pmRoot),o=
|
|
16
|
-
`)}import Io from"node:path";import{mkdir as Ao}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var Je=["agile","ops","research"],bo={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function en(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${Je.join(", ")}.`)}function He(e){return bo[e].map(t=>me(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var Eo=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function To(e){let t=Eo.exec(e.trim());if(!t)return;let o=t[1];if(!(o.length<2)&&!/^[A-Za-z]\d+$/.test(o))return o.toLowerCase()}function $o(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function tn(e,t={}){let o=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,n=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=To(a);if(c===void 0)continue;let l=r.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<n&&l.examples.push(a),r.set(c,l)}let i=[];for(let[s,a]of r.entries()){if(a.count<o)continue;let c=$o(s);i.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:rt(c)!==void 0})}return i.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var gi=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ee="schema-types",nn="schema-statuses",on="schema-fields";function K(e){return ot({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function wi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{r=me({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(m){throw new y(m instanceof Error?m.message:String(m),h.USAGE)}let i=await b(n),s=x(i.schema),a=M(n,s.files.types,P.types),c=[],l=C(t.author,i.author_default),f=N(i),d=await F(n,Ee,i.locks.ttl_seconds,l,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms),g;try{let m=await I(a),u;try{u=j(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.GENERIC_FAILURE)}try{it(r,u);let p=new Map,w=R(i,v());for(let[E,_]of Object.entries(w.type_to_folder)){let $=_.trim().toLowerCase();$.length>0&&!p.has($)&&p.set($,E)}st(r,u,p)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}g=_e(u,r),g.replaced&&g.previousName!==void 0&&g.previousName!==g.definition.name&&c.push(`type_recased:${g.previousName}->${g.definition.name}`),await K({pmRoot:n,filePath:a,raw:q(g.file),op:"schema:add-type",author:l,settings:i}),await Ke(n,[g.definition],c,"schema:add-type-folder"),c.push(...await D({path:a,scope:"project",op:"schema:add-type"}))}finally{await d()}return await rn(n,c),{action:"add-type",registered:!0,replaced:g.replaced,type:g.definition,file:{path:a,definitions:g.file.definitions.length},warnings:B(c),generated_at:k()}}async function G(e){if(!await U(ne(e)))throw new y(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND)}async function rn(e,t){try{let o=await Pt(e);o.status==="refreshed"?t.push("merge_fence_refreshed"):o.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function B(e){return[...new Set(e)].sort((t,o)=>t.localeCompare(o))}async function Ro(e,t,o,n){let r=R(t,v()),i=n.trim().toLowerCase();return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===i).length}async function vo(e,t,o,n){let r=R(t,v()),i=ue(o),s=T(n);return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(T(l))??T(l))===s}).length}async function xo(e,t,o,n,r){if(r.length===0||Q.has(r))return;let i=await vo(t,o,n,r);i>0&&e.push(`items_using_status:${i}`);let s=sn(n.workflow,r);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function sn(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&T(n)===t).map(([n])=>n)}async function _i(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=x(r.schema),s=M(n,i.files.types,P.types),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,Ee,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=j(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=at(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=(d.definition?.name??e??"").trim();if(u.length>0){let p=await Ro(n,r,i,u);p>0&&a.push(`items_using_type:${p}`)}await K({pmRoot:n,filePath:s,raw:q(d.file),op:"schema:remove-type",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await f()}return d.removed&&await rn(n,a),{action:"remove-type",removed:d.removed,...d.definition?{type:d.definition}:{},file:{path:s,definitions:d.file.definitions.length},warnings:B(a),generated_at:k()}}function We(e,t){return M(e,t.files.statuses,P.statuses)}function Te(e,t){return M(e,t.files.fields,P.fields)}function an(e,t){return M(e,t.files.types,P.types)}async function Ke(e,t,o,n){for(let r of t){let i=tt(r.folder??et(r.name)),s=Io.join(e,i);await U(s)||(await Ao(s,{recursive:!0}),o.push(...await D({path:s,scope:"project",op:n})))}}function Be(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Co(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Fo(e){let t=new Map;for(let o of e){let n=T(o.id);if(n.length!==0){t.set(n,n);for(let r of Array.isArray(o.aliases)?o.aliases:[]){let i=T(r);i.length>0&&!t.has(i)&&t.set(i,n)}}}return t}async function Si(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{r=Gt({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let i=await b(n),s=x(i.schema),a=We(n,s),c=ue(s);try{je(r,c.alias_to_id)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let l=Co(c.by_id.get(r.id)),f=[],d=C(t.author,i.author_default),g=N(i),m=await F(n,nn,i.locks.ttl_seconds,d,!!t.force,g.force_required_for_stale_lock,i.locks.wait_ms),u;try{let p=await I(a),w;try{w=ie(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}let E=Fo(w.statuses);try{je(r,E)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.USAGE)}u=qt(w,r,l),await K({pmRoot:n,filePath:a,raw:se(u.file),op:"schema:add-status",author:d,settings:i}),f.push(...await D({path:a,scope:"project",op:"schema:add-status"}))}finally{await m()}return{action:"add-status",registered:!0,replaced:u.replaced,status:u.definition,file:{path:a,statuses:u.file.statuses.length},warnings:B(f),generated_at:k()}}async function ki(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=x(r.schema),s=We(n,i),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,nn,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=ie(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=Jt(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=T(d.definition?.id??e);await xo(a,n,r,i,u),await K({pmRoot:n,filePath:s,raw:se(d.file),op:"schema:remove-status",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await f()}return{action:"remove-status",removed:d.removed,...d.definition?{status:d.definition}:{},file:{path:s,statuses:d.file.statuses.length},warnings:B(a),generated_at:k()}}function cn(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Po(e,t,o){return{...cn(e),source:t,...o?{extension:o}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function ln(e){return{id:e.id,source:Q.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function dn(e,t,o){let n=e.toLowerCase();return o.has(n)?"extension":t.has(n)?"custom":"builtin"}function Oo(){let e=new Map,t=v();for(let o of t?.item_types??[]){let n=o.types;if(Array.isArray(n))for(let r of n){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:o.layer,name:o.name})}}return e}function No(e){let t=ue(e),o=[],n=[];for(let r of t.definitions){let i=ln(r);i.source==="builtin"?o.push(i):n.push(i)}return{builtin:o,custom:n}}async function ge(e){let t=A(process.cwd(),e.path);await G(t);let o=await b(t),n=x(o.schema),r=M(t,n.files.types,P.types),i=We(t,n),s=R(o,v()),a=Oo(),c=new Set((o.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!a.has(l)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:s.by_type,customNames:c,extensionProvenance:a,schema:n}}async function bi(e){let t=await ge(e),o=[],n=[],r=[];for(let a of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=dn(a.name,t.customNames,new Set(t.extensionProvenance.keys())),l=cn(a);c==="extension"?r.push(l):c==="custom"?n.push(l):o.push(l)}let i=No(t.schema),s=we(t.schema).definitions.map(Be);return{action:"list",builtin:o,custom:n,extension:r,counts:{builtin:o.length,custom:n.length,extension:r.length,total:o.length+n.length+r.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:k()}}async function Ei(e,t){let o=(e??"").trim();if(o.length===0)throw new y("Type name must not be empty.",h.USAGE);let n=await ge(t),r=Object.values(n.byType).find(i=>i.name.toLowerCase()===o.toLowerCase()||i.aliases.some(s=>s.toLowerCase()===o.toLowerCase()));if(!r)throw new y(`Unknown item type "${o}". Run pm schema list to inspect registered types, or pm schema add-type "${pe(o)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Po(r,dn(r.name,n.customNames,new Set(n.extensionProvenance.keys())),n.extensionProvenance.get(r.name.toLowerCase())),file:{path:n.typesPath},generated_at:k()}}async function Ti(e,t){let o=T(e);if(o.length===0)throw new y("Status id must not be empty.",h.USAGE);let n=await ge(t),r=ue(n.schema),i=r.alias_to_id.get(o)??o,s=r.by_id.get(i);if(!s)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ln(s),file:{path:n.statusesPath},generated_at:k()}}async function $i(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{r=Ut({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}let i=await b(n),s=x(i.schema),a=Te(n,s),c=[],l=ut(r.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let f=C(t.author,i.author_default),d=N(i),g=await F(n,on,i.locks.ttl_seconds,f,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),m;try{let u=await I(a),p;try{p=oe(u)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}m=jt(p,r),await K({pmRoot:n,filePath:a,raw:re(m.file),op:"schema:add-field",author:f,settings:i}),c.push(...await D({path:a,scope:"project",op:"schema:add-field"}))}finally{await g()}return{action:"add-field",registered:!0,replaced:m.replaced,field:m.definition,file:{path:a,fields:m.file.fields.length},warnings:B(c),generated_at:k()}}async function Lo(e,t,o,n){let r=R(t,v());return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(s=>{let a=s[n];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function Ii(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=x(r.schema),s=Te(n,i),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,on,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=oe(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=zt(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=L(d.definition?.key??e),p=L(d.definition?.metadata_key??d.definition?.front_matter_key??u);if(p.length>0){let w=await Lo(n,r,i,p);w>0&&a.push(`items_using_field:${w}`)}await K({pmRoot:n,filePath:s,raw:re(d.file),op:"schema:remove-field",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await f()}return{action:"remove-field",removed:d.removed,...d.definition?{field:d.definition}:{},file:{path:s,fields:d.file.fields.length},warnings:B(a),generated_at:k()}}async function Ai(e){let t=await ge(e),o=we(t.schema).definitions.map(Be);return{action:"list-fields",fields:o,counts:{total:o.length},file:{path:Te(t.pmRoot,t.schema)},generated_at:k()}}async function Ri(e,t){let o=L(e);if(o.length===0)throw new y("Field key must not be empty.",h.USAGE);let n=await ge(t),r=we(n.schema).by_key.get(o);if(!r)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Be(r),file:{path:Te(n.pmRoot,n.schema)},generated_at:k()}}async function vi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{let p=en(e);if(p===void 0)throw new Error(`Type preset name is required. Allowed: ${Je.join(", ")}.`);r=p}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let i=await b(n),s=x(i.schema),a=an(n,s),c=[],l=C(t.author,i.author_default),f=N(i),d=[],g=[],m,u=await F(n,Ee,i.locks.ttl_seconds,l,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms);try{let p=await I(a),w;try{w=j(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}let E=w;for(let _ of He(r)){let $=_e(E,_);E=$.file,($.replaced?g:d).push($.definition.name)}m=E.definitions.length,await K({pmRoot:n,filePath:a,raw:q(E),op:"schema:apply-preset",author:l,settings:i}),await Ke(n,He(r),c,"schema:apply-preset-folder"),c.push(...await D({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await u()}return{action:"apply-preset",preset:r,registered:d,replaced:g,file:{path:a,definitions:m},warnings:B(c),generated_at:k()}}function Do(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function xi(e,t){let o=A(process.cwd(),t.path);await G(o);let n=await b(o),r=x(n.schema),i=an(o,r),s=Do(e.minCount),a=R(n,v()),l=(await Z(o,n.item_format,a.type_to_folder,[],r)).map($=>typeof $.title=="string"?$.title:""),f=tn(l,{minCount:s}),d=[],g=[],m=[],u=[],p;if(!e.apply){let $;try{$=j(await I(i))}catch(te){throw new y(te instanceof Error?te.message:String(te),h.GENERIC_FAILURE)}return p=$.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:f,registered:g,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:d,generated_at:k()}}let w=C(e.author,n.author_default),E=N(n),_=await F(o,Ee,n.locks.ttl_seconds,w,!!e.force,E.force_required_for_stale_lock,n.locks.wait_ms);try{let $=await I(i),te;try{te=j($)}catch(O){throw new y(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let fe=te;for(let O of f){if(O.shadows_builtin){u.push({name:O.name,reason:"shadows_builtin"});continue}let Ye;try{Ye=me({name:O.name})}catch{u.push({name:O.name,reason:"invalid_type_token"});continue}let $e=_e(fe,Ye);fe=$e.file,($e.replaced?m:g).push($e.definition.name)}p=fe.definitions.length,await K({pmRoot:o,filePath:i,raw:q(fe),op:"schema:infer-types",author:w,settings:n}),await Ke(o,fe.definitions.filter(O=>g.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await D({path:i,scope:"project",op:"schema:infer-types"}))}finally{await _()}return{action:"infer-types",applied:!0,min_count:s,candidates:f,registered:g,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:B(d),generated_at:k()}}function Ci(e){let t=e.replaced?"Updated":"Registered",o=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${o} in ${e.file.path}. Run: pm create "${pe(e.type.name)}" "<title>"`}function Fi(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function Pi(e){let t=e.replaced?"Updated":"Registered",o=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",n=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${o}${n} in ${e.file.path}.`}function Oi(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Ni(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[o,n]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])n.length!==0&&t.push(`${o}: ${n.map(r=>r.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[o,n]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])n.length!==0&&t.push(`${o}: ${n.map(r=>r.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(o=>`${o.key} (${o.type}, ${o.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
13
|
+
`}function qt(e,t,o){let n=e.statuses.slice(),r=n.findIndex(a=>T(a.id)===t.id),i=r>=0?n[r]:o,s={...i,id:t.id};return t.roles!==void 0&&(t.roles.length>0?s.roles=[...t.roles]:s.roles!==void 0&&delete s.roles),t.aliases!==void 0&&(t.aliases.length>0?s.aliases=[...t.aliases]:s.aliases!==void 0&&delete s.aliases),t.description!==void 0&&(s.description=t.description),t.order!==void 0&&(s.order=t.order),r>=0?n[r]=s:n.push(s),{file:{statuses:n},definition:s,replaced:i!==void 0}}function Jt(e,t){let o=T(t);if(o.length===0)throw new Error("Status id must not be empty.");if(Q.has(o))throw new Error(`Cannot remove built-in status "${o}". Built-in statuses are reserved: ${[...Q].join(", ")}.`);let n=e.statuses.slice(),r=n.findIndex(s=>T(s.id)===o);if(r<0)return{file:{statuses:n},removed:!1};let[i]=n.splice(r,1);return{file:{statuses:n},removed:!0,definition:i}}function je(e,t){let o=[e.id,...e.aliases??[]];for(let n of o){let r=T(n);if(r.length===0)continue;let i=t.get(r);if(i!==void 0&&i!==e.id)throw new Error(`Status token "${r}" already belongs to status "${i}". Choose a different id/alias to avoid shadowing it.`)}}(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]="c4b4af3b-6ce6-56f7-9665-9e6b2f3d9630")}catch{}})();function ae(e,t){if(typeof e!="string"||e.trim().length===0)throw new TypeError(`Schema migration ${t} must be non-empty`);return e.trim()}function Bt(e){let t=ae(e,"migrationId");if(!/^[a-zA-Z0-9._-]+$/.test(t))throw new TypeError("Schema migration migrationId must match [a-zA-Z0-9._-]+");return t}function Yt(e,t){let o=Ge(e),n=ae(t,"migrationScope");return`auto-${Kt("sha256").update(JSON.stringify({scope:n,request:o})).digest("hex").slice(0,20)}`}function Ge(e){let t=n=>ae(n,"source or target").toLowerCase().replaceAll(/[\s-]+/g,"_"),o=e.kind==="rename-type"?{kind:e.kind,from:ae(e.from,"source"),to:ae(e.to,"target")}:e.kind==="rename-field"?{kind:e.kind,from:t(e.from),to:t(e.to),...e.type===void 0?{}:{type:ae(e.type,"type")}}:{kind:e.kind,from:t(e.from),to:t(e.to)};if(o.from.toLowerCase()===o.to.toLowerCase())throw new TypeError("Schema migration source and target must differ");return o}function Zn(e){return e.kind==="rename-type"?"types":e.kind==="rename-field"?"fields":"statuses"}function Xn(e,t,o){let n=v(t.schema),r=Zn(o);return M(e,n.files[r],P[r])}function Zt(e,t){return le.join(e,"transactions","schema",`${t}-plan.json`)}function be(e){return e.length===0?null:JSON.parse(e)}async function ce(e){let t=await I(e);return{exists:t!==null,raw:t??""}}async function Xt(e,t){t.exists?await Y(e,t.raw):await ee.rm(e,{force:!0})}function Vn(e,t,o){let n=z(e),r=n.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.from.toLowerCase()),i=n.definitions.findIndex(s=>s.name.trim().toLowerCase()===t.to.toLowerCase());if(o==="stage"){if(i>=0)return J(n);if(r<0)throw new TypeError(`Unknown custom type "${t.from}".`);n.definitions.push({...n.definitions[r],name:t.to})}else r>=0&&n.definitions.splice(r,1);return J(n)}function Qn(e,t,o){let n=oe(e),r=n.fields.findIndex(s=>s.key===t.from),i=n.fields.findIndex(s=>s.key===t.to);if(o==="stage"){if(i>=0)return re(n);if(r<0)throw new TypeError(`Unknown custom field "${t.from}".`);let s=n.fields[r];n.fields.push({...s,key:t.to,metadata_key:t.to,front_matter_key:t.to,cli_flag:t.to.replaceAll("_","-")})}else r>=0&&n.fields.splice(r,1);return re(n)}function eo(e,t,o){let n=ie(e),r=n.statuses.findIndex(s=>s.id===t.from),i=n.statuses.findIndex(s=>s.id===t.to);if(o==="stage"){if(i>=0)return se(n);if(r<0)throw new TypeError(`Unknown custom status "${t.from}".`);n.statuses.push({...n.statuses[r],id:t.to})}else r>=0&&n.statuses.splice(r,1);return se(n)}function to(e,t,o){return t.kind==="rename-type"?Vn(e,t,o):t.kind==="rename-field"?Qn(e,t,o):eo(e,t,o)}function W(e,t){return typeof e=="string"&&e.trim().toLowerCase()===t.from.toLowerCase()?t.to:e}function qe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function de(e){return Array.isArray(e)?e.map(t=>qe(t)).filter(t=>t!==void 0):[]}function no(e,t){for(let o of de(e.fields))Array.isArray(o.required_types)&&(o.required_types=o.required_types.map(n=>W(n,t)));for(let o of de(e.type_workflows))o.type=W(o.type,t)}function oo(e,t){for(let n of de(e.definitions))n.default_status=W(n.default_status,t);let o=qe(e.workflow);if(o)for(let[n,r]of Object.entries(o))o[n]=W(r,t);for(let n of de(e.type_workflows))Array.isArray(n.allowed_transitions)&&(n.allowed_transitions=n.allowed_transitions.map(r=>Array.isArray(r)?r.map(i=>W(i,t)):r))}function ro(e,t){for(let o of de(e.definitions)){for(let n of["required_create_fields","required_create_repeatables"])Array.isArray(o[n])&&(o[n]=o[n].map(r=>W(r,t)));for(let n of["options","command_option_policies"])for(let r of de(o[n])){let i=n==="options"?"key":"option";r[i]=W(r[i],t)}}}function io(e,t){let o=qe(e.options);if(!o)return;if(t.kind==="rename-field"){if(!Object.prototype.hasOwnProperty.call(o,t.from))return;if(Object.prototype.hasOwnProperty.call(o,t.to))throw new TypeError(`Schema migration collision in saved template "${String(e.name??"unknown")}": target field "${t.to}" already exists.`);o[t.to]=o[t.from],delete o[t.from];return}let n=t.kind==="rename-type"?"type":"status";o[n]=W(o[n],t)}function ze(e,t){let o=JSON.parse(e);if(typeof o!="object"||o===null||Array.isArray(o))return e;let n=o;return t.kind==="rename-type"?no(n,t):t.kind==="rename-field"?ro(n,t):oo(n,t),io(n,t),`${JSON.stringify(n,null,2)}
|
|
14
|
+
`}function Vt(e,t){if(t.kind==="rename-type"){let n=z(e).definitions;return{source:n.some(r=>r.name.trim().toLowerCase()===t.from.toLowerCase()),target:n.some(r=>r.name.trim().toLowerCase()===t.to.toLowerCase())}}if(t.kind==="rename-field"){let n=oe(e).fields;return{source:n.some(r=>r.key===t.from),target:n.some(r=>r.key===t.to)}}let o=ie(e).statuses;return{source:o.some(n=>n.id===t.from),target:o.some(n=>n.id===t.to)}}function so(e,t){let o=e;return t.kind==="rename-type"?e.type.toLowerCase()===t.to.toLowerCase()?[]:["type"]:t.kind==="remap-status"?e.status.toLowerCase()===t.to.toLowerCase()?[]:["status"]:Object.prototype.hasOwnProperty.call(o,t.to)&&!Object.prototype.hasOwnProperty.call(o,t.from)?[]:[t.from,t.to]}function ao(e,t){if(t.kind==="rename-type")return e.type.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"type",before:e.type,after:t.to}]}:null;if(t.kind==="remap-status")return e.status.toLowerCase()===t.from.toLowerCase()?{id:e.id,changes:[{field:"status",before:e.status,after:t.to}]}:null;if(t.type!==void 0&&e.type.toLowerCase()!==t.type.toLowerCase())return null;let o=e;if(!Object.prototype.hasOwnProperty.call(o,t.from))return null;if(Object.prototype.hasOwnProperty.call(o,t.to))throw new TypeError(`Schema migration collision on item "${e.id}": target field "${t.to}" already exists.`);return{id:e.id,changes:[{field:t.from,before:o[t.from],after:void 0},{field:t.to,before:void 0,after:o[t.from]}]}}function Qt(e,t){let o=Ge(t.request),n=t.migrationId===void 0?Yt(o,t.migrationScope??"plan"):Bt(t.migrationId),r=e.map(c=>ao(c,o)).filter(c=>c!==null).sort((c,l)=>c.id.localeCompare(l.id)),i=Kt("sha256").update(JSON.stringify({migrationId:n,request:o,items:r})).digest("hex"),s=new Set([...t.completedItemIds??[]].map(c=>c.trim()).filter(c=>c.length>0)),a=r.filter(c=>!s.has(c.id));return Object.freeze({migration_id:n,request:o,fingerprint:i,affected_item_count:r.length,pending_item_count:a.length,skipped_completed_count:r.length-a.length,items:Object.freeze(a)})}async function co(e){let t=x(e.settings,R()),o=[...new Set(Object.values(t.type_to_folder))],n=await lt(e.pmRoot,o),r=e.request.kind==="rename-type"?{types:[e.request.from]}:e.request.kind==="remap-status"?{statuses:[e.request.from]}:{metadataKeys:[e.request.from],...e.request.type===void 0?{}:{types:[e.request.type]}},i=n?await ct({pmRoot:e.pmRoot,expectedSourceCursor:n.source_cursor,query:r}):null;return i?{items:i.items,selectionSource:"derived_index",typeToFolder:t.type_to_folder}:{items:await Z(e.pmRoot,e.settings.item_format,t.type_to_folder,[],e.settings.schema),selectionSource:"scan",typeToFolder:t.type_to_folder}}async function lo(e,t){let o=await I(Zt(e,t));if(o===null)return null;try{let n=JSON.parse(o);if(n.schema_version!==1||n.plan.migration_id!==t||!Array.isArray(n.plan.items))throw new TypeError("invalid plan envelope");return n.plan}catch(n){throw new y(`Stored schema migration plan "${t}" is invalid: ${Xe(n)}`,h.GENERIC_FAILURE)}}async function fo(e,t){let o=Zt(e,t.migration_id);await ee.mkdir(le.dirname(o),{recursive:!0});let n={schema_version:1,plan:t,created_at:new Date().toISOString()};await Y(o,`${JSON.stringify(n,null,2)}
|
|
15
|
+
`)}function uo(e,t){return JSON.stringify(e)===JSON.stringify(t)}async function po(e){let t=await dt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)throw new y(`Schema migration item "${e.id}" no longer exists.`,h.NOT_FOUND);return(await ft(t,{schema:e.settings.schema})).document.metadata}function Ht(e,t,o){let n=o==="forward"?t.from:t.to,r=o==="forward"?t.to:t.from;if(t.kind==="rename-type"){if(e.metadata.type.toLowerCase()===r.toLowerCase())return[];if(e.metadata.type.toLowerCase()!==n.toLowerCase())throw new TypeError(`Schema migration expected type "${n}" on item "${e.metadata.id}".`);return e.metadata.type=r,["type"]}if(t.kind==="remap-status"){if(e.metadata.status.toLowerCase()===r.toLowerCase())return[];if(e.metadata.status.toLowerCase()!==n.toLowerCase())throw new TypeError(`Schema migration expected status "${n}" on item "${e.metadata.id}".`);return e.metadata.status=r,["status"]}let i=e.metadata;if(Object.prototype.hasOwnProperty.call(i,r)&&!Object.prototype.hasOwnProperty.call(i,n))return[];if(!Object.prototype.hasOwnProperty.call(i,n)||Object.prototype.hasOwnProperty.call(i,r))throw new TypeError(`Schema migration field state changed concurrently on item "${e.metadata.id}".`);return i[r]=i[n],delete i[n],[n,r]}function Wt(e){return{id:e.id,inspect:async()=>{let t=await ce(e.filePath),o=Vt(t.raw,e.request),n=e.phase==="stage"?o.source&&o.target:!o.source&&o.target;return{state:n?"applied":"pending",...n?{result:{phase:e.phase}}:{}}},prepareCompensation:async()=>{let t=await ce(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await ce(e.filePath);return await Y(e.filePath,to(t.raw,e.request,e.phase)),{phase:e.phase}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema snapshot for ${e.id} compensation.`);await Xt(e.filePath,{exists:t.exists,raw:t.raw})}}}function mo(e){return{id:e.stepId,inspect:async()=>{let t=await ce(e.filePath);return{state:ze(t.raw,e.request)===t.raw?"applied":"pending"}},prepareCompensation:async()=>{let t=await ce(e.filePath);return{exists:t.exists,raw:t.raw}},apply:async()=>{let t=await ce(e.filePath);return await Y(e.filePath,ze(t.raw,e.request)),{file:e.filePath}},compensate:async t=>{if(typeof t!="object"||t===null||Array.isArray(t)||typeof t.exists!="boolean"||typeof t.raw!="string")throw new TypeError(`Missing schema reference snapshot for ${e.stepId} compensation.`);await Xt(e.filePath,{exists:t.exists,raw:t.raw})}}}function ho(e){return{id:`item-${e.id}`,inspect:async()=>{let t=await b(e.pmRoot),o=x(t,R()).type_to_folder,n=await po({pmRoot:e.pmRoot,settings:t,typeToFolder:o,id:e.id}),r=so(n,e.request).length===0;return{state:r?"applied":"pending",...r?{result:{item_id:e.id}}:{}}},apply:async()=>{let t=await b(e.pmRoot),o=x(t,R()).type_to_folder,n=await ve({pmRoot:e.pmRoot,settings:t,typeToFolder:o,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}`,author:e.author,message:`Schema migration ${e.request.kind}: ${e.request.from} -> ${e.request.to}`,force:e.force,skipNoop:!0,mutate(r){return{changedFields:Ht(r,e.request,"forward")}}});return{item_id:e.id,changed_fields:n.changedFields}},compensate:async()=>{let t=await b(e.pmRoot),o=x(t,R()).type_to_folder;await ve({pmRoot:e.pmRoot,settings:t,typeToFolder:o,id:e.id,op:`schema_${e.request.kind.replaceAll("-","_")}_compensate`,author:e.author,message:`Compensate schema migration ${e.request.kind}: ${e.request.to} -> ${e.request.from}`,force:!0,skipNoop:!0,mutate(n){return{changedFields:Ht(n,e.request,"reverse")}}})}}}async function yo(e){let t=await lo(e.pmRoot,e.migrationId);if(t){if(!uo(t.request,e.request))throw new y(`Schema migration id "${e.migrationId}" already belongs to a different request.`,h.CONFLICT);return{plan:t,stored:!0}}let o=await co({pmRoot:e.pmRoot,settings:e.settings,request:e.request});return{plan:{...Qt(o.items,{migrationId:e.migrationId,request:e.request}),selection_source:o.selectionSource},stored:!1}}async function go(e){let t=Vt(await I(e.schemaPath)??"",e.request);if(!t.source)throw new y(`Schema migration source "${e.request.from}" is not a custom definition.`,h.NOT_FOUND);if(t.target)throw new y(`Schema migration target "${e.request.to}" already exists.`,h.CONFLICT);await fo(e.pmRoot,e.plan)}async function wo(e){let t=v(e.settings.schema),o=[...new Set([["types",P.types],["fields",P.fields],["workflows",P.workflows]].map(([r,i])=>M(e.pmRoot,t.files[r],i)).filter(r=>r!==e.schemaPath))];try{let r=le.join(e.pmRoot,"templates"),i=await ee.readdir(r,{withFileTypes:!0});o.push(...i.filter(s=>s.isFile()&&s.name.toLowerCase().endsWith(".json")).map(s=>le.join(r,s.name)))}catch(r){if(typeof r!="object"||r===null||!("code"in r)||r.code!=="ENOENT")throw r}o.sort((r,i)=>r.localeCompare(i));let n=[];for(let r of o){let i=await I(r);i!==null&&ze(i,e.request)!==i&&n.push({filePath:r,beforeRaw:i})}return{paths:o,snapshots:n}}async function _o(e){for(let t of e.snapshots){let o=await ee.readFile(t.filePath,"utf8"),n=le.relative(e.pmRoot,t.filePath).replaceAll("\\","/");await Re({pmRoot:e.pmRoot,author:e.author,documentPath:n,before:be(t.beforeRaw),after:be(o),op:"schema_migration_reference",idempotencyKey:`${e.plan.migration_id}:${e.plan.fingerprint}:${n}`,message:`${e.request.kind}: ${e.request.from} -> ${e.request.to}`,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}}async function So(e,t,o){let n=Ge(e),r=A(process.cwd(),o.path);if(!await j(ne(r)))throw new y(`Tracker is not initialized at ${r}. Run pm init first.`,h.NOT_FOUND);let i=t.migrationId===void 0?Yt(n,await ee.realpath(r)):Bt(t.migrationId),s=await b(r),a=C(t.author,s.author_default),c=await yo({pmRoot:r,settings:s,migrationId:i,request:n}),l=c.plan;if(t.dryRun===!0)return{...l,action:n.kind,applied:!1,recovered:!1,migrated_item_count:0};let f=Xn(r,s,n),d=await ee.readFile(f,"utf8");c.stored||await go({pmRoot:r,schemaPath:f,request:n,plan:l});let g=await wo({pmRoot:r,schemaPath:f,settings:s,request:n}),m=[Wt({id:"stage-schema",filePath:f,request:n,phase:"stage"}),...g.paths.map((E,_)=>mo({filePath:E,request:n,stepId:`reference-${String(_+1).padStart(4,"0")}`})),...l.items.map(E=>ho({pmRoot:r,id:E.id,request:n,author:a,force:t.force===!0})),Wt({id:"retire-source",filePath:f,request:n,phase:"retire"})],u=await kt({pmRoot:r,transactionId:`schema-${i}`,author:a,steps:m,lockTtlSeconds:Math.max(s.locks.ttl_seconds,300),lockWaitMs:s.locks.wait_ms}),p=await ee.readFile(f,"utf8"),{historyPath:w}=await Re({pmRoot:r,author:a,documentPath:le.relative(r,f).replaceAll("\\","/"),before:be(d),after:be(p),op:"schema_migration",idempotencyKey:`${l.migration_id}:${l.fingerprint}`,message:`${n.kind}: ${n.from} -> ${n.to}; affected=${l.affected_item_count}`,lockTtlSeconds:s.locks.ttl_seconds,lockWaitMs:s.locks.wait_ms});return await _o({pmRoot:r,author:a,settings:s,request:n,plan:l,snapshots:g.snapshots}),{...l,action:n.kind,applied:!0,recovered:u.recovered,migrated_item_count:l.affected_item_count,workspace_history_path:w}}function ko(e){let t=e.applied?"applied":"dry-run",o=e.recovered?" (recovered)":"";return[`${e.action}: ${e.request.from} -> ${e.request.to} [${t}${o}]`,`migration_id: ${e.migration_id}`,`affected: ${e.affected_item_count}`,`pending: ${e.pending_item_count}`,`fingerprint: ${e.fingerprint}`].join(`
|
|
16
|
+
`)}import Io from"node:path";import{mkdir as Ao}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e3f016bb-8add-5765-bb1a-a7b22423f8d1")}catch{}})();var Je=["agile","ops","research"],bo={agile:[{name:"Story",description:"User-facing outcome or capability slice expressed from a stakeholder perspective.",defaultStatus:"open",folder:"stories",aliases:["user-story"]},{name:"Spike",description:"Time-boxed investigation used to reduce uncertainty before implementation.",defaultStatus:"open",folder:"spikes",aliases:["research-spike"]}],ops:[{name:"Incident",description:"Operational disruption, degradation, or support escalation with recovery tracking.",defaultStatus:"open",folder:"incidents",aliases:["outage"]},{name:"Runbook",description:"Repeatable operational procedure, diagnostic path, or response playbook.",defaultStatus:"open",folder:"runbooks",aliases:["playbook"]}],research:[{name:"Experiment",description:"Validated-learning activity with hypothesis, method, and outcome tracking.",defaultStatus:"open",folder:"experiments",aliases:["study"]},{name:"Hypothesis",description:"Testable claim or assumption that should be supported, rejected, or refined.",defaultStatus:"open",folder:"hypotheses",aliases:["assumption"]}]};function en(e){if(e===void 0)return;let t=e.trim().toLowerCase().replaceAll("-","_");if(t.length===0)throw new Error("Type preset name must not be empty.");if(t==="agile"||t==="ops"||t==="research")return t;throw new Error(`Invalid type preset "${e}". Allowed: ${Je.join(", ")}.`)}function He(e){return bo[e].map(t=>me(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3d53ef97-6dd5-5dea-a5c2-9bc9e62d881c")}catch{}})();var Eo=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function To(e){let t=Eo.exec(e.trim());if(!t)return;let o=t[1];if(!(o.length<2)&&!/^[A-Za-z]\d+$/.test(o))return o.toLowerCase()}function $o(e){return e.split(/[-_]+/).filter(t=>t.length>0).map(t=>`${t.slice(0,1).toUpperCase()}${t.slice(1).toLowerCase()}`).join("")}function tn(e,t={}){let o=typeof t.minCount=="number"&&t.minCount>0?Math.trunc(t.minCount):10,n=typeof t.maxExamples=="number"&&t.maxExamples>0?Math.trunc(t.maxExamples):3,r=new Map;for(let s of e){let a=typeof s=="string"?s.trim():"";if(a.length===0)continue;let c=To(a);if(c===void 0)continue;let l=r.get(c)??{count:0,examples:[]};l.count+=1,l.examples.length<n&&l.examples.push(a),r.set(c,l)}let i=[];for(let[s,a]of r.entries()){if(a.count<o)continue;let c=$o(s);i.push({name:c,prefix:s,count:a.count,examples:a.examples,shadows_builtin:rt(c)!==void 0})}return i.sort((s,a)=>a.count-s.count||s.name.localeCompare(a.name)),i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1a035e10-b8fe-52cd-a9c7-0762dd0ab160")}catch{}})();var gi=["add-type","remove-type","add-status","remove-status","add-field","remove-field","list-fields","show-field","apply-preset","list","show","show-status","rename-type","rename-field","remap-status"],Ee="schema-types",nn="schema-statuses",on="schema-fields";function K(e){return ot({pmRoot:e.pmRoot,filePath:e.filePath,raw:e.raw,op:e.op,author:e.author,lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms})}async function wi(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r;try{r=me({name:e,description:t.description,defaultStatus:t.defaultStatus,folder:t.folder,aliases:t.alias})}catch(m){throw new y(m instanceof Error?m.message:String(m),h.USAGE)}let i=await b(n),s=v(i.schema),a=M(n,s.files.types,P.types),c=[],l=C(t.author,i.author_default),f=N(i),d=await F(n,Ee,i.locks.ttl_seconds,l,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms),g;try{let m=await I(a),u;try{u=z(m)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.GENERIC_FAILURE)}try{it(r,u);let p=new Map,w=x(i,R());for(let[E,_]of Object.entries(w.type_to_folder)){let $=_.trim().toLowerCase();$.length>0&&!p.has($)&&p.set($,E)}st(r,u,p)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}g=_e(u,r),g.replaced&&g.previousName!==void 0&&g.previousName!==g.definition.name&&c.push(`type_recased:${g.previousName}->${g.definition.name}`),await K({pmRoot:n,filePath:a,raw:J(g.file),op:"schema:add-type",author:l,settings:i}),await Ke(n,[g.definition],c,"schema:add-type-folder"),c.push(...await D({path:a,scope:"project",op:"schema:add-type"}))}finally{await d()}return await rn(n,c),{action:"add-type",registered:!0,replaced:g.replaced,type:g.definition,file:{path:a,definitions:g.file.definitions.length},warnings:B(c),generated_at:k()}}async function q(e){if(!await j(ne(e)))throw new y(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND)}async function rn(e,t){try{let o=await Pt(e);o.status==="refreshed"?t.push("merge_fence_refreshed"):o.status==="not_installed"&&t.push('merge_fence_not_installed:type folders lack git merge drivers; run "pm merge install"')}catch{t.push('merge_fence_refresh_failed:run "pm merge install" to reconcile')}}function B(e){return[...new Set(e)].sort((t,o)=>t.localeCompare(o))}async function xo(e,t,o,n){let r=x(t,R()),i=n.trim().toLowerCase();return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(a=>typeof a.type=="string"&&a.type.toLowerCase()===i).length}async function Ro(e,t,o,n){let r=x(t,R()),i=ue(o),s=T(n);return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(c=>{let l=typeof c.status=="string"?c.status:"";return(i.alias_to_id.get(T(l))??T(l))===s}).length}async function vo(e,t,o,n,r){if(r.length===0||Q.has(r))return;let i=await Ro(t,o,n,r);i>0&&e.push(`items_using_status:${i}`);let s=sn(n.workflow,r);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function sn(e,t){return[["draft_status",e.draft_status],["open_status",e.open_status],["in_progress_status",e.in_progress_status],["blocked_status",e.blocked_status],["close_status",e.close_status],["canceled_status",e.canceled_status]].filter(([,n])=>n!==void 0&&T(n)===t).map(([n])=>n)}async function _i(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r=await b(n),i=v(r.schema),s=M(n,i.files.types,P.types),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,Ee,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=z(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=at(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=(d.definition?.name??e??"").trim();if(u.length>0){let p=await xo(n,r,i,u);p>0&&a.push(`items_using_type:${p}`)}await K({pmRoot:n,filePath:s,raw:J(d.file),op:"schema:remove-type",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-type"}))}}finally{await f()}return d.removed&&await rn(n,a),{action:"remove-type",removed:d.removed,...d.definition?{type:d.definition}:{},file:{path:s,definitions:d.file.definitions.length},warnings:B(a),generated_at:k()}}function We(e,t){return M(e,t.files.statuses,P.statuses)}function Te(e,t){return M(e,t.files.fields,P.fields)}function an(e,t){return M(e,t.files.types,P.types)}async function Ke(e,t,o,n){for(let r of t){let i=tt(r.folder??et(r.name)),s=Io.join(e,i);await j(s)||(await Ao(s,{recursive:!0}),o.push(...await D({path:s,scope:"project",op:n})))}}function Be(e){return{key:e.key,type:e.type,commands:[...e.commands],cli_flag:`--${e.cli_flag}`,cli_aliases:e.cli_aliases.map(t=>`--${t}`),...e.description?{description:e.description}:{},required:e.required,required_on_create:e.required_on_create,allow_unset:e.allow_unset,required_types:[...e.required_types]}}function Co(e){if(e)return{id:e.id,...e.roles.length>0?{roles:[...e.roles]}:{},...e.aliases.length>0?{aliases:[...e.aliases]}:{},...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function Fo(e){let t=new Map;for(let o of e){let n=T(o.id);if(n.length!==0){t.set(n,n);for(let r of Array.isArray(o.aliases)?o.aliases:[]){let i=T(r);i.length>0&&!t.has(i)&&t.set(i,n)}}}return t}async function Si(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r;try{r=Gt({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let i=await b(n),s=v(i.schema),a=We(n,s),c=ue(s);try{je(r,c.alias_to_id)}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let l=Co(c.by_id.get(r.id)),f=[],d=C(t.author,i.author_default),g=N(i),m=await F(n,nn,i.locks.ttl_seconds,d,!!t.force,g.force_required_for_stale_lock,i.locks.wait_ms),u;try{let p=await I(a),w;try{w=ie(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}let E=Fo(w.statuses);try{je(r,E)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.USAGE)}u=qt(w,r,l),await K({pmRoot:n,filePath:a,raw:se(u.file),op:"schema:add-status",author:d,settings:i}),f.push(...await D({path:a,scope:"project",op:"schema:add-status"}))}finally{await m()}return{action:"add-status",registered:!0,replaced:u.replaced,status:u.definition,file:{path:a,statuses:u.file.statuses.length},warnings:B(f),generated_at:k()}}async function ki(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r=await b(n),i=v(r.schema),s=We(n,i),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,nn,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=ie(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=Jt(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=T(d.definition?.id??e);await vo(a,n,r,i,u),await K({pmRoot:n,filePath:s,raw:se(d.file),op:"schema:remove-status",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-status"}))}}finally{await f()}return{action:"remove-status",removed:d.removed,...d.definition?{status:d.definition}:{},file:{path:s,statuses:d.file.statuses.length},warnings:B(a),generated_at:k()}}function cn(e){return{name:e.name,folder:e.folder,aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.default_status?{default_status:e.default_status}:{},...e.description?{description:e.description}:{}}}function Po(e,t,o){return{...cn(e),source:t,...o?{extension:o}:{},required_create_fields:[...e.required_create_fields],required_create_repeatables:[...e.required_create_repeatables],options:structuredClone(e.options),command_option_policies:structuredClone(e.command_option_policies)}}function ln(e){return{id:e.id,source:Q.has(e.id)?"builtin":"custom",roles:Array.isArray(e.roles)?[...e.roles]:[],aliases:Array.isArray(e.aliases)?[...e.aliases]:[],...e.description?{description:e.description}:{},...typeof e.order=="number"?{order:e.order}:{}}}function dn(e,t,o){let n=e.toLowerCase();return o.has(n)?"extension":t.has(n)?"custom":"builtin"}function Oo(){let e=new Map,t=R();for(let o of t?.item_types??[]){let n=o.types;if(Array.isArray(n))for(let r of n){if(typeof r!="object"||r===null||Array.isArray(r))continue;let i=r.name;typeof i=="string"&&i.trim().length>0&&e.set(i.trim().toLowerCase(),{layer:o.layer,name:o.name})}}return e}function No(e){let t=ue(e),o=[],n=[];for(let r of t.definitions){let i=ln(r);i.source==="builtin"?o.push(i):n.push(i)}return{builtin:o,custom:n}}async function ge(e){let t=A(process.cwd(),e.path);await q(t);let o=await b(t),n=v(o.schema),r=M(t,n.files.types,P.types),i=We(t,n),s=x(o,R()),a=Oo(),c=new Set((o.item_types?.definitions??[]).map(l=>l.name.trim().toLowerCase()).filter(l=>l.length>0&&!a.has(l)));return{pmRoot:t,typesPath:r,statusesPath:i,byType:s.by_type,customNames:c,extensionProvenance:a,schema:n}}async function bi(e){let t=await ge(e),o=[],n=[],r=[];for(let a of Object.values(t.byType).sort((c,l)=>c.name.localeCompare(l.name))){let c=dn(a.name,t.customNames,new Set(t.extensionProvenance.keys())),l=cn(a);c==="extension"?r.push(l):c==="custom"?n.push(l):o.push(l)}let i=No(t.schema),s=we(t.schema).definitions.map(Be);return{action:"list",builtin:o,custom:n,extension:r,counts:{builtin:o.length,custom:n.length,extension:r.length,total:o.length+n.length+r.length},statuses:{builtin:i.builtin,custom:i.custom,counts:{builtin:i.builtin.length,custom:i.custom.length,total:i.builtin.length+i.custom.length}},fields:{custom:s,counts:{total:s.length}},file:{path:t.typesPath},generated_at:k()}}async function Ei(e,t){let o=(e??"").trim();if(o.length===0)throw new y("Type name must not be empty.",h.USAGE);let n=await ge(t),r=Object.values(n.byType).find(i=>i.name.toLowerCase()===o.toLowerCase()||i.aliases.some(s=>s.toLowerCase()===o.toLowerCase()));if(!r)throw new y(`Unknown item type "${o}". Run pm schema list to inspect registered types, or pm schema add-type "${pe(o)}" to register it.`,h.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Po(r,dn(r.name,n.customNames,new Set(n.extensionProvenance.keys())),n.extensionProvenance.get(r.name.toLowerCase())),file:{path:n.typesPath},generated_at:k()}}async function Ti(e,t){let o=T(e);if(o.length===0)throw new y("Status id must not be empty.",h.USAGE);let n=await ge(t),r=ue(n.schema),i=r.alias_to_id.get(o)??o,s=r.by_id.get(i);if(!s)throw new y(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:ln(s),file:{path:n.statusesPath},generated_at:k()}}async function $i(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r;try{r=Ut({key:e,type:t.type,commands:t.commands,description:t.description,cliFlag:t.cliFlag,aliases:t.alias,required:t.required,requiredOnCreate:t.requiredOnCreate,allowUnset:t.allowUnset,requiredTypes:t.requiredTypes})}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}let i=await b(n),s=v(i.schema),a=Te(n,s),c=[],l=ut(r.key);l&&c.push(`custom_field_mcp_input_collision:${l.field}:${l.property}:${l.owner}:use=${l.nested_path}`);let f=C(t.author,i.author_default),d=N(i),g=await F(n,on,i.locks.ttl_seconds,f,!!t.force,d.force_required_for_stale_lock,i.locks.wait_ms),m;try{let u=await I(a),p;try{p=oe(u)}catch(w){throw new y(w instanceof Error?w.message:String(w),h.GENERIC_FAILURE)}m=jt(p,r),await K({pmRoot:n,filePath:a,raw:re(m.file),op:"schema:add-field",author:f,settings:i}),c.push(...await D({path:a,scope:"project",op:"schema:add-field"}))}finally{await g()}return{action:"add-field",registered:!0,replaced:m.replaced,field:m.definition,file:{path:a,fields:m.file.fields.length},warnings:B(c),generated_at:k()}}async function Lo(e,t,o,n){let r=x(t,R());return(await Z(e,t.item_format,r.type_to_folder,[],o)).filter(s=>{let a=s[n];return a==null?!1:Array.isArray(a)?a.length>0:typeof a=="string"?a.trim().length>0:!0}).length}async function Ii(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r=await b(n),i=v(r.schema),s=Te(n,i),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,on,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let g=await I(s),m;try{m=oe(g)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.GENERIC_FAILURE)}try{d=zt(m,e)}catch(u){throw new y(u instanceof Error?u.message:String(u),h.USAGE)}if(d.removed){let u=L(d.definition?.key??e),p=L(d.definition?.metadata_key??d.definition?.front_matter_key??u);if(p.length>0){let w=await Lo(n,r,i,p);w>0&&a.push(`items_using_field:${w}`)}await K({pmRoot:n,filePath:s,raw:re(d.file),op:"schema:remove-field",author:c,settings:r}),a.push(...await D({path:s,scope:"project",op:"schema:remove-field"}))}}finally{await f()}return{action:"remove-field",removed:d.removed,...d.definition?{field:d.definition}:{},file:{path:s,fields:d.file.fields.length},warnings:B(a),generated_at:k()}}async function Ai(e){let t=await ge(e),o=we(t.schema).definitions.map(Be);return{action:"list-fields",fields:o,counts:{total:o.length},file:{path:Te(t.pmRoot,t.schema)},generated_at:k()}}async function xi(e,t){let o=L(e);if(o.length===0)throw new y("Field key must not be empty.",h.USAGE);let n=await ge(t),r=we(n.schema).by_key.get(o);if(!r)throw new y(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${pe(e??"")}" to register it.`,h.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Be(r),file:{path:Te(n.pmRoot,n.schema)},generated_at:k()}}async function Ri(e,t,o){let n=A(process.cwd(),o.path);await q(n);let r;try{let p=en(e);if(p===void 0)throw new Error(`Type preset name is required. Allowed: ${Je.join(", ")}.`);r=p}catch(p){throw new y(p instanceof Error?p.message:String(p),h.USAGE)}let i=await b(n),s=v(i.schema),a=an(n,s),c=[],l=C(t.author,i.author_default),f=N(i),d=[],g=[],m,u=await F(n,Ee,i.locks.ttl_seconds,l,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms);try{let p=await I(a),w;try{w=z(p)}catch(_){throw new y(_ instanceof Error?_.message:String(_),h.GENERIC_FAILURE)}let E=w;for(let _ of He(r)){let $=_e(E,_);E=$.file,($.replaced?g:d).push($.definition.name)}m=E.definitions.length,await K({pmRoot:n,filePath:a,raw:J(E),op:"schema:apply-preset",author:l,settings:i}),await Ke(n,He(r),c,"schema:apply-preset-folder"),c.push(...await D({path:a,scope:"project",op:"schema:apply-preset"}))}finally{await u()}return{action:"apply-preset",preset:r,registered:d,replaced:g,file:{path:a,definitions:m},warnings:B(c),generated_at:k()}}function Do(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new y("--min-count must be a positive integer (>= 1).",h.USAGE);return e}async function vi(e,t){let o=A(process.cwd(),t.path);await q(o);let n=await b(o),r=v(n.schema),i=an(o,r),s=Do(e.minCount),a=x(n,R()),l=(await Z(o,n.item_format,a.type_to_folder,[],r)).map($=>typeof $.title=="string"?$.title:""),f=tn(l,{minCount:s}),d=[],g=[],m=[],u=[],p;if(!e.apply){let $;try{$=z(await I(i))}catch(te){throw new y(te instanceof Error?te.message:String(te),h.GENERIC_FAILURE)}return p=$.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:f,registered:g,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:d,generated_at:k()}}let w=C(e.author,n.author_default),E=N(n),_=await F(o,Ee,n.locks.ttl_seconds,w,!!e.force,E.force_required_for_stale_lock,n.locks.wait_ms);try{let $=await I(i),te;try{te=z($)}catch(O){throw new y(O instanceof Error?O.message:String(O),h.GENERIC_FAILURE)}let fe=te;for(let O of f){if(O.shadows_builtin){u.push({name:O.name,reason:"shadows_builtin"});continue}let Ye;try{Ye=me({name:O.name})}catch{u.push({name:O.name,reason:"invalid_type_token"});continue}let $e=_e(fe,Ye);fe=$e.file,($e.replaced?m:g).push($e.definition.name)}p=fe.definitions.length,await K({pmRoot:o,filePath:i,raw:J(fe),op:"schema:infer-types",author:w,settings:n}),await Ke(o,fe.definitions.filter(O=>g.includes(O.name)||m.includes(O.name)),d,"schema:infer-types-folder"),d.push(...await D({path:i,scope:"project",op:"schema:infer-types"}))}finally{await _()}return{action:"infer-types",applied:!0,min_count:s,candidates:f,registered:g,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:B(d),generated_at:k()}}function Ci(e){let t=e.replaced?"Updated":"Registered",o=e.type.aliases&&e.type.aliases.length>0?` (aliases: ${e.type.aliases.join(", ")})`:"";return`${t} custom item type "${e.type.name}"${o} in ${e.file.path}. Run: pm create "${pe(e.type.name)}" "<title>"`}function Fi(e){return e.removed?`Removed custom item type "${e.type?.name??"(unknown)"}" from ${e.file.path}.`:`No custom item type matched; nothing removed from ${e.file.path}.`}function Pi(e){let t=e.replaced?"Updated":"Registered",o=e.status.roles&&e.status.roles.length>0?` (roles: ${e.status.roles.join(", ")})`:"",n=e.status.aliases&&e.status.aliases.length>0?` (aliases: ${e.status.aliases.join(", ")})`:"";return`${t} status "${e.status.id}"${o}${n} in ${e.file.path}.`}function Oi(e){return e.removed?`Removed custom status "${e.status?.id??"(unknown)"}" from ${e.file.path}.`:`No custom status matched; nothing removed from ${e.file.path}.`}function Ni(e){let t=[`Schema types: ${e.counts.total} total (${e.counts.builtin} builtin, ${e.counts.custom} custom, ${e.counts.extension} extension)`];for(let[o,n]of[["builtin",e.builtin],["custom",e.custom],["extension",e.extension]])n.length!==0&&t.push(`${o}: ${n.map(r=>r.name).join(", ")}`);t.push(`statuses: ${e.statuses.counts.total} total (${e.statuses.counts.builtin} builtin, ${e.statuses.counts.custom} custom)`);for(let[o,n]of[["builtin statuses",e.statuses.builtin],["custom statuses",e.statuses.custom]])n.length!==0&&t.push(`${o}: ${n.map(r=>r.id).join(", ")}`);return t.push(`custom fields: ${e.fields.counts.total} total`),e.fields.custom.length>0&&t.push(`fields: ${e.fields.custom.map(o=>`${o.key} (${o.type}, ${o.cli_flag})`).join(", ")}`),t.push("Inspect one: pm schema show <Type>"),t.push("Inspect one status: pm schema show-status <status>"),t.push("Inspect one field: pm schema show-field <key>"),t.join(`
|
|
17
17
|
`)}function Li(e){let t=[`type: ${e.type.name}`,`source: ${e.type.source}`,`folder: ${e.type.folder}`];return e.type.default_status&&t.push(`default_status: ${e.type.default_status}`),e.type.aliases.length>0&&t.push(`aliases: ${e.type.aliases.join(", ")}`),e.type.description&&t.push(`description: ${e.type.description}`),e.type.options.length>0&&t.push(`options: ${e.type.options.map(o=>o.key).join(", ")}`),t.join(`
|
|
18
18
|
`)}function Di(e){let t=[`status: ${e.status.id}`,`source: ${e.status.source}`];return e.status.roles.length>0&&t.push(`roles: ${e.status.roles.join(", ")}`),e.status.aliases.length>0&&t.push(`aliases: ${e.status.aliases.join(", ")}`),e.status.description&&t.push(`description: ${e.status.description}`),typeof e.status.order=="number"&&t.push(`order: ${e.status.order}`),t.join(`
|
|
19
19
|
`)}function Mo(e){let t=[];e.required&&t.push("required"),e.required_on_create&&t.push("required_on_create"),e.allow_unset||t.push("no_unset");let o=t.length>0?` [${t.join(", ")}]`:"";return`${e.key} (${e.type}) ${e.cli_flag} commands=${e.commands.join("/")}${o}`}function Mi(e){return`${e.replaced?"Updated":"Registered"} custom field "${e.field.key}" in ${e.file.path}. Use it: pm create "<title>" --${(e.field.cli_flag??e.field.key).replaceAll("_","-")} <value>`}function Ui(e){return e.removed?`Removed custom field "${e.field?.key??"(unknown)"}" from ${e.file.path}.`:`No custom field matched; nothing removed from ${e.file.path}.`}function ji(e){let t=[`Custom fields: ${e.counts.total} total`];for(let o of e.fields)t.push(` ${Mo(o)}`);return t.push("Inspect one: pm schema show-field <key>"),t.join(`
|
|
20
20
|
`)}function zi(e){let t=e.field,o=[`field: ${t.key}`,`type: ${t.type}`,`cli_flag: ${t.cli_flag}`,`commands: ${t.commands.join(", ")}`];return t.cli_aliases.length>0&&o.push(`cli_aliases: ${t.cli_aliases.join(", ")}`),t.description&&o.push(`description: ${t.description}`),t.required&&o.push("required: true"),t.required_on_create&&o.push("required_on_create: true"),t.allow_unset||o.push("allow_unset: false"),t.required_types.length>0&&o.push(`required_types: ${t.required_types.join(", ")}`),o.join(`
|
|
21
21
|
`)}function Gi(e){let t=e.registered.length>0?`registered: ${e.registered.join(", ")}`:"",o=e.replaced.length>0?`updated: ${e.replaced.join(", ")}`:"",n=[t,o].filter(r=>r.length>0).join("; ");return`Applied "${e.preset}" type preset to ${e.file.path}${n.length>0?` (${n})`:""}.`}function qi(e){if(e.candidates.length===0)return`No title-prefix conventions found with at least ${e.min_count} items. Lower the threshold with --min-count <n>.`;let t=e.applied?[`Inferred and registered custom types from title prefixes (min-count ${e.min_count}):`]:[`Inferred custom type candidates from title prefixes (min-count ${e.min_count}, dry-run):`];for(let o of e.candidates){let n=o.shadows_builtin?" [shadows built-in, skipped]":"";t.push(` ${o.name} <- "${o.prefix}" (${o.count} items)${n}`)}return e.applied?(e.registered.length>0&&t.push(`registered: ${e.registered.join(", ")}`),e.replaced.length>0&&t.push(`updated: ${e.replaced.join(", ")}`)):t.push("Re-run with --apply to register the non-shadowing candidates."),t.join(`
|
|
22
|
-
`)}var Ji={workflowSlotsReferencing:sn};export{Ce as a,kt as b,Et as c,Oe as d,An as e,
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
22
|
+
`)}var Ji={workflowSlotsReferencing:sn};export{Ce as a,kt as b,Et as c,Oe as d,An as e,Rn as f,Yo as g,V as h,ye as i,On as j,Ue as k,Ft as l,ur as m,pr as n,Pt as o,mr as p,Ln as q,Gt as r,ie as s,se as t,qt as u,Ut as v,oe as w,re as x,jt as y,Je as z,bo as A,en as B,He as C,Yt as D,Qt as E,So as F,ko as G,gi as H,wi as I,_i as J,Ke as K,Si as L,ki as M,bi as N,Ei as O,Ti as P,$i as Q,Ii as R,Ai as S,xi as T,Ri as U,vi as V,Ci as W,Fi as X,Pi as Y,Oi as Z,Ni as _,Li as $,Di as aa,Mi as ba,Ui as ca,ji as da,zi as ea,Gi as fa,qi as ga,Ji as ha};
|
|
23
|
+
//# sourceMappingURL=chunk-CALJHNBL.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as N}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as N}from"./chunk-K44PYFXH.js";import{c as T}from"./chunk-2AXF3VSK.js";import{a as m}from"./chunk-FB7G2HY2.js";import{u as D}from"./chunk-NZ75GNSA.js";import{a as R,b as I,c as v,d as M}from"./chunk-NG6OXIBR.js";import{$f as x,A as u,C as f,Da as S,H as C,La as E,Nc as y,Nf as q,Oa as A,R as b,b as k,cd as g,lc as O,zd as P}from"./chunk-D4FPS43D.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="1be4d7c4-3ede-59cc-8d70-df966a66e67e")}catch{}})();var U=1,_="close-many",z=["--filter-status","--filter-type","--filter-tag","--filter-priority","--filter-sprint","--filter-release","--filter-parent","--filter-assignee","--filter-updated-before","--ids"].join(", ");function L(e,t){return m(e,t,{includePagination:!1})}function G(e,t){return m(e,t)}function F(e){if(e?.ids!=null&&String(e.ids).trim().length===0)throw new f("--ids requires at least one non-empty item ID",u.USAGE)}function V(e){let t={};if(!e)return t;for(let[n,o]of Object.entries(e))o==null||typeof o=="string"&&!o.split(",").some(i=>i.trim().length>0)||(t[n]=o);return t}function $(e,t){let n=String(e??"").trim();if(n.length>0)return n;if(t)throw new f("pm close-many requires a shared close reason via --reason because governance.require_close_reason is enabled.",u.USAGE,{code:"close_reason_required",required:"Provide a shared closing summary via --reason for the whole batch.",why:"governance.require_close_reason is enabled, so every close must record why the items are done.",examples:['pm close-many --filter-sprint S-12 --reason "Sprint S-12 acceptance criteria met"','pm close-many --ids pm-a,pm-b --reason "Superseded by redesign"'],nextSteps:["Re-run with --reason describing the shared outcome.","To stop requiring reasons, run: pm config set governance-require-close-reason --policy disabled"]})}async function B(e,t){let n=y(t.schema),o=S(t,O()),i=await x(e,t.item_format,o.type_to_folder,void 0,t.schema),s=new Map,l=new Map;for(let r of i){if(typeof r.parent!="string"||r.parent.length===0||(l.set(r.id,r.parent),g(r.status,n)))continue;let c=s.get(r.parent);c?c.push(r.id):s.set(r.parent,[r.id])}for(let r of s.values())r.sort((c,a)=>c.localeCompare(a));return{childrenByParent:s,parentByChild:l}}function w(e,t,n){let o=n?.get(e);if(o!==void 0)return o;let i=0,s=t.get(e),l=[],r=new Set,c=!1;for(;s!==void 0&&!r.has(s);){let a=n?.get(s);if(a!==void 0){i+=a+1;break}r.add(s),l.push(s),i+=1,s=t.get(s)}if(s!==void 0&&r.has(s)&&(c=!0),!c){n?.set(e,i);for(let[a,h]of l.entries())n?.set(h,i-a-1)}return i}async function K(e){let t=await v(e.pmRoot,_,e.rollbackId,U),n=e.options.message??`Rollback close-many checkpoint ${t.id}`,o=await M(t.items,(i,s)=>N(i,s,{author:e.options.author,message:n,force:!0},e.global));return{mode:"rollback",matched_count:t.items.length,dry_run:!1,rollback_checkpoint_id:t.id,checkpoint:{id:t.id,created_at:t.created_at,path:t.path,rollback_command:`pm close-many --rollback ${t.id}`},restored_count:o.restored_ids.length,failed_count:o.failed_count,rows:o.rows,ids:o.restored_ids}}function X(e,t,n,o,i){return e.map(s=>{let l=(t.get(s.id)??[]).filter(c=>!n.has(c)),r=!H(s,o,i);return{id:s.id,title:typeof s.title=="string"?s.title:"",status:s.status,action:r?"skip":"close",...r?{skip_reason:"already_terminal"}:{},...l.length>0?{active_child_ids:l}:{}}})}async function J(e){let t=await I(e.pmRoot,_,e.checkpointId,{schema_version:U,id:e.checkpointId,created_at:e.nowValue,author:P(e.options.author,"unknown"),...e.reason!==void 0?{reason:e.reason}:{},filters:e.filters,items:e.checkpointItems});return{id:e.checkpointId,created_at:e.nowValue,path:t,rollback_command:`pm close-many --rollback ${e.checkpointId}`}}async function Q(e){let t=[],n=[];for(let o of e.matched){if(!e.closableIds.has(o.id)){t.push({id:o.id,status:"skipped",skip_reason:"already_terminal"});continue}try{let i=await T(o.id,e.reason,e.closeOptions,e.global);t.push({id:o.id,status:"closed",changed_fields:i.changed_fields,...i.warnings&&i.warnings.length>0?{warnings:i.warnings}:{}}),n.push(o.id)}catch(i){t.push({id:o.id,status:"failed",error:C(i)})}}return{rows:t,closedIds:n}}function W(e){return typeof e.rollback=="string"?e.rollback:void 0}function Z(e,t){if(t.trim().length===0)throw new f("--rollback requires a checkpoint id",u.USAGE);if(e.dryRun===!0)throw new f("--dry-run cannot be combined with --rollback",u.USAGE);if(G(e.list,e.status))throw new f("Rollback mode does not accept filter options",u.USAGE)}function ee(e){if(!L(e.list,e.status))throw new f(`close-many requires at least one filter to scope the close (for example: ${z}). Refusing to match every item.`,u.USAGE)}function te(e,t){let n=new Map;return[...e].sort((o,i)=>{let s=w(i.id,t,n)-w(o.id,t,n);return s!==0?s:o.id.localeCompare(i.id)})}function H(e,t,n){return n||!g(e.status,t)}function ne(e,t,n){return new Set(e.filter(o=>H(o,t,n)).map(o=>o.id))}async function oe(e){ee(e.options);let t=y(e.settings.schema),n=$(e.options.reason,e.settings.governance.require_close_reason),o=e.options.force===!0,i=await D(e.options.status,V(e.options.list),e.global),{childrenByParent:s,parentByChild:l}=await B(e.pmRoot,e.settings),r=te(i.items,l),c=ne(r,t,o);return{pmRoot:e.pmRoot,settings:e.settings,statusRegistry:t,reason:n,validateCloseMode:e.options.validateClose,force:o,listed:i,matched:r,planRows:X(r,s,c,t,o)}}function se(e){return{mode:"dry_run",matched_count:e.matched.length,dry_run:!0,...e.reason!==void 0?{reason:e.reason}:{},filters:e.listed.filters,...e.validateCloseMode?{validate_close:e.validateCloseMode}:{},item_plans:e.planRows,ids:[]}}async function ie(e){if(e.options.checkpoint===!1||e.closableIds.size===0)return;let t=e.context.matched.filter(n=>e.closableIds.has(n.id)).map(n=>({id:n.id,target_updated_at:n.updated_at}));return J({pmRoot:e.context.pmRoot,checkpointId:e.checkpointId,nowValue:e.nowValue,options:e.options,reason:e.context.reason,filters:e.context.listed.filters,checkpointItems:t})}async function ue(e,t){let n=E(process.cwd(),t.path);if(!await k(A(n)))throw new f(`Tracker is not initialized at ${n}. Run pm init first.`,u.NOT_FOUND);let o=await q(n),i=e.dryRun===!0,s=W(e);if(F(e.list),s!==void 0)return Z(e,s),K({pmRoot:n,rollbackId:s,options:e,global:t});let l=await oe({pmRoot:n,settings:o,options:e,global:t});if(i)return se(l);let r=new Set(l.planRows.filter(d=>d.action==="close").map(d=>d.id)),c=b(),a=R(_,c),h=await ie({context:l,options:e,closableIds:r,checkpointId:a,nowValue:c}),j={author:e.author,message:e.message??`close-many apply ${a}`,completedAt:e.completedAt,validateClose:l.validateCloseMode,force:l.force,resolution:e.resolution,expectedResult:e.expectedResult,actualResult:e.actualResult},{rows:p,closedIds:Y}=await Q({matched:l.matched,closableIds:r,reason:l.reason,closeOptions:j,global:t});return{mode:"apply",matched_count:l.matched.length,dry_run:!1,...l.reason!==void 0?{reason:l.reason}:{},filters:l.listed.filters,...l.validateCloseMode?{validate_close:l.validateCloseMode}:{},...h?{checkpoint:h}:{},closed_count:p.filter(d=>d.status==="closed").length,skipped_count:p.filter(d=>d.status==="skipped").length,failed_count:p.filter(d=>d.status==="failed").length,rows:p,ids:Y}}var fe={activeListOptions:V,buildActiveChildrenByParent:B,hasCloseManyFilters:L,hasCloseManyRollbackConflicts:G,hierarchyDepth:w,rejectBlankIdsFilter:F,resolveReason:$};export{ue as a,fe as b};
|
|
2
|
+
//# sourceMappingURL=chunk-CFIGP5LY.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as q}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as q}from"./chunk-HFSD77TQ.js";import{f as M,g as V,h as X}from"./chunk-PD3225AM.js";import{a as E}from"./chunk-VT3Z5G7D.js";import{A as m,Ad as D,C as _,Da as P,La as b,Nf as A,Oa as x,R as I,Zf as W,ag as G,b as v,c as $,ff as N,lc as k,nf as w,qf as j,rf as L,tf as C,uc as F,uf as z,vf as U,zd as T}from"./chunk-D4FPS43D.js";import Q from"fast-json-patch";(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]="dd5ab9c3-bc6f-59f1-be89-ad0ab2abe7b5")}catch{}})();function J(e,t){return t==="body"?e.body:e.metadata[t]}function H(e,t){if(e===void 0||Object.is(e,t))return!0;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let s=new Set;return e.every(o=>{let c=t.findIndex((n,u)=>!s.has(u)&&H(o,n));return c<0?!1:(s.add(c),!0)})}if(e===null||t===null||typeof e!="object"||typeof t!="object"||Array.isArray(t))return!1;let i=t;return Object.entries(e).every(([s,o])=>Object.hasOwn(i,s)&&H(o,i[s]))}function K(e,t){let i=new Set(t),s=[];for(let o=e.length-1;o>=0&&i.size>0;o-=1){let c=e[o],n=new Set;for(let a of L(c.patch))n.add(E(a.path)),a.from&&n.add(E(a.from));let u=[...i].filter(a=>n.has(a));if(u.length!==0){for(let a of u)i.delete(a);s.push({index:o+1,ts:c.ts,author:c.author,op:c.op,fields:u.sort((a,y)=>a.localeCompare(y))})}}return s.reverse()}function re(e,t,i){let s=Q.compare(t,i);if(s.length===0)return;let o=new Set;for(let r of s)o.add(E(r.path));let c=new Set([...o].filter(r=>H(J(t,r),J(i,r)))),n=new Set([...o].filter(r=>!c.has(r))),u=K(e,n),a=K(e,c),y=[...o].sort((r,f)=>r.localeCompare(f)),l=[...n].sort((r,f)=>r.localeCompare(f)),d=[...c].sort((r,f)=>r.localeCompare(f)),h=[...new Set(u.map(r=>r.author))].sort((r,f)=>r.localeCompare(f)),p=[...new Set(a.map(r=>r.author))].sort((r,f)=>r.localeCompare(f));return{reconciled_field_count:o.size,reconciled_fields:y,reverted_field_count:n.size,reverted_fields:l,discarded_events:u,discarded_authors:h,preserved_field_count:c.size,preserved_fields:d,preserved_events:a,preserved_authors:p,recovery_hint:u.length>0?"Reconciliation keeps the on-disk item and overwrites these replayed mutations. To recover one, inspect it with pm history <id> --diff --field <field>, then re-apply the lost value with pm update.":null}}async function ie(e,t,i){let s=e.located?.itemPath??null,o=e.located?await W(e.located,{schema:t.schema}):null;if(!o)return{currentItemReplay:null,currentItemPath:s,matchedChainBefore:null,currentItemRawBeforeLock:null,loadedItem:null};let c=j(o.document),n=i[i.length-1]?.after_hash;return{currentItemReplay:c,currentItemPath:s,matchedChainBefore:w(c)===n,currentItemRawBeforeLock:o.raw,loadedItem:o}}function oe(e){return typeof e.message=="string"&&e.message.trim().length>0?e.message:`history-repair re-anchored ${e.entriesRehashed} entr${e.entriesRehashed===1?"y":"ies"}${e.entriesPatchRepaired>0?`, repaired ${e.entriesPatchRepaired} patch(es)`:""}${e.reconcileNeeded?", reconciled chain with on-disk item":""}.`}function ne(e){let t=[...e.reanchorEntries];if(!e.changed)return{rewrittenEntries:t,auditEntryAdded:!1};let i=e.reconcileNeeded&&e.currentItemReplay?e.currentItemReplay:e.finalReplay;return t.push({ts:I(),author:e.author,op:e.auditOperation,patch:e.reconcileNeeded&&e.currentItemReplay?Q.compare(e.finalReplay,e.currentItemReplay):[],before_hash:w(e.finalReplay),after_hash:w(i),message:e.message,...e.auditContext===void 0?{}:{context:e.auditContext}}),{rewrittenEntries:t,auditEntryAdded:!0}}function se(e,t){let i=[];return e||i.push("history_repair_no_changes"),t>0&&i.push(`history_repair_skipped_unresolvable_ops:${t}`),i}async function ae(e){return V({pmRoot:e.pmRoot,subject:e.subject,settings:e.settings,typeRegistry:e.typeRegistry,historyRawBeforeLock:e.historyRawBeforeLock,currentItemRawBeforeLock:e.currentItemRawBeforeLock,operation:"history-repair",author:e.author,force:e.force,itemDocument:e.loadedItem?.document??null,applyRewrite:async({historyRawUnderLock:t})=>M({historyPath:e.historyPath,nextHistoryRaw:U(e.rewrittenEntries),historyRawUnderLock:t}),applyPostRewrite:async()=>F({path:e.historyPath,scope:"project",op:"history_repair:history"})})}async function ce(e,t,i){let s=b(process.cwd(),i.path);if(!await v(x(s)))throw new _(`Tracker is not initialized at ${s}. Run pm init first.`,m.NOT_FOUND);let o=await A(s),c=P(o,k()),n=await X(s,e,o,c.type_to_folder);if(!await v(n.historyPath))throw new _(`No history stream exists for ${n.id}.`,m.NOT_FOUND);let u=await $(n.historyPath),a=await D(n.historyPath,n.id);if(a.length===0)throw new _(`No history entries exist for ${n.id}; nothing to repair.`,m.USAGE);let y=C(a),l=z(a),d=await ie(n,o,a),h=l.finalDocument,p=d.currentItemReplay!==null&&w(h)!==w(d.currentItemReplay),r=p&&d.currentItemReplay?re(l.entries,h,d.currentItemReplay):void 0,f=[l.entriesRehashed>0,l.entriesPatchRepaired>0,p,t.forceAuditEntry===!0].some(Boolean),B=T(t.author,o.author_default),S=!!t.dryRun,Y=oe({message:t.message,entriesRehashed:l.entriesRehashed,entriesPatchRepaired:l.entriesPatchRepaired,reconcileNeeded:p}),{rewrittenEntries:O,auditEntryAdded:Z}=ne({reanchorEntries:l.entries,changed:f,reconcileNeeded:p,currentItemReplay:d.currentItemReplay,finalReplay:h,author:B,message:Y,auditOperation:t.auditOperation??"history_repair",auditContext:t.auditContext}),R=C(O);if(!R.ok)throw new _(`history-repair produced an invalid rewritten chain (${R.errors.join(", ")}).`,m.GENERIC_FAILURE);let g=se(f,l.skippedOps);return r&&r.discarded_events.length>0&&(g.push(`history_repair_reconcile_discards_events:${r.discarded_events.length}`),g.push(`history_repair_discarded_authors:${r.discarded_authors.join(",")}`)),f&&!S&&g.push(...await ae({pmRoot:s,subject:n,settings:o,typeRegistry:c,historyRawBeforeLock:u,currentItemRawBeforeLock:d.currentItemRawBeforeLock,author:B,force:t.force,loadedItem:d.loadedItem,historyPath:n.historyPath,rewrittenEntries:O})),{id:n.id,dry_run:S,changed:f,history:{path:n.historyPath,entries_scanned:a.length,chain_drift_before:!y.ok,entries_rehashed:l.entriesRehashed,entries_patch_repaired:l.entriesPatchRepaired,converted_replace_to_add:l.convertedReplaceToAdd,skipped_ops:l.skippedOps,reconciled_with_item:p,audit_entry_added:Z,verify_ok:R.ok,verify_errors:R.errors},item:{exists:d.currentItemPath!==null,path:d.currentItemPath,matched_chain_before:d.matchedChainBefore},...r?{reconciliation:r}:{},warnings:[...new Set(g)].sort((ee,te)=>ee.localeCompare(te)),generated_at:I()}}function ke(e,t){if(t&&e!==void 0)throw new _("history-repair: <id> and --all are mutually exclusive; pass an item id to repair one stream or --all to repair every drifted stream.",m.USAGE);if(!t&&e===void 0)throw new _("history-repair: provide an item <id> or pass --all to repair every drifted stream.",m.USAGE)}async function Ce(e,t){let i=b(process.cwd(),t.path);if(!await v(x(i)))throw new _(`Tracker is not initialized at ${i}. Run pm init first.`,m.NOT_FOUND);let s=await A(i),o=P(s,k()),c=[],n=await G(i,s.item_format,o.type_to_folder,c,s.schema,{forceSourceScan:!0}),u=await q(i,n),a=[],y=[],l={repaired:0,skipped_clean:0,failed:0};for(let d of u.driftedItems)try{let h=await ce(d,{...e,auditContext:e.auditContextById?.[d],auditContextById:void 0},t),p=h.changed?"repaired":"skipped_clean";l[p]+=1,y.push(...h.warnings.map(r=>`${d}:${r}`)),a.push({id:d,outcome:p,entries_rehashed:h.history.entries_rehashed,entries_patch_repaired:h.history.entries_patch_repaired,reconciled_with_item:h.history.reconciled_with_item,...h.reconciliation?{reconciliation:h.reconciliation}:{},warnings:h.warnings})}catch(h){l.failed+=1,a.push({id:d,outcome:"failed",error:h instanceof Error?h.message:String(h)})}return e.dryRun||await N(i),{all:!0,dry_run:!!e.dryRun,scanned_streams:n.length,drifted_streams:u.driftedItems.length,streams:a,totals:l,warnings:[...new Set([...c,...y])].sort((d,h)=>d.localeCompare(h)),generated_at:I()}}export{re as a,ce as b,ke as c,Ce as d};
|
|
2
|
+
//# sourceMappingURL=chunk-CS6MRHG7.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{qa as w,ra as I,ta as S,ua as g}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{qa as w,ra as I,ta as S,ua as g}from"./chunk-NG6OXIBR.js";import{$f as h,A as u,C as m,Da as f,La as y,Nf as _,Rf as x,Vf as b}from"./chunk-D4FPS43D.js";(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new i.Error().stack;t&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[t]="078456b8-ed61-5c47-afc7-7553833934e1")}catch{}})();var U=3,R=20,k=.8,N=100,A=1e3,D=1e6;function Q(i){return i===void 0?[]:[`likely_duplicates:${i.result.items.map(t=>t.id).join(",")}`]}function C(i){let t=i.limit??U,s=i.threshold??k;if(!Number.isSafeInteger(t)||t<0||t>R)throw new m(`Similarity limit must be an integer from 0 to ${R}.`,u.USAGE);if(!Number.isFinite(s)||s<0||s>1)throw new m("Similarity threshold must be a number from 0 to 1.",u.USAGE);return{limit:t,threshold:s}}function O(i){let t=i.limit??N;if(!Number.isSafeInteger(t)||t<0||t>A)throw new m(`Duplicate cluster limit must be an integer from 0 to ${A}.`,u.USAGE);let s=i.since===void 0?void 0:new Date(i.since);if(s&&Number.isNaN(s.getTime()))throw new m("Duplicate cluster --since must be a valid ISO timestamp.",u.USAGE);return{limit:t,since:s}}async function $(i,t){let s=y(i.cwd??process.cwd(),i.pmRoot),o=await _(s),n=f(o),e=i.statuses?new Set(i.statuses.map(r=>r.trim()).filter(Boolean)):void 0;return(await h(s,o.item_format,n.type_to_folder,void 0,o.schema)).filter(r=>(!e||e.has(r.status))&&(!t||new Date(r.created_at).getTime()>=t.getTime())).sort((r,c)=>r.id.localeCompare(c.id)).map(r=>({item:r,prepared:I(r.title)}))}function L(i,t=D){let s=new Set,o=[new Map,new Map,new Map];for(let[n,e]of i.entries()){let r=[[e.prepared.normalized],e.prepared.issueCodes,e.prepared.tokens];for(let[c,a]of r.entries())for(let l of a){let d=o[c].get(l)??[];for(let p of d)s.add(`${p}:${n}`);if(s.size>t)throw new m(`Duplicate sweep exceeded ${D} candidate pairs; narrow it with statuses or since.`,u.CONFLICT,{code:"duplicate_sweep_cost_limit",required:"Narrow the batch duplicate query until its deterministic candidate set fits the disclosed safety bound."});d.push(n),o[c].set(l,d)}}return s}var Z={buildDuplicateClusters:E,collectDuplicateCandidatePairs:L,createDuplicateUnionFind:M};function M(i){let t=Array.from({length:i},(o,n)=>n);return{parent:t,findRoot:o=>{let n=o;for(;t[n]!==n;)n=t[n];for(;t[o]!==o;){let e=t[o];t[o]=n,o=e}return n}}}function P(i,t,s,o){let n=[];for(let e of t){let[r,c]=e.split(":").map(p=>Number.parseInt(p,10)),a=g(i[r].prepared,i[c].prepared);if(a.score<s)continue;let l=o.findRoot(r),d=o.findRoot(c);l!==d&&(o.parent[d]=l),n.push({left_id:i[r].item.id,right_id:i[c].item.id,...a})}return n}function E(i,t,s,o){let n=new Map;for(let e of i.keys()){let r=s.findRoot(e),c=n.get(r)??[];c.push(e),n.set(r,c)}return[...n.values()].filter(e=>e.length>1).map(e=>{let r=new Set(e.map(a=>i[a].item.id)),c=t.filter(a=>r.has(a.left_id)&&r.has(a.right_id)).sort((a,l)=>l.score-a.score||a.left_id.localeCompare(l.left_id)||a.right_id.localeCompare(l.right_id));return{id:i[e[0]].item.id,items:e.map(a=>{let l=i[a].item;return{id:l.id,title:l.title,status:l.status,type:l.type}}),matches:c,max_score:c[0]?.score??0}}).sort((e,r)=>r.max_score-e.max_score||e.id.localeCompare(r.id)).slice(0,o)}function z(i,t,s,o,n){return t.filter(e=>!s.has(e.id)).map(e=>({id:e.id,title:e.title,status:e.status,type:e.type,...S(i,e.title)})).filter(e=>e.score>=o).sort((e,r)=>r.score-e.score||e.id.localeCompare(r.id)).slice(0,n)}async function F(i,t={}){let s=i.title.trim();if(s.length===0)throw new m("Similarity candidate title must not be empty.",u.USAGE);let{limit:o,threshold:n}=C(t),e=y(t.cwd??process.cwd(),t.pmRoot),r=await _(e),c=f(r),a=await b(e,Object.values(c.type_to_folder)),l=w(s),d=a&&l.length>0?await x({pmRoot:e,expectedSourceCursor:a.source_cursor,query:l.map(v=>`"${v.replaceAll('"','""')}"`).join(" OR "),limit:Math.max(o*10,50)}):null,p=d===null?await h(e,r.item_format,c.type_to_folder,void 0,r.schema):d.items,T=z(s,p,new Set(i.excludeIds??[]),n,o);return{items:T,count:T.length,threshold:n,source:d?"persistent_index":"metadata_fallback"}}async function ee(i={}){let{threshold:t}=C({...i,limit:void 0}),{limit:s,since:o}=O(i),n=await $(i,o),e=L(n),r=M(n.length),c=P(n,e,t,r),a=E(n,c,r,s);return{clusters:a,count:a.length,threshold:t,source:"metadata_scan",cost:{item_count:n.length,candidate_pairs:e.size,scored_pairs:e.size}}}async function te(i,t){if(t.mode==="off")return;let s=await F(i,t);if(s.count===0)return;let o=t.mode==="strict"&&t.allowDuplicate===!0;if(t.mode==="strict"&&!o){let n=s.items.map(e=>`${e.id} (${e.status}): ${e.title}`).join("; ");throw new m(`Likely duplicate item(s) found: ${n}. Reuse the canonical item or pass --allow-duplicate with explicit intent.`,u.CONFLICT,{code:"likely_duplicate",required:"Reuse an existing item, or explicitly acknowledge the duplicate with --allow-duplicate.",recovery:{suggested_flags:["--allow-duplicate"]}})}return{mode:t.mode,bypassed:o,result:s}}export{Q as a,Z as b,F as c,ee as d,te as e};
|
|
2
|
+
//# sourceMappingURL=chunk-CUGNQQKH.js.map
|