@unbrained/pm-cli 2026.8.4 → 2026.8.5
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 +39 -13
- package/dist/cli/error-guidance.js +4 -4
- package/dist/cli/register-structured-mutation.d.ts +2 -0
- package/dist/cli/register-structured-mutation.js +124 -12
- package/dist/cli-bundle/bundle-manifest.json +407 -407
- package/dist/cli-bundle/chunks/append-VXXGOXSG.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-QVO3VTA4.js → chunk-2WFXWAYX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NM5G7RLU.js → chunk-3FTILRJ2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-VH2EAGUG.js → chunk-42E7YPLG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-RB65T4RX.js → chunk-43HQQI6S.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-J4EPW4GT.js → chunk-45G53IU4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PQXEB7W4.js → chunk-4VN6GS4U.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-4YUBDMQM.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-D2MBVMVE.js → chunk-54FNT7U2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NRDKVOUE.js → chunk-5ZBOIPGP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-3XZYTRPC.js → chunk-6MSQJOTG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-GOICHIX4.js → chunk-7A5OT5J2.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HTYC76A4.js → chunk-7C4PTJG6.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BKMZTZYL.js → chunk-A62CYISG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-5H47J5FG.js → chunk-BPELKUQD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HE3DZFN4.js → chunk-BXQLRKWF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-BLINBTMX.js → chunk-CSI3WS5I.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KH4GVBMC.js → chunk-DXDREUXT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-KIKLF2W4.js → chunk-E2RKBKWB.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-377OOXUF.js → chunk-EGJ4JTUG.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SULWTPQO.js → chunk-FPBQHMFT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-V5K52PYW.js → chunk-GE4KCSZP.js} +35 -35
- package/dist/cli-bundle/chunks/{chunk-NPUJ7OLK.js → chunk-HNFD72UK.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QMWUL66F.js → chunk-HWRRMBJO.js} +5 -5
- package/dist/cli-bundle/chunks/chunk-L3AZOELJ.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-CGY5I2GO.js → chunk-LKDGK44W.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-LN2WFEU4.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-ZSH4GNBH.js → chunk-M72BKL5Q.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HQ2WU7OY.js → chunk-MHK6LIWE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-H6FITE7D.js → chunk-NE5VRDAI.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-NY4T3JWN.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-DCJ6CM6F.js → chunk-OMXVBQ2N.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-OPVH7SKD.js +8 -0
- package/dist/cli-bundle/chunks/{chunk-CU5ENFNP.js → chunk-OTHLDSFP.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NH35JNK5.js → chunk-PMXJEU3F.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SVDH5CHC.js → chunk-Q35VBGOQ.js} +4 -4
- package/dist/cli-bundle/chunks/{chunk-5PZGZMPG.js → chunk-R546TPDE.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-Q5F6OI7C.js → chunk-RKAVWO3O.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JMKVCQSE.js → chunk-SSF4PIUR.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-PA5XRN2A.js → chunk-UN66FZRO.js} +3 -3
- package/dist/cli-bundle/chunks/{chunk-FQ4EFFDU.js → chunk-UP7DTVMD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-NFF3JAQR.js → chunk-UZBWIUYD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-2POYGY53.js → chunk-V3774P7D.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-B5ZLCD5Z.js → chunk-V3EUXXOF.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-6S7I3UKV.js → chunk-VCKLFEUN.js} +19 -19
- package/dist/cli-bundle/chunks/{chunk-PYYPQLHC.js → chunk-VN5VITU3.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-WRL4KNDL.js +20 -0
- package/dist/cli-bundle/chunks/{chunk-UJHUR3LZ.js → chunk-XCEZYMNI.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-JDPKBV5P.js → chunk-YEWNL576.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OB7TRZ2G.js → chunk-YSO3YFZ4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-UVZREFZU.js → chunk-ZYHOB3SN.js} +2 -2
- package/dist/cli-bundle/chunks/close-VZ3OQPN5.js +2 -0
- package/dist/cli-bundle/chunks/close-many-SB4TI27P.js +2 -0
- package/dist/cli-bundle/chunks/comments-BIF3Q4KY.js +2 -0
- package/dist/cli-bundle/chunks/copy-6AI5Z57X.js +2 -0
- package/dist/cli-bundle/chunks/{create-RLLCBCXM.js → create-XLKTXTUF.js} +2 -2
- package/dist/cli-bundle/chunks/delete-ZY2VHQTP.js +2 -0
- package/dist/cli-bundle/chunks/{deps-J4ONTF4X.js → deps-ITTY3GIC.js} +2 -2
- package/dist/cli-bundle/chunks/{docs-YL2DJ4WD.js → docs-W4OSRTYR.js} +2 -2
- package/dist/cli-bundle/chunks/{files-NGNAIYKK.js → files-EOK4AZI4.js} +2 -2
- package/dist/cli-bundle/chunks/focus-DLBNWL7L.js +2 -0
- package/dist/cli-bundle/chunks/{history-compact-HW62K5XP.js → history-compact-7UGTMLL3.js} +2 -2
- package/dist/cli-bundle/chunks/{history-redact-HVBKUJOW.js → history-redact-4DZRMD6Z.js} +2 -2
- package/dist/cli-bundle/chunks/{history-repair-OPNBH5JJ.js → history-repair-UPOSZW5R.js} +2 -2
- package/dist/cli-bundle/chunks/{learnings-F36PZXT6.js → learnings-GMRNCBS3.js} +2 -2
- package/dist/cli-bundle/chunks/{profile-N3XMWBM7.js → profile-2MUUMHRE.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-BKGHBI7Y.js → register-list-query-LR3SQ5ZF.js} +2 -2
- package/dist/cli-bundle/chunks/register-mutation-SUOHFVWM.js +20 -0
- package/dist/cli-bundle/chunks/register-operations-ARRRKOVN.js +2 -0
- package/dist/cli-bundle/chunks/{register-setup-KWV6UD77.js → register-setup-O6AYP6NP.js} +2 -2
- package/dist/cli-bundle/chunks/restore-ZVCVHTB5.js +2 -0
- package/dist/cli-bundle/chunks/{schema-4PJQMGUY.js → schema-FJ4EA3XF.js} +2 -2
- package/dist/cli-bundle/chunks/update-YHV52CSS.js +2 -0
- package/dist/cli-bundle/chunks/update-many-M6YHVNXM.js +2 -0
- package/dist/cli-bundle/focused-chunks/chunk-7J5TUBUJ.js +153 -0
- package/dist/cli-bundle/focused-chunks/{chunk-ONIX2KKW.js → chunk-A7BJ5SS6.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-B7LJWAZE.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-QM2BIVK7.js → chunk-BIMTMOS7.js} +3 -3
- package/dist/cli-bundle/focused-chunks/{chunk-BOGRY7M6.js → chunk-FGKY4MBE.js} +10 -10
- package/dist/cli-bundle/focused-chunks/chunk-G6ETT4QK.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C2QSL62X.js → chunk-GJ2TG2CW.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-RO5BQFG3.js → chunk-IPWSFADF.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-UFCPSWIL.js → chunk-MJ7HWSFK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-2VIIXOAD.js → chunk-N5XU5UVK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-PG2RIZBX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-OYTK4VNH.js → chunk-PIMMYG7Q.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-K37BB4JL.js → chunk-QVHKCI4T.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-SQXVGHMH.js → chunk-RUR5I3TK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-SV3O7TSH.js +8 -0
- package/dist/cli-bundle/focused-chunks/{chunk-L6A4NVQC.js → chunk-UIL2M2NA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-WVGJAD7L.js → chunk-VLYOEYML.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-W7BJEWHX.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-DQ4PLKEE.js → chunk-WEM2E2PE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-WVIVUWVL.js +5 -0
- package/dist/cli-bundle/focused-chunks/chunk-Y4LDYLLT.js +2 -0
- package/dist/cli-bundle/main.js +4 -4
- 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 +28 -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/loader.js +5 -2
- package/dist/core/item/item-format.js +14 -20
- package/dist/core/shared/constants.js +3 -2
- package/dist/core/store/item-store.js +2 -2
- package/dist/core/store/settings.js +2 -2
- package/dist/mcp/server.js +12 -6
- package/dist/mcp/tool-definitions.js +14 -7
- package/dist/sdk/cli-contracts/agent-output-contracts.d.ts +18 -18
- package/dist/sdk/cli-contracts/agent-output-contracts.js +51 -23
- package/dist/sdk/cli-contracts/commander-mutation-options.js +26 -2
- package/dist/sdk/cli-contracts/flag-contracts.d.ts +2 -0
- package/dist/sdk/cli-contracts/flag-contracts.js +28 -2
- package/dist/sdk/cli-contracts/registration-helpers.js +4 -2
- package/dist/sdk/cli-contracts/runtime-contracts.d.ts +10 -2
- package/dist/sdk/cli-contracts/runtime-contracts.js +20 -5
- package/dist/sdk/cli-contracts/tool-schema.js +4 -2
- package/dist/sdk/cli-contracts.d.ts +2 -2
- package/dist/sdk/cli-contracts.js +4 -4
- package/dist/sdk/cli-program.js +3 -3
- package/dist/sdk/contracts.d.ts +1 -0
- package/dist/sdk/contracts.js +3 -2
- package/dist/sdk/dependency-provenance.d.ts +2 -0
- package/dist/sdk/dependency-provenance.js +7 -3
- package/dist/sdk/error-code-catalog.d.ts +23 -0
- package/dist/sdk/error-code-catalog.js +25 -5
- package/dist/sdk/generated-error-code-catalog.js +499 -3
- package/dist/sdk/graph/governance.js +3 -3
- package/dist/sdk/graph/remediation.js +3 -3
- package/dist/sdk/graph/run.js +4 -8
- package/dist/sdk/index.d.ts +2 -1
- package/dist/sdk/index.js +4 -3
- package/dist/sdk/item-transaction.d.ts +51 -6
- package/dist/sdk/item-transaction.js +132 -22
- package/dist/sdk/lifecycle/create.d.ts +4 -0
- package/dist/sdk/lifecycle/create.js +26 -10
- package/dist/sdk/lifecycle-policy.d.ts +9 -0
- package/dist/sdk/lifecycle-policy.js +22 -9
- package/dist/sdk/merge/driver.js +6 -3
- package/dist/sdk/output-contracts.d.ts +67 -0
- package/dist/sdk/output-contracts.js +173 -0
- package/dist/sdk/package-import-adapters.js +2 -2
- package/dist/sdk/structured-mutations.d.ts +23 -0
- package/dist/sdk/structured-mutations.js +219 -10
- package/dist/sdk/workspace-snapshot.js +58 -12
- package/dist/sdk/workspace.js +30 -4
- package/docs/COMMANDS.md +40 -10
- package/docs/EXTENSIONS.md +1 -1
- package/docs/MERGE_SAFETY.md +2 -0
- package/docs/PR_REVIEW_LOOP.md +10 -4
- package/docs/README.md +22 -22
- package/docs/RELEASING.md +3 -3
- package/docs/SCRIPTING.md +32 -9
- package/docs/SDK.md +91 -11
- package/docs/SELF_DESCRIBING_CONTEXT_CONTRACTS.md +13 -0
- package/docs/TESTING.md +25 -0
- package/docs/examples/sdk-contract-consumer/README.md +11 -1
- package/docs/examples/sdk-contract-consumer/package.json +2 -1
- package/docs/examples/sdk-contract-consumer/parse-receipt.mjs +22 -0
- package/marketplace.json +2 -2
- package/package.json +3 -2
- 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 +292 -14
- package/dist/cli-bundle/chunks/append-DHBRLHHS.js +0 -2
- package/dist/cli-bundle/chunks/chunk-2INN52SU.js +0 -8
- package/dist/cli-bundle/chunks/chunk-6RSK4IFN.js +0 -20
- package/dist/cli-bundle/chunks/chunk-ASJJKA57.js +0 -2
- package/dist/cli-bundle/chunks/chunk-IYAVULRN.js +0 -2
- package/dist/cli-bundle/chunks/chunk-RRQBHQOV.js +0 -2
- package/dist/cli-bundle/chunks/chunk-XBLOD5TZ.js +0 -2
- package/dist/cli-bundle/chunks/close-VLHNN6YB.js +0 -2
- package/dist/cli-bundle/chunks/close-many-LSJNZKU6.js +0 -2
- package/dist/cli-bundle/chunks/comments-AAIA6A6X.js +0 -2
- package/dist/cli-bundle/chunks/copy-Z7YMLEHN.js +0 -2
- package/dist/cli-bundle/chunks/delete-KNOHHQJM.js +0 -2
- package/dist/cli-bundle/chunks/focus-LFRCGALV.js +0 -2
- package/dist/cli-bundle/chunks/register-mutation-GU3DCECN.js +0 -20
- package/dist/cli-bundle/chunks/register-operations-PTWH727R.js +0 -2
- package/dist/cli-bundle/chunks/restore-4HZSLILR.js +0 -2
- package/dist/cli-bundle/chunks/update-E6LPS5IV.js +0 -2
- package/dist/cli-bundle/chunks/update-many-OSIC6KRO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-5MTKO7TV.js +0 -153
- package/dist/cli-bundle/focused-chunks/chunk-6GIZK7VQ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-AOP2WIZZ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-CL75YW32.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-E7OFMWGT.js +0 -8
- package/dist/cli-bundle/focused-chunks/chunk-I5F5UK3Q.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-T5TSY36R.js +0 -5
- package/dist/cli-bundle/focused-chunks/chunk-VT6BF2IX.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{a as q}from"./chunk-
|
|
2
|
-
//# sourceMappingURL=chunk-
|
|
1
|
+
import{a as q}from"./chunk-E2RKBKWB.js";import{f as M,g as V,h as X}from"./chunk-ZYHOB3SN.js";import{a as E}from"./chunk-BPELKUQD.js";import{A as m,Ad as D,Af as A,C as _,Da as P,La as b,Mf as W,Oa as x,Pf as G,R as I,Ve as N,b as v,bf as w,c as $,ef as j,ff as L,hf as C,if as z,jf as U,lc as k,uc as F,zd as T}from"./chunk-GE4KCSZP.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-V3EUXXOF.js.map
|
|
@@ -1,23 +1,23 @@
|
|
|
1
|
-
import{s as ut}from"./chunk-
|
|
2
|
-
`)}function
|
|
3
|
-
`)}async function
|
|
1
|
+
import{s as ut}from"./chunk-SSF4PIUR.js";import{a as rt,b as pe,c as me,d as it,e as st,f as j,g as _e,h as at,i as q}from"./chunk-M72BKL5Q.js";import{A as h,Af as b,Ba as et,C as y,Ca as tt,Cf as ct,Da as R,H as Xe,Hc as P,Ic as nt,If as lt,Jc as x,Kc as M,La as A,Lf as dt,Mf as ft,Nc as ue,O as Ve,Oa as ne,Of as Z,Pc as we,R as k,Sf as xe,Z as Qe,b as U,c as I,d as Y,da as Ie,ea as Ae,fa as Re,lc as v,mf as F,pf as ve,rf as ot,uc as D,v as Ze,xf as N,zd as C}from"./chunk-GE4KCSZP.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 J(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 J(e.pmRoot,i),await z(e,i,"prepared")}return{journal:i,recovered:s}}async function bn(e,t,o){try{await Tn(t,e.steps),await J(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 J(e.pmRoot,t);let l=await i.apply();a=Fe(l,`Step ${i.id} result`)}await z(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 J(e.pmRoot,t),await z(e,t,"step_recorded",i.id)}return await z(e,t,"committing"),t.status="committed",await J(e.pmRoot,t),await z(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 z(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 J(e.pmRoot,t),await z(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 z(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 J(e.pmRoot,t),await z(e,t,"step_compensated",r.id)}t.status="compensated",await J(e.pmRoot,t),await z(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/"],Rn=["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 vn(e=Tt){let t=$t(e);return[Et,...An.map(o=>o==="search/"?`${t}/${o}*`:`${t}/${o}`),...Rn.map(o=>`!${t}/${o}`),Oe].join(`
|
|
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
5
|
`:""}${vn(n)}
|
|
6
|
-
`;return l===r?{path:o,changed:!1}:(await
|
|
7
|
-
`),s=r.indexOf(
|
|
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 xn}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]="1729579e-ef08-55c3-914f-c025ba3033e4")}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 Rt(){let e=Qe(import.meta.url,["../../.."]);return`${It(process.execPath)} ${It(S.join(e,"dist","cli.js"))}`}var vt=[{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 xt(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 H(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 U(o.value)||!await U(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=[`${H(`${o}**/*.toon`)} merge=pm-item-toon`,`${H(`${o}**/*.md`)} merge=pm-item-markdown`];for(let r of t)n.push(`${H(`${o}${r}/*.toon`)} merge=pm-item-toon`),n.push(`${H(`${o}${r}/*.md`)} merge=pm-item-markdown`);return n.push(`${H(`${o}**/*.jsonl`)} merge=pm-relationship`),n.push(`${H(`${o}history/*.jsonl`)} merge=pm-history`),n.push(`${H(`${o}settings.json`)} merge=pm-json`),n.push(`${H(`${o}**/*.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
|
+
`),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 xn(n,f,"utf8"),{path:n,changed:!0})}function
|
|
11
|
-
`).map(p=>p.trim()).filter(p=>p.length>0):[],f=Ue(Me(n,o),t),d=new Set(l),
|
|
12
|
-
`}function
|
|
13
|
-
`}function
|
|
14
|
-
`}function Vt(e,t){if(t.kind==="rename-type"){let n=j(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
|
|
15
|
-
`)}function
|
|
16
|
-
`)}import Eo from"node:path";import{mkdir as Io}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"],ko={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 Qt(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 ko[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 bo=/^([A-Za-z][A-Za-z0-9_-]*?)\s*[-:]\s+\S/;function To(e){let t=bo.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 en(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 mi=["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"],Te="schema-types",tn="schema-statuses",nn="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 hi(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 g(m instanceof Error?m.message:String(m),y.USAGE)}let i=await b(n),s=R(i.schema),a=M(n,s.files.types,O.types),c=[],l=C(t.author,i.author_default),f=N(i),d=await F(n,Te,i.locks.ttl_seconds,l,!!t.force,f.force_required_for_stale_lock,i.locks.wait_ms),h;try{let m=await I(a),u;try{u=j(m)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.GENERIC_FAILURE)}try{it(r,u);let p=new Map,w=v(i,x());for(let[T,_]of Object.entries(w.type_to_folder)){let E=_.trim().toLowerCase();E.length>0&&!p.has(E)&&p.set(E,T)}st(r,u,p)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}h=_e(u,r),h.replaced&&h.previousName!==void 0&&h.previousName!==h.definition.name&&c.push(`type_recased:${h.previousName}->${h.definition.name}`),await K({pmRoot:n,filePath:a,raw:q(h.file),op:"schema:add-type",author:l,settings:i}),await Ke(n,[h.definition],c,"schema:add-type-folder"),c.push(...await D({path:a,scope:"project",op:"schema:add-type"}))}finally{await d()}return await on(n,c),{action:"add-type",registered:!0,replaced:h.replaced,type:h.definition,file:{path:a,definitions:h.file.definitions.length},warnings:B(c),generated_at:k()}}async function G(e){if(!await U(ne(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,y.NOT_FOUND)}async function on(e,t){try{let o=await Ft(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 Ao(e,t,o,n){let r=v(t,x()),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=v(t,x()),i=ue(o),s=$(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($(l))??$(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=rn(n.workflow,r);s.length>0&&e.push(`status_referenced_by_workflow:${s.join(",")}`)}function rn(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&&$(n)===t).map(([n])=>n)}async function yi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=R(r.schema),s=M(n,i.files.types,O.types),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,Te,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let h=await I(s),m;try{m=j(h)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.GENERIC_FAILURE)}try{d=at(m,e)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.USAGE)}if(d.removed){let u=(d.definition?.name??e??"").trim();if(u.length>0){let p=await Ao(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 on(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,O.statuses)}function $e(e,t){return M(e,t.files.fields,O.fields)}function sn(e,t){return M(e,t.files.types,O.types)}async function Ke(e,t,o,n){for(let r of t){let i=tt(r.folder??et(r.name)),s=Eo.join(e,i);await U(s)||(await Io(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 Ro(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 Co(e){let t=new Map;for(let o of e){let n=$(o.id);if(n.length!==0){t.set(n,n);for(let r of Array.isArray(o.aliases)?o.aliases:[]){let i=$(r);i.length>0&&!t.has(i)&&t.set(i,n)}}}return t}async function gi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{r=zt({id:e,roles:t.role,aliases:t.alias,description:t.description,order:t.order})}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}let i=await b(n),s=R(i.schema),a=We(n,s),c=ue(s);try{je(r,c.alias_to_id)}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}let l=Ro(c.by_id.get(r.id)),f=[],d=C(t.author,i.author_default),h=N(i),m=await F(n,tn,i.locks.ttl_seconds,d,!!t.force,h.force_required_for_stale_lock,i.locks.wait_ms),u;try{let p=await I(a),w;try{w=ie(p)}catch(_){throw new g(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}let T=Co(w.statuses);try{je(r,T)}catch(_){throw new g(_ instanceof Error?_.message:String(_),y.USAGE)}u=Gt(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 wi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=R(r.schema),s=We(n,i),a=[],c=C(t.author,r.author_default),l=N(r),f=await F(n,tn,r.locks.ttl_seconds,c,!!t.force,l.force_required_for_stale_lock,r.locks.wait_ms),d;try{let h=await I(s),m;try{m=ie(h)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.GENERIC_FAILURE)}try{d=qt(m,e)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.USAGE)}if(d.removed){let u=$(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 an(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 Fo(e,t,o){return{...an(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 cn(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 ln(e,t,o){let n=e.toLowerCase();return o.has(n)?"extension":t.has(n)?"custom":"builtin"}function Oo(){let e=new Map,t=x();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 Po(e){let t=ue(e),o=[],n=[];for(let r of t.definitions){let i=cn(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=R(o.schema),r=M(t,n.files.types,O.types),i=We(t,n),s=v(o,x()),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 _i(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=ln(a.name,t.customNames,new Set(t.extensionProvenance.keys())),l=an(a);c==="extension"?r.push(l):c==="custom"?n.push(l):o.push(l)}let i=Po(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 Si(e,t){let o=(e??"").trim();if(o.length===0)throw new g("Type name must not be empty.",y.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 g(`Unknown item type "${o}". Run pm schema list to inspect registered types, or pm schema add-type "${pe(o)}" to register it.`,y.NOT_FOUND,{code:"unknown_item_type"});return{action:"show",type:Fo(r,ln(r.name,n.customNames,new Set(n.extensionProvenance.keys())),n.extensionProvenance.get(r.name.toLowerCase())),file:{path:n.typesPath},generated_at:k()}}async function ki(e,t){let o=$(e);if(o.length===0)throw new g("Status id must not be empty.",y.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 g(`Unknown status "${e}". Run pm schema list to inspect registered statuses, or pm schema add-status "${pe(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_status"});return{action:"show-status",status:cn(s),file:{path:n.statusesPath},generated_at:k()}}async function bi(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{r=Mt({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 g(u instanceof Error?u.message:String(u),y.USAGE)}let i=await b(n),s=R(i.schema),a=$e(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),h=await F(n,nn,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 g(w instanceof Error?w.message:String(w),y.GENERIC_FAILURE)}m=Ut(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 h()}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 No(e,t,o,n){let r=v(t,x());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 Ti(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r=await b(n),i=R(r.schema),s=$e(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 h=await I(s),m;try{m=oe(h)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.GENERIC_FAILURE)}try{d=jt(m,e)}catch(u){throw new g(u instanceof Error?u.message:String(u),y.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 No(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 $i(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:$e(t.pmRoot,t.schema)},generated_at:k()}}async function Ei(e,t){let o=L(e);if(o.length===0)throw new g("Field key must not be empty.",y.USAGE);let n=await ge(t),r=we(n.schema).by_key.get(o);if(!r)throw new g(`Unknown custom field "${e}". Run pm schema list-fields to inspect registered fields, or pm schema add-field "${pe(e??"")}" to register it.`,y.NOT_FOUND,{code:"unknown_field"});return{action:"show-field",field:Be(r),file:{path:$e(n.pmRoot,n.schema)},generated_at:k()}}async function Ii(e,t,o){let n=A(process.cwd(),o.path);await G(n);let r;try{let p=Qt(e);if(p===void 0)throw new Error(`Type preset name is required. Allowed: ${Je.join(", ")}.`);r=p}catch(p){throw new g(p instanceof Error?p.message:String(p),y.USAGE)}let i=await b(n),s=R(i.schema),a=sn(n,s),c=[],l=C(t.author,i.author_default),f=N(i),d=[],h=[],m,u=await F(n,Te,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 g(_ instanceof Error?_.message:String(_),y.GENERIC_FAILURE)}let T=w;for(let _ of He(r)){let E=_e(T,_);T=E.file,(E.replaced?h:d).push(E.definition.name)}m=T.definitions.length,await K({pmRoot:n,filePath:a,raw:q(T),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:h,file:{path:a,definitions:m},warnings:B(c),generated_at:k()}}function Lo(e){if(e===void 0)return 10;if(!Number.isInteger(e)||e<1)throw new g("--min-count must be a positive integer (>= 1).",y.USAGE);return e}async function Ai(e,t){let o=A(process.cwd(),t.path);await G(o);let n=await b(o),r=R(n.schema),i=sn(o,r),s=Lo(e.minCount),a=v(n,x()),l=(await Z(o,n.item_format,a.type_to_folder,[],r)).map(E=>typeof E.title=="string"?E.title:""),f=en(l,{minCount:s}),d=[],h=[],m=[],u=[],p;if(!e.apply){let E;try{E=j(await I(i))}catch(te){throw new g(te instanceof Error?te.message:String(te),y.GENERIC_FAILURE)}return p=E.definitions.length,{action:"infer-types",applied:!1,min_count:s,candidates:f,registered:h,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:d,generated_at:k()}}let w=C(e.author,n.author_default),T=N(n),_=await F(o,Te,n.locks.ttl_seconds,w,!!e.force,T.force_required_for_stale_lock,n.locks.wait_ms);try{let E=await I(i),te;try{te=j(E)}catch(P){throw new g(P instanceof Error?P.message:String(P),y.GENERIC_FAILURE)}let fe=te;for(let P of f){if(P.shadows_builtin){u.push({name:P.name,reason:"shadows_builtin"});continue}let Ye;try{Ye=me({name:P.name})}catch{u.push({name:P.name,reason:"invalid_type_token"});continue}let Ee=_e(fe,Ye);fe=Ee.file,(Ee.replaced?m:h).push(Ee.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(P=>h.includes(P.name)||m.includes(P.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:h,replaced:m,skipped:u,file:{path:i,definitions:p},warnings:B(d),generated_at:k()}}function vi(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 xi(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 Ri(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 Ci(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 Fi(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
|
-
`)}function
|
|
18
|
-
`)}function
|
|
19
|
-
`)}function
|
|
20
|
-
`)}function
|
|
21
|
-
`)}function
|
|
22
|
-
`)}var
|
|
23
|
-
//# sourceMappingURL=chunk-
|
|
10
|
+
`;return f===r?{path:n,changed:!1}:(o||await xn(n,f,"utf8"),{path:n,changed:!0})}function Ft(e){let t=R(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=Rt(),o=[],n=[];for(let r of vt){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 xt(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 U(ne(s)))throw new y(`Tracker is not initialized at ${s}. Run pm init first.`,h.NOT_FOUND);let a=await xt(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=Rt();for(let m of vt)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(Re),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: ${Re.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
|
+
`}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=x(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=j(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 q(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 q(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=j(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=R(e.settings,v()),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=R(t,v()).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=R(t,v()).type_to_folder,n=await xe({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=R(t,v()).type_to_folder;await xe({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=x(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 ve({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 U(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 ve({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 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(`
|
|
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
|
+
`)}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
|
+
`)}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
|
+
`)}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
|
+
`)}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,vn 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,Ri as T,vi as U,xi 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-VCKLFEUN.js.map
|
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{F as it,G as lt,H as ot,I as ct,J as Y,K as F,L as ut,M as ft,N as pt,O as yt,a as qe,b as He,c as Xe,d as Ze,e as Je,f as Qe,g as xe,h as K,i as et,j as R,k as tt,l as at,m as nt,n as rt,o as st,p as dt}from"./chunk-
|
|
1
|
+
import{F as it,G as lt,H as ot,I as ct,J as Y,K as F,L as ut,M as ft,N as pt,O as yt,a as qe,b as He,c as Xe,d as Ze,e as Je,f as Qe,g as xe,h as K,i as et,j as R,k as tt,l as at,m as nt,n as rt,o as st,p as dt}from"./chunk-HWRRMBJO.js";import{d as z,e as W}from"./chunk-L3AZOELJ.js";import{c as Ye}from"./chunk-PMXJEU3F.js";import{j as Se,l as Ee,m as Te,n as Le,p as Pe}from"./chunk-A62CYISG.js";import{b as Ge,c as Be,d as Ve}from"./chunk-RSIC5OPE.js";import{a as ke,b as Ie,c as Ue,d as De,e as Fe,f as G,g as Oe,h as B,i as Me,j as Ce,k as Ne}from"./chunk-42E7YPLG.js";import{k as $e}from"./chunk-M72BKL5Q.js";import{A as o,Aa as _,Af as je,C as c,Cb as U,Da as ce,Ea as I,Ec as ge,Fa as ue,Fc as he,Ga as fe,Gc as we,Ha as $,La as pe,Lc as _e,Lf as b,Mf as V,Nc as ve,Oa as ye,Of as ze,Pc as Ae,Rf as j,Sf as We,V as N,Vc as be,ad as g,b as de,cd as Ke,ga as L,ia as ie,ja as le,lc as me,uf as D,ya as P,za as oe,zd as Re}from"./chunk-GE4KCSZP.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]="ada579bd-134d-5201-9221-6ce39d282a37")}catch{}})();var Q=[...it,{canonical:"close-reason",aliases:["close_reason","close-reason"],optionKey:"closeReason",metadataKey:"close_reason"},...lt,...ot],zt=(()=>{let e=new Map;for(let t of Q)for(let r of t.aliases)e.set(r,{optionKey:t.optionKey,metadataKey:t.metadataKey});return e})(),O=new Map(Q.map(e=>[e.optionKey,e.canonical])),Wt=Q.map(e=>e.canonical).sort((e,t)=>e.localeCompare(t)).join(", "),Yt=new Set(["close_reason","assignee","parent","blocked_by","blocked_reason","unblock_note","dependencies","comments","notes","learnings","files","tests","docs","reminders","events"]),qt=Je({depDisableFlagKey:"replaceDeps",fileDisableFlagKey:"replaceFiles",testDisableFlagKey:"replaceTests",docDisableFlagKey:"replaceDocs"});function At(e){let t={...e,unset:e.unset?[...e.unset]:void 0},r=a=>{let n=t.unset?[...t.unset]:[];n.includes(a)||n.push(a),t.unset=n},s=new Set([...O.keys(),"rank"]);for(let a of s){let n=t[a];if(typeof n!="string"||!Qe(n))continue;let i=a==="rank"?"order":O.get(a)??a;r(i),t[a]=void 0}return et(t,qt)}function x(e,t,r=[]){return ct({raw:e,supportedFields:Wt,resolveDefinition:s=>{let a=r.find(i=>{let l=i.toLowerCase();return l===s||l.replaceAll("_","-")===s||l.replaceAll("-","_")===s});return zt.get(s)??Y(s,"update",t)??(a?{optionKey:"field",metadataKey:a}:void 0)}})}var mt=new Map([["--comment",e=>`pm comments ${e} --add "<text>" --force`],["--file",e=>`pm files ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`],["--doc",e=>`pm docs ${e} --add "path=<path>,scope=<scope>,note=<note>" --force`]]);function X(e){let t=e.disallowedFlags.flatMap(s=>{let a=mt.get(s);return a?[a(e.id)]:[]}),r=e.disallowedFlags.flatMap(s=>{let a=mt.get(s);return a?[`Replace ${s} with: ${a(e.id)}`]:[]});return new c(e.message,o.USAGE,{code:e.code,required:e.required,why:e.why,...t.length>0?{examples:t}:{},nextSteps:[`Re-run without: ${e.disallowedFlags.join(", ")}`,...r]})}function bt(e,t,r){let s=t.ownershipMetadataBypass===!0,a=t.ownershipDependencyBypass===!0;if(!s&&!a)return;if(s&&a)throw new c("Choose only one package-provided ownership bypass mode.",o.USAGE);let n=(d,u,p)=>{d&&p.push(u)};if(a){let d=[];if(n(t.title!==void 0,"--title",d),n(t.description!==void 0,"--description",d),n(t.body!==void 0,"--body",d),n(t.status!==void 0,"--status",d),n(t.closeReason!==void 0,"--close-reason",d),n(t.priority!==void 0,"--priority",d),n(t.type!==void 0,"--type",d),n(t.tags!==void 0,"--tags",d),n(Array.isArray(t.addTags)&&t.addTags.length>0,"--add-tags",d),n(Array.isArray(t.removeTags)&&t.removeTags.length>0,"--remove-tags",d),n(t.deadline!==void 0,"--deadline",d),n(t.estimatedMinutes!==void 0,"--estimate",d),n(t.acceptanceCriteria!==void 0,"--acceptance-criteria",d),n(Array.isArray(t.addAc)&&t.addAc.length>0,"--add-ac",d),n(Array.isArray(t.removeAc)&&t.removeAc.length>0,"--remove-ac",d),n(t.definitionOfReady!==void 0,"--definition-of-ready",d),n(t.order!==void 0||t.rank!==void 0,"--order/--rank",d),n(t.goal!==void 0,"--goal",d),n(t.objective!==void 0,"--objective",d),n(t.value!==void 0,"--value",d),n(t.impact!==void 0,"--impact",d),n(t.outcome!==void 0,"--outcome",d),n(t.whyNow!==void 0,"--why-now",d),n(t.assignee!==void 0,"--assignee",d),n(t.parent!==void 0,"--parent",d),n(t.reviewer!==void 0,"--reviewer",d),n(t.risk!==void 0,"--risk",d),n(t.confidence!==void 0,"--confidence",d),n(t.sprint!==void 0,"--sprint",d),n(t.release!==void 0,"--release",d),n(t.blockedBy!==void 0,"--blocked-by",d),n(t.blockedReason!==void 0,"--blocked-reason",d),n(t.unblockNote!==void 0,"--unblock-note",d),n(t.reporter!==void 0,"--reporter",d),n(t.severity!==void 0,"--severity",d),n(t.environment!==void 0,"--environment",d),n(t.reproSteps!==void 0,"--repro-steps",d),n(t.resolution!==void 0,"--resolution",d),n(t.expectedResult!==void 0,"--expected-result",d),n(t.actualResult!==void 0,"--actual-result",d),n(t.affectedVersion!==void 0,"--affected-version",d),n(t.fixedVersion!==void 0,"--fixed-version",d),n(t.component!==void 0,"--component",d),n(t.regression!==void 0,"--regression",d),n(t.customerImpact!==void 0,"--customer-impact",d),n(t.depRemove!==void 0,"--dep-remove",d),n(t.replaceDeps===!0,"--replace-deps",d),n(t.replaceTests===!0,"--replace-tests",d),n(t.replaceFiles===!0,"--replace-files",d),n(t.replaceDocs===!0,"--replace-docs",d),n(t.comment!==void 0,"--comment",d),n(t.note!==void 0,"--note",d),n(t.learning!==void 0,"--learning",d),n(t.file!==void 0,"--file",d),n(t.test!==void 0,"--test",d),n(t.doc!==void 0,"--doc",d),n(t.reminder!==void 0,"--reminder",d),n(t.event!==void 0,"--event",d),n(t.typeOption!==void 0,"--type-option",d),n(t.clearDeps===!0,"--clear-deps",d),n(t.clearComments===!0,"--clear-comments",d),n(t.clearNotes===!0,"--clear-notes",d),n(t.clearLearnings===!0,"--clear-learnings",d),n(t.clearFiles===!0,"--clear-files",d),n(t.clearTests===!0,"--clear-tests",d),n(t.clearDocs===!0,"--clear-docs",d),n(t.clearReminders===!0,"--clear-reminders",d),n(t.clearEvents===!0,"--clear-events",d),n(t.clearTypeOptions===!0,"--clear-type-options",d),n(t.force===!0,"--force",d),n(r.size>0,"--unset",d),t.dep===void 0||t.dep.length===0)throw new c("The dependency ownership bypass requires at least one --dep value",o.USAGE);if(d.length>0)throw X({id:e,code:"ownership_dependency_bypass_restricted_options",message:`The dependency ownership bypass supports append-only dependency additions via --dep. Remove restricted options: ${d.join(", ")}`,required:"Pass only --dep additions (plus --message/--author) with the dependency ownership bypass.",why:"the dependency ownership bypass is a narrow non-owner override scoped to append-only dependency additions; every other mutation keeps its normal ownership rules.",disallowedFlags:d});return}let i=[];n(t.status!==void 0,"--status",i),n(t.closeReason!==void 0,"--close-reason",i),n(t.assignee!==void 0,"--assignee",i),n(t.parent!==void 0,"--parent",i),n(t.blockedBy!==void 0,"--blocked-by",i),n(t.blockedReason!==void 0,"--blocked-reason",i),n(t.unblockNote!==void 0,"--unblock-note",i),n(t.dep!==void 0,"--dep",i),n(t.depRemove!==void 0,"--dep-remove",i),n(t.replaceDeps===!0,"--replace-deps",i),n(t.replaceTests===!0,"--replace-tests",i),n(t.replaceFiles===!0,"--replace-files",i),n(t.replaceDocs===!0,"--replace-docs",i),n(t.note!==void 0,"--note",i),n(t.learning!==void 0,"--learning",i),n(t.test!==void 0,"--test",i),n(t.reminder!==void 0,"--reminder",i),n(t.event!==void 0,"--event",i),n(t.clearDeps===!0,"--clear-deps",i),n(t.clearComments===!0,"--clear-comments",i),n(t.clearNotes===!0,"--clear-notes",i),n(t.clearLearnings===!0,"--clear-learnings",i),n(t.clearFiles===!0,"--clear-files",i),n(t.clearTests===!0,"--clear-tests",i),n(t.clearDocs===!0,"--clear-docs",i),n(t.clearReminders===!0,"--clear-reminders",i),n(t.clearEvents===!0,"--clear-events",i);let l=[...r].filter(d=>Yt.has(d)).sort((d,u)=>d.localeCompare(u)).map(d=>`--unset ${d.replaceAll("_","-")}`);if(i.push(...l),i.length>0)throw X({id:e,code:"ownership_metadata_bypass_restricted_options",message:`The metadata ownership bypass only supports non-lifecycle metadata fields and evidence appends. Remove restricted options: ${i.join(", ")}`,required:"Limit the metadata ownership bypass to non-lifecycle metadata fields plus append-only --comment/--file/--doc evidence; route restricted appends and lifecycle changes through their dedicated commands.",why:"the metadata ownership bypass is a non-owner override scoped to metadata maintenance and append-only evidence; lifecycle, ownership, dependency mutations, restricted append fields, and clear/replace operations keep their normal ownership rules.",disallowedFlags:i})}function Ht(e,t){let r=g(e,t);if(!r){let s=t.definitions.map(a=>a.id);throw new c(`Invalid --status value "${e}". Allowed: ${s.join(", ")}`,o.USAGE)}return r}function Kt(e){if(e.enforcement==="off"||e.typeWorkflows.length===0)return;let t=Be({typeName:e.typeName,fromStatus:e.fromStatus,toStatus:e.toStatus,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry});if(!t.hasRule||t.allowed)return;let r=g(e.fromStatus,e.statusRegistry)??e.fromStatus,s=g(e.toStatus,e.statusRegistry)??e.toStatus,a=`Disallowed transition for type "${e.typeName}": ${r} -> ${s}. Allowed transitions: ${Ve(t.allowedTransitions)}.`;if(e.enforcement==="strict")throw new c(a,o.USAGE);return`workflow_transition_not_allowed: ${a}`}function Xt(e,t){if(!e||e.trim()===""||e.trim().toLowerCase()==="now")return t;let r=Date.parse(e);if(!Number.isFinite(r))throw new c(`Invalid dependency created_at timestamp "${e}"`,o.USAGE);return new Date(r).toISOString()}function M(e){if(e===void 0)return;let t=e.trim();return t.length>0?t:void 0}var Zt=["id","kind","type","author","created_at","source_kind"],Jt=["id","kind","type","source_kind"];function Qt(e){return e.startsWith("```")||e.includes(`
|
|
2
2
|
`)||/^(?:[-*+]\s+)?(?:id|kind|type|author|created_at|source_kind)\s*[:=]/i.test(e)?!0:Oe(e)}var xt={"blocked-by":"blocked_by",depends_on:"blocked_by","depends-on":"blocked_by"};function Rt(e){if(typeof e!="string")return e;let t=e.trim();return xt[t.toLowerCase()]??t}function St(e,t,r,s){return e?(K(e,"--dep","Use --clear-deps to clear dependencies."),{additions:e.map(n=>{let i=n.trim(),l=Qt(i);rt(i,l);let d=l?G(n,"--dep"):{id:i,kind:"related"};l&&B(d,"--dep",Zt);let u=d.id?.trim(),p=Rt((d.kind??d.type)?.trim());if(!u||!p)throw new c("--dep requires id and kind, or a bare item id to add a related dependency",o.USAGE);if(u.toLowerCase()==="undefined")throw new c(`--dep id must not use placeholder token "${u}". Use --clear-deps to clear dependencies.`,o.USAGE);let f=z(M(d.source_kind)),S=M(d.author);return{id:W(u,t,f),kind:R(p,L,"dependency kind"),created_at:Xt(d.created_at,r),author:S??s,source_kind:f??"cli:update:dep",author_source:S?"asserted":"detected"}})}):{additions:[]}}function Et(e,t){return e?(K(e,"--dep-remove"),e.map(r=>{let s=r.trim();if(!s)throw new c("--dep-remove requires id or key/value selectors",o.USAGE);if(s.includes("=")||/^(?:[-*+]\s+)?(?:id|kind|type|source_kind)\s*[:=]/i.test(s)||s.startsWith("```")){let a=G(s,"--dep-remove");B(a,"--dep-remove",Jt);let n=a.id?.trim();if(!n)throw new c("--dep-remove key/value form requires id=<value>",o.USAGE);if(n.toLowerCase()==="undefined")throw new c(`--dep-remove id must not use placeholder token "${n}"`,o.USAGE);let i=Rt(M(a.kind??a.type)),l=z(M(a.source_kind));return{id:W(n,t,l),kind:i?R(i,L,"dependency kind"):void 0,source_kind:l}}if(s.toLowerCase()==="undefined")throw new c(`--dep-remove id must not use placeholder token "${s}"`,o.USAGE);return{id:D(s,t)}})):[]}function gt(e){let t=e.source_kind?.trim().toLowerCase()??"";return`${e.id.trim().toLowerCase()}::${e.kind}::${t}`}function Tt(e,t,r,s){let a=[...e??[]],n=!1;if(t===void 0){let i=a.filter(l=>l.kind!=="blocked_by");return i.length!==a.length&&(a=i,n=!0),n?{dependencies:a.length>0?a:void 0,changed:!0}:{dependencies:e,changed:!1}}return a.some(i=>i.kind==="blocked_by"&&i.id===t)||(a.push({id:t,kind:"blocked_by",created_at:r,author:s,source_kind:"cli:update:blocked_by",author_source:"detected"}),n=!0),n?{dependencies:a.length>0?a:void 0,changed:!0}:{dependencies:e,changed:!1}}async function ea(e,t,r,s,a,n){if(e===void 0||t)return{};let i=e.trim();if(i.length===0)return{};let l=await b(r,D(i,s),s,a,n);return l?{id:l.id}:{unresolved:i}}function ta(e,t,r,s,a){let n=Tt(e.dependencies,t,r,s);n.changed&&(n.dependencies===void 0?delete e.dependencies:e.dependencies=n.dependencies,a.includes("dependencies")||a.push("dependencies"))}function aa(e){return`${e.path}::${e.scope}`}function na(e){return`${e.path}::${e.scope}`}function ra(e){return`${e.command}::${e.path??""}::${e.scope}::${e.pm_context_mode??""}`}function kt(e,t){return!(e.id.trim().toLowerCase()!==t.id.trim().toLowerCase()||t.kind&&e.kind!==t.kind||t.source_kind!==void 0&&e.source_kind?.trim().toLowerCase()!==t.source_kind.trim().toLowerCase())}function sa(e){return Le(e)}function Z(e,t){let r=oe("update",e);if(!r)throw new c(`Unsupported command_option_policies option "${e}" for update command on type "${t}"`,o.CONFLICT);return r}function It(e,t,r){let s=new Set,a=(n,i)=>{i&&s.add(n)};if(a("title",e.title!==void 0),a("description",e.description!==void 0),a("body",e.body!==void 0),a("status",e.status!==void 0),a("closeReason",e.closeReason!==void 0),a("priority",e.priority!==void 0),a("type",e.type!==void 0),a("tags",e.tags!==void 0||Array.isArray(e.addTags)&&e.addTags.length>0||Array.isArray(e.removeTags)&&e.removeTags.length>0),a("deadline",e.deadline!==void 0),a("estimatedMinutes",e.estimatedMinutes!==void 0),a("acceptanceCriteria",e.acceptanceCriteria!==void 0||Array.isArray(e.addAc)&&e.addAc.length>0||Array.isArray(e.removeAc)&&e.removeAc.length>0),a("definitionOfReady",e.definitionOfReady!==void 0),a("order",e.order!==void 0||e.rank!==void 0),a("goal",e.goal!==void 0),a("objective",e.objective!==void 0),a("value",e.value!==void 0),a("impact",e.impact!==void 0),a("outcome",e.outcome!==void 0),a("whyNow",e.whyNow!==void 0),a("author",e.author!==void 0),a("message",e.message!==void 0),a("assignee",e.assignee!==void 0),a("parent",e.parent!==void 0),a("reviewer",e.reviewer!==void 0),a("risk",e.risk!==void 0),a("confidence",e.confidence!==void 0),a("sprint",e.sprint!==void 0),a("release",e.release!==void 0),a("blockedBy",e.blockedBy!==void 0),a("blockedReason",e.blockedReason!==void 0),a("unblockNote",e.unblockNote!==void 0),a("reporter",e.reporter!==void 0),a("severity",e.severity!==void 0),a("environment",e.environment!==void 0),a("reproSteps",e.reproSteps!==void 0),a("resolution",e.resolution!==void 0),a("expectedResult",e.expectedResult!==void 0),a("actualResult",e.actualResult!==void 0),a("affectedVersion",e.affectedVersion!==void 0),a("fixedVersion",e.fixedVersion!==void 0),a("component",e.component!==void 0),a("regression",e.regression!==void 0),a("customerImpact",e.customerImpact!==void 0),a("dep",e.dep!==void 0),a("depRemove",e.depRemove!==void 0),a("dep",e.replaceDeps===!0),a("comment",e.comment!==void 0),a("note",e.note!==void 0),a("learning",e.learning!==void 0),a("file",e.file!==void 0),a("test",e.test!==void 0),a("test",e.replaceTests===!0),a("file",e.replaceFiles===!0),a("doc",e.replaceDocs===!0),a("doc",e.doc!==void 0),a("reminder",e.reminder!==void 0),a("event",e.event!==void 0),a("typeOption",e.typeOption!==void 0),a("field",e.field!==void 0),a("force",e.force===!0),a("ownershipMetadataBypass",e.ownershipMetadataBypass===!0),a("ownershipDependencyBypass",e.ownershipDependencyBypass===!0),a("dep",e.clearDeps===!0),a("comment",e.clearComments===!0),a("note",e.clearNotes===!0),a("learning",e.clearLearnings===!0),a("file",e.clearFiles===!0),a("test",e.clearTests===!0),a("doc",e.clearDocs===!0),a("reminder",e.clearReminders===!0),a("event",e.clearEvents===!0),a("typeOption",e.clearTypeOptions===!0),e.unset&&e.unset.length>0){let n=x(e.unset,t,r);for(let i of n.optionKeys)a(i,!0)}return s}function da(e,t,r,s,a){let n=ue(e,r);if(!n)throw new c(`Invalid type value "${e}"`,o.USAGE);let i=fe(n,"update",[]);if(i.errors.length>0)throw new c(i.errors.join("; "),o.CONFLICT);let l=It(t,s,a);for(let d of i.disabled)if(l.has(Z(d,e)))throw new c(`Option ${_("update",d)} is disabled for type "${e}" by command_option_policies`,o.USAGE);for(let d of i.required)if(!l.has(Z(d,e)))throw new c(`Missing required option ${_("update",d)} for type "${e}"`,o.USAGE)}var ia=new Set(["order","rank"]),la=P.filter(e=>!ia.has(e)),Ut=["tags","closeReason",...la],oa=["title","description","body","status","closeReason","completedAt","priority","type",...P,"dep","depRemove","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ca=[{optionKey:"deadline",metadataKey:"deadline",transform:(e,t)=>N(e,t.nowValue,"deadline")},{optionKey:"estimatedMinutes",metadataKey:"estimated_minutes",transform:e=>Ne(e,"estimated-minutes")},{optionKey:"acceptanceCriteria",metadataKey:"acceptance_criteria",transform:e=>e},{optionKey:"definitionOfReady",metadataKey:"definition_of_ready"},{optionKey:"goal",metadataKey:"goal"},{optionKey:"objective",metadataKey:"objective"},{optionKey:"value",metadataKey:"value"},{optionKey:"impact",metadataKey:"impact"},{optionKey:"outcome",metadataKey:"outcome"},{optionKey:"whyNow",metadataKey:"why_now"}],ua=[{optionKey:"reviewer",metadataKey:"reviewer"},{optionKey:"risk",metadataKey:"risk",transform:e=>R(qe(e),ie,"risk")},{optionKey:"confidence",metadataKey:"confidence",transform:e=>Xe(e)}],fa=[{optionKey:"blockedReason",metadataKey:"blocked_reason"},{optionKey:"unblockNote",metadataKey:"unblock_note"},{optionKey:"reporter",metadataKey:"reporter"},{optionKey:"severity",metadataKey:"severity",transform:e=>R(He(e),le,"severity")},{optionKey:"environment",metadataKey:"environment"},{optionKey:"reproSteps",metadataKey:"repro_steps"},{optionKey:"resolution",metadataKey:"resolution"},{optionKey:"expectedResult",metadataKey:"expected_result"},{optionKey:"actualResult",metadataKey:"actual_result"},{optionKey:"affectedVersion",metadataKey:"affected_version"},{optionKey:"fixedVersion",metadataKey:"fixed_version"},{optionKey:"component",metadataKey:"component"},{optionKey:"regression",metadataKey:"regression",transform:e=>Ze(e)},{optionKey:"customerImpact",metadataKey:"customer_impact"}];function J(e,t,r){for(let s of e){let a=t[s.optionKey],n=r.clearItemMetadataKeys.has(s.metadataKey);if(!(a===void 0&&!n)){if(n){delete r.metadataRecord[s.metadataKey],r.changedFields.push(s.metadataKey);continue}if(typeof a!="string")throw new c(`${_("update",String(s.optionKey))} must be a string value`,o.USAGE);r.metadataRecord[s.metadataKey]=s.transform?s.transform(a,r):a.trim(),r.changedFields.push(s.metadataKey)}}}async function pa(e){let t=Me();return At({...e,body:await t.resolveValue(e.body,"--body"),dep:await t.resolveList(e.dep,"--dep"),depRemove:await t.resolveList(e.depRemove,"--dep-remove"),comment:await t.resolveList(e.comment,"--comment"),note:await t.resolveList(e.note,"--note"),learning:await t.resolveList(e.learning,"--learning"),file:await t.resolveList(e.file,"--file"),test:await t.resolveList(e.test,"--test"),doc:await t.resolveList(e.doc,"--doc"),reminder:await t.resolveList(e.reminder,"--reminder"),event:await t.resolveList(e.event,"--event"),typeOption:await t.resolveList(e.typeOption,"--type-option"),field:await t.resolveList(e.field,"--field")})}function ya(e){return[{enabled:e.clearDeps||e.replaceDeps,optionKey:"dep",clearFlag:"--clear-deps",valueFlag:"--dep",values:e.dep,metadataKey:"dependencies"},{enabled:e.clearComments,optionKey:"comment",clearFlag:"--clear-comments",valueFlag:"--comment",values:e.comment,metadataKey:"comments"},{enabled:e.clearNotes,optionKey:"note",clearFlag:"--clear-notes",valueFlag:"--note",values:e.note,metadataKey:"notes"},{enabled:e.clearLearnings,optionKey:"learning",clearFlag:"--clear-learnings",valueFlag:"--learning",values:e.learning,metadataKey:"learnings"},{enabled:e.clearFiles||e.replaceFiles,optionKey:"file",clearFlag:"--clear-files",valueFlag:"--file",values:e.file,metadataKey:"files"},{enabled:e.clearTests||e.replaceTests,optionKey:"test",clearFlag:"--clear-tests",valueFlag:"--test",values:e.test,metadataKey:"tests"},{enabled:e.clearDocs||e.replaceDocs,optionKey:"doc",clearFlag:"--clear-docs",valueFlag:"--doc",values:e.doc,metadataKey:"docs"},{enabled:e.clearReminders,optionKey:"reminder",clearFlag:"--clear-reminders",valueFlag:"--reminder",values:e.reminder,metadataKey:"reminders"},{enabled:e.clearEvents,optionKey:"event",clearFlag:"--clear-events",valueFlag:"--event",values:e.event,metadataKey:"events"},{enabled:e.clearTypeOptions,optionKey:"typeOption",clearFlag:"--clear-type-options",valueFlag:"--type-option",values:e.typeOption,metadataKey:"type_options"}]}function q(e){if(e.enabled&&(!e.values||e.values.length===0))throw new c(`${e.replaceFlag} requires at least one ${e.valueFlag} entry`,o.USAGE);if(e.enabled&&e.clearEnabled)throw new c(`${e.replaceFlag} cannot be combined with ${e.clearFlag}`,o.USAGE)}function ma(e){if(e.replaceDeps===!0&&(e.dep===void 0||e.dep.length===0))throw new c("--replace-deps requires at least one --dep entry",o.USAGE);if(e.replaceDeps===!0&&e.depRemove!==void 0&&e.depRemove.length>0)throw new c("--replace-deps cannot be combined with --dep-remove",o.USAGE);q({enabled:e.replaceTests===!0,values:e.test,replaceFlag:"--replace-tests",clearEnabled:e.clearTests===!0,clearFlag:"--clear-tests",valueFlag:"--test"}),q({enabled:e.replaceFiles===!0,values:e.file,replaceFlag:"--replace-files",clearEnabled:e.clearFiles===!0,clearFlag:"--clear-files",valueFlag:"--file"}),q({enabled:e.replaceDocs===!0,values:e.doc,replaceFlag:"--replace-docs",clearEnabled:e.clearDocs===!0,clearFlag:"--clear-docs",valueFlag:"--doc"})}function ga(e){for(let t of e.definitions){if(!t.enabled)continue;let r=t.optionKey==="dep"&&e.options.replaceDeps===!0||t.optionKey==="test"&&e.options.replaceTests===!0||t.optionKey==="file"&&e.options.replaceFiles===!0||t.optionKey==="doc"&&e.options.replaceDocs===!0;if(t.values&&t.values.length>0&&!r)throw new c(`Cannot combine ${t.clearFlag} with ${t.valueFlag}`,o.USAGE);e.clearOptionKeys.add(t.optionKey),e.clearItemMetadataKeys.add(t.metadataKey)}}function ha(e){let t={};for(let r of Ut)t[String(r)]=e[r]!==void 0;return t.order=e.order!==void 0||e.rank!==void 0,t}function wa(e,t){let r=ha(e);for(let[s,a]of Object.entries(r)){if(!a||!t.optionKeys.has(s))continue;let n=O.get(s)??s;throw new c(`Cannot combine --unset ${n} with ${_("update",s)}`,o.USAGE)}if(t.metadataKeys.has("acceptance_criteria")){if(Array.isArray(e.addAc)&&e.addAc.length>0)throw new c("Cannot combine --unset acceptance-criteria with --add-ac",o.USAGE);if(Array.isArray(e.removeAc)&&e.removeAc.length>0)throw new c("Cannot combine --unset acceptance-criteria with --remove-ac",o.USAGE)}if(t.metadataKeys.has("tags")){if(Array.isArray(e.addTags)&&e.addTags.length>0)throw new c("Cannot combine --unset tags with --add-tags",o.USAGE);if(Array.isArray(e.removeTags)&&e.removeTags.length>0)throw new c("Cannot combine --unset tags with --remove-tags",o.USAGE)}}function _a(e){let t=(r,s)=>{let a=O.get(s),n=a?`Use --unset ${a} to clear this field.`:void 0;xe(r,_("update",s),n)};for(let r of Ut)t(e[r],String(r));t(e.order??e.rank,"order"),K(e.reminder,"--reminder","Use --clear-reminders to clear reminders."),K(e.event,"--event","Use --clear-events to clear linked events.")}function va(e,t){let r={};for(let s of oa)r[String(s)]=e[s]!==void 0;return r.tags=e.tags!==void 0,r.addTags=Array.isArray(e.addTags)&&e.addTags.length>0,r.removeTags=Array.isArray(e.removeTags)&&e.removeTags.length>0,r.addAc=Array.isArray(e.addAc)&&e.addAc.length>0,r.removeAc=Array.isArray(e.removeAc)&&e.removeAc.length>0,r.order=e.order!==void 0,r.rank=e.rank!==void 0,r.replaceDeps=e.replaceDeps===!0,r.replaceTests=e.replaceTests===!0,r.replaceFiles=e.replaceFiles===!0,r.replaceDocs=e.replaceDocs===!0,r.unset=e.unset!==void 0&&e.unset.length>0,r.clearDeps=e.clearDeps===!0,r.clearComments=e.clearComments===!0,r.clearNotes=e.clearNotes===!0,r.clearLearnings=e.clearLearnings===!0,r.clearFiles=e.clearFiles===!0,r.clearTests=e.clearTests===!0,r.clearDocs=e.clearDocs===!0,r.clearReminders=e.clearReminders===!0,r.clearEvents=e.clearEvents===!0,r.clearTypeOptions=e.clearTypeOptions===!0,r.runtimeFields=Object.keys(t).length>0,r}async function Aa(e){let t=await b(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await j(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:r}=await V(t,{schema:e.settings.schema});return{item:r.metadata,changed_fields:[],warnings:["noop_no_update_fields"]}}async function ba(e){if(!await de(ye(e)))throw new c(`Tracker is not initialized at ${e}. Run pm init first.`,o.NOT_FOUND)}function Ka(e){if(e.order!==void 0&&e.rank!==void 0&&e.order!==e.rank)throw new c("--order and --rank must match when both are provided",o.USAGE)}async function Ra(e){if(e.options.parent===void 0||e.unsetTargets.metadataKeys.has("parent"))return{resolvedParentValue:void 0,warnings:[]};let t=Se(e.options.parent);if(Te(e.id,t,e.settings.id_prefix),await b(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder))return{resolvedParentValue:t,warnings:[]};let s=D(t,e.settings.id_prefix);return{resolvedParentValue:t,warnings:Ee(s,e.parentReferencePolicy).warnings}}function Sa(e){return e.unresolved===void 0?[]:[`blocked_by_unresolved:${e.unresolved}`]}async function Ea(e){if(e.workflowEnforcement==="off"||e.typeWorkflows.length===0||!e.fieldFlags.status||e.options.status===void 0)return[];let t=await b(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeRegistry.type_to_folder);if(!t)throw await j(e.pmRoot,e.id,e.settings.id_prefix,e.typeRegistry.type_to_folder);let{document:r}=await V(t,{schema:e.settings.schema}),s=e.options.type!==void 0?I(e.options.type,e.typeRegistry)??e.options.type:r.metadata?.type??"",a=Kt({enforcement:e.workflowEnforcement,typeWorkflows:e.typeWorkflows,statusRegistry:e.statusRegistry,typeName:s,fromStatus:r.metadata?.status??"",toStatus:e.options.status});return a?[a]:[]}async function Ta(e){if(!e.fieldFlags.status||g(e.options.status,e.statusRegistry)!==e.statusRegistry.close_status)return;let r=Object.entries(e.fieldFlags).filter(([l,d])=>d&&l!=="status"&&l!=="closeReason"&&l!=="completedAt").map(([l])=>l),s=[],a=[];if(r.length>0){let l=await Ha(e.id,{...e.options,status:void 0,closeReason:void 0,message:void 0},e.global);a=l.changed_fields,s.push(...l.warnings)}let n=await Ye(e.id,e.options.closeReason,{author:e.options.author,message:e.options.message,force:e.options.force,completedAt:e.options.completedAt},e.global),i=[...e.workflowTransitionWarnings,...s,...n.warnings,"auto_routed_from_update_to_close"];return{item:n.item,changed_fields:[...a,...n.changed_fields],warnings:i}}function ka(e,t,r,s){return t.title!==void 0&&(e.metadata.title=yt(t.title,"--title"),s.push("title")),t.description!==void 0&&(e.metadata.description=t.description,s.push("description")),t.body!==void 0&&(e.body=t.body,s.push("body")),g(e.metadata.status,r)??e.metadata.status}function Ia(e,t,r,s,a){let n=Ht(r,t.statusRegistry);if(e.metadata.status=n,a.push("status"),n===t.statusRegistry.close_status&&(e.metadata.closed_at===void 0||e.metadata.closed_at===null)){e.metadata.closed_at=t.nowIso,e.metadata.completed_at=t.nowIso,a.push("closed_at","completed_at");return}n!==t.statusRegistry.close_status&&s===t.statusRegistry.close_status&&e.metadata.closed_at!==void 0&&(delete e.metadata.closed_at,a.push("closed_at"),e.metadata.completed_at!==void 0&&(delete e.metadata.completed_at,a.push("completed_at")))}function Ua(e,t,r,s){if(t.options.status!==void 0&&Ia(e,t,t.options.status,r,s),t.options.completedAt!==void 0){if(!Ke(e.metadata.status,t.statusRegistry))throw new c("--completed-at can only be set on a terminal item",o.USAGE);e.metadata.completed_at=N(t.options.completedAt,new Date(t.nowIso),"completed-at"),s.push("completed_at")}}function Da(e,t,r,s){if(t.options.closeReason!==void 0||t.clearItemMetadataKeys.has("close_reason")){if(t.clearItemMetadataKeys.has("close_reason"))delete e.metadata.close_reason;else{let a=t.options.closeReason?.trim()??"";if(a.length===0)throw new c("--close-reason must not be empty",o.USAGE);e.metadata.close_reason=a}s.push("close_reason");return}t.options.status!==void 0&&r===t.statusRegistry.close_status&&e.metadata.status!==t.statusRegistry.canceled_status&&e.metadata.close_reason!==void 0&&(delete e.metadata.close_reason,s.push("close_reason"))}function Dt(e,t,r,s){Ua(e,t,r,s),Da(e,t,r,s)}function Fa(e,t,r){let s=I(e.metadata.type,t.typeRegistry)??e.metadata.type;if(t.options.priority!==void 0&&(e.metadata.priority=sa(t.options.priority),r.push("priority")),t.options.type!==void 0){let a=I(t.options.type,t.typeRegistry);if(!a)throw new c($e(t.options.type,t.typeRegistry.types,_e(t.pmRoot,t.settings.schema)),o.USAGE);e.metadata.type=a,s=a,r.push("type")}return da(s,t.options,t.typeRegistry,t.runtimeFieldRegistry,t.extensionFieldNames),Oa(e,t,s,r),s}function Oa(e,t,r,s){if(t.options.typeOption!==void 0||t.clearItemMetadataKeys.has("type_options")){if(t.clearItemMetadataKeys.has("type_options"))delete e.metadata.type_options;else{let n=nt(t.options.typeOption??[]),i=$(r,n,t.typeRegistry);if(i.errors.length>0)throw new c(i.errors.join("; "),o.USAGE);e.metadata.type_options=i.normalized}s.push("type_options");return}if(t.options.type===void 0||e.metadata.type_options===void 0)return;let a=$(r,e.metadata.type_options,t.typeRegistry);if(a.errors.length>0)throw new c(`Current type options are incompatible with type "${r}". ${a.errors.join("; ")}. Use --clear-type-options to clear them.`,o.USAGE);e.metadata.type_options=a.normalized}function Ma(e,t,r){if(t.options.dep===void 0&&t.options.depRemove===void 0&&!t.clearItemMetadataKeys.has("dependencies"))return;let s=t.clearItemMetadataKeys.has("dependencies")?[]:[...e.metadata.dependencies??[]];if(t.dependencyUpdates.additions.length>0){let a=new Set(s.map(n=>gt(n)));for(let n of t.dependencyUpdates.additions){let i=gt(n);a.has(i)||(s.push(n),a.add(i))}}t.dependencyRemovals.length>0&&(s=s.filter(a=>!t.dependencyRemovals.some(n=>kt(a,n)))),s.length===0?delete e.metadata.dependencies:e.metadata.dependencies=s,r.push("dependencies")}function Ca(e,t,r){H(e,"comments",t.options.comment,t.commentUpdates.values,t.clearItemMetadataKeys,r),H(e,"notes",t.options.note,t.noteUpdates.values,t.clearItemMetadataKeys,r),H(e,"learnings",t.options.learning,t.learningUpdates.values,t.clearItemMetadataKeys,r)}function H(e,t,r,s,a,n){r===void 0&&!a.has(t)||(a.has(t)||!s||s.length===0?delete e.metadata[t]:e.metadata[t]=[...e.metadata[t]??[],...s],n.push(t))}function Na(e,t,r){ht(e,"files",t.options.file,t.fileUpdates.values,aa,t.options.replaceFiles===!0,t.clearItemMetadataKeys,r),La(e,t,r),ht(e,"docs",t.options.doc,t.docUpdates.values,na,t.options.replaceDocs===!0,t.clearItemMetadataKeys,r)}function ht(e,t,r,s,a,n,i,l){if(!(r===void 0&&!i.has(t))){if(n)e.metadata[t]=s;else if(i.has(t)||!s||s.length===0)delete e.metadata[t];else{let d=[...e.metadata[t]??[]],u=new Set(d.map(p=>a(p)));for(let p of s){let f=a(p);u.has(f)||(d.push(p),u.add(f))}e.metadata[t]=d}l.push(t)}}function La(e,t,r){t.options.test===void 0&&!t.clearItemMetadataKeys.has("tests")||(t.clearItemMetadataKeys.has("tests")&&t.options.replaceTests===!0?e.metadata.tests=wt(t.testUpdates.values)??[]:t.clearItemMetadataKeys.has("tests")||!t.testUpdates.values||t.testUpdates.values.length===0?delete e.metadata.tests:e.metadata.tests=wt([...e.metadata.tests??[],...t.testUpdates.values]),e.metadata.tests!==void 0&&e.metadata.tests.length===0&&delete e.metadata.tests,r.push("tests"))}function wt(e){if(!e||e.length===0)return;let t=[],r=new Set;for(let s of e){let a=ra(s);r.has(a)||(t.push(s),r.add(a))}return t}function Pa(e,t,r){let s=t.options.addTags,a=t.options.removeTags,n=Array.isArray(s)&&s.length>0||Array.isArray(a)&&a.length>0;if(t.options.tags!==void 0||t.clearItemMetadataKeys.has("tags")||n){let i=t.clearItemMetadataKeys.has("tags")?[]:t.options.tags!==void 0?ke(t.options.tags):Array.isArray(e.metadata.tags)?[...e.metadata.tags]:[];e.metadata.tags=Fe(De(i,s),a),r.changedFields.push("tags")}J(ca,t.options,r),Ga(e,t,r.changedFields)}function $a(e,t,r,s){let a=t.options.addAc,n=t.options.removeAc;if(!(Array.isArray(a)&&a.length>0)&&!(Array.isArray(n)&&n.length>0))return;let i=Ue(Ie(e.metadata.acceptance_criteria),a,n);for(let d of i.unmatchedRemovals)s.push(`remove_ac_unmatched:${d}`);let l=i.criteria.join("; ");e.metadata.acceptance_criteria!==l&&(l===""&&e.metadata.acceptance_criteria===void 0||(e.metadata.acceptance_criteria=l,r.changedFields.includes("acceptance_criteria")||r.changedFields.push("acceptance_criteria")))}function Ga(e,t,r){let s=t.options.order??t.options.rank;if(!(s===void 0&&!t.clearItemMetadataKeys.has("order"))){if(t.clearItemMetadataKeys.has("order"))delete e.metadata.order;else{let a=Ce(s??"","order");if(!Number.isInteger(a))throw new c("Order must be an integer",o.USAGE);e.metadata.order=a}r.push("order")}}function Ba(e,t,r,s){Va(e,t,r.changedFields),ja(e,t,r.changedFields),J(ua,t.options,r),_t(e,t,"sprint",s,r.changedFields),_t(e,t,"release",s,r.changedFields),za(e,t,r.changedFields),J(fa,t.options,r)}function Va(e,t,r){if(!(t.options.assignee===void 0&&!t.clearItemMetadataKeys.has("assignee"))){if(t.clearItemMetadataKeys.has("assignee"))delete e.metadata.assignee;else{let s=t.options.assignee?.trim()??"";if(s==="")throw new c("--assignee must not be empty. Use --unset assignee to clear it.",o.USAGE);e.metadata.assignee=s}r.push("assignee")}}function ja(e,t,r){t.options.parent===void 0&&!t.clearItemMetadataKeys.has("parent")||(t.clearItemMetadataKeys.has("parent")?delete e.metadata.parent:e.metadata.parent=t.resolvedParentValue??"",r.push("parent"))}function _t(e,t,r,s,a){if(!(t.options[r]===void 0&&!t.clearItemMetadataKeys.has(r))){if(t.clearItemMetadataKeys.has(r))delete e.metadata[r];else{let n=Pe(r,t.options[r]??"",t.settings.validation.sprint_release_format);e.metadata[r]=n.value,s.push(...n.warnings)}a.push(r)}}function za(e,t,r){t.options.blockedBy===void 0&&!t.clearItemMetadataKeys.has("blocked_by")||(t.clearItemMetadataKeys.has("blocked_by")?delete e.metadata.blocked_by:e.metadata.blocked_by=t.options.blockedBy?.trim()??"",r.push("blocked_by"),(t.clearItemMetadataKeys.has("blocked_by")||t.resolvedBlockedByDependencyId!==void 0)&&ta(e.metadata,t.resolvedBlockedByDependencyId,t.nowIso,t.author,r))}function Wa(e,t,r){(t.options.reminder!==void 0||t.clearItemMetadataKeys.has("reminders"))&&(t.clearItemMetadataKeys.has("reminders")?delete e.metadata.reminders:e.metadata.reminders=tt(t.options.reminder??[],t.nowValue,{valueMode:"trimmed"}),r.push("reminders")),(t.options.event!==void 0||t.clearItemMetadataKeys.has("events"))&&(t.clearItemMetadataKeys.has("events")?delete e.metadata.events:e.metadata.events=at(t.options.event??[],t.nowValue,{allDayEmptyGuard:"truthy",recurrenceEmptyNumericGuard:"truthy"}),r.push("events"))}function Ya(e,t,r){vt(e,t.runtimeFieldRegistry.definitions.map(a=>a.metadata_key),t.clearItemMetadataKeys,r),vt(e,t.extensionFieldNames,t.clearItemMetadataKeys,r);for(let[a,n]of Object.entries(t.runtimeFieldUpdates)){if(t.clearItemMetadataKeys.has(a)){let i=a.replaceAll("_","-"),d=t.runtimeFieldRegistry.definitions.find(u=>u.metadata_key===a)?.cli_flag??i;throw new c(`Cannot combine --unset ${i} with --${d}`,o.USAGE)}U(e[a],n)||(e[a]=n,r.push(a))}let s=he(t.options.field,t.extensionRegistrations);for(let a of Object.keys(s))if(t.clearItemMetadataKeys.has(a))throw new c(`Cannot combine --unset ${a.replaceAll("_","-")} with --field ${a}=...`,o.USAGE);for(let[a,n]of Object.entries(s))U(e[a],n)||(e[a]=n,r.push(a))}function vt(e,t,r,s){for(let a of t)!r.has(a)||e[a]===void 0||(delete e[a],s.push(a))}function qa(e,t){let r=structuredClone(e.metadata),s=e.body,a=[],n=[],i=ka(e,t.options,t.statusRegistry,a),l=e.metadata,d={metadataRecord:l,clearItemMetadataKeys:t.clearItemMetadataKeys,changedFields:a,nowValue:t.nowValue};Dt(e,t,i,a),Fa(e,t,a),Ma(e,t,a),Ca(e,t,a),Na(e,t,a),Pa(e,t,d),$a(e,t,d,n),Ba(e,t,d,n),(t.options.dep!==void 0||t.options.depRemove!==void 0||t.options.blockedBy!==void 0||t.clearItemMetadataKeys.has("dependencies")||t.clearItemMetadataKeys.has("blocked_by"))&&st(e.metadata.id,e.metadata.dependencies),g(e.metadata.status,t.statusRegistry)===t.statusRegistry.canceled_status&&e.metadata.assignee!==void 0&&(delete e.metadata.assignee,a.includes("assignee")||a.push("assignee")),Wa(e,t,a),Ya(l,t,a);try{we(l,t.extensionRegistrations,{skipDefaultFields:t.clearItemMetadataKeys})}catch(f){throw new c(f instanceof Error?f.message:"Invalid extension item field values",o.USAGE)}let u=e.metadata;return{changedFields:[...new Set(a)].filter(f=>f==="body"?e.body!==s:!U(r[f],u[f])),warnings:n}}async function Ha(e,t,r){t=await pa(t);let s=pe(process.cwd(),r.path);await ba(s);let a=await je(s),n=ve(a.schema),i=Ae(a.schema),l=me(),d=ge(l),u=ce(a,l),p=a.governance.workflow_enforcement??"off",f=p==="off"?[]:Ge(a.schema),S=[{strict_error:"strict_error",warn:"warn",off:"off"},{strict_error:"warn",warn:"warn",off:"off"}][+(t.allowMissingParent===!0)][a.validation.parent_reference],E=x(t.unset,i,d),Ft=new Set(E.optionKeys),T=new Set(E.metadataKeys);ma(t),ga({definitions:ya(t),options:t,clearOptionKeys:Ft,clearItemMetadataKeys:T}),bt(e,t,T),wa(t,E),_a(t);let m=Re(t.author,a.author_default),ee=new Date,v=ee.toISOString(),Ot=St(t.dep,a.id_prefix,v,m),Mt=Et(t.depRemove,a.id_prefix),k=F("--comment",t.comment,v,m),Ct=t.ownershipMetadataBypass===!0&&k.values?{...k,values:k.values.map(y=>({...y,author:m}))}:k,Nt=F("--note",t.note,v,m),Lt=F("--learning",t.learning,v,m),Pt=ut(t.file),$t=ft(t.test),Gt=pt(t.doc),C=[],te=await Ra({id:e,options:t,unsetTargets:E,pmRoot:s,settings:a,typeRegistry:u,parentReferencePolicy:S}),ae=await ea(t.blockedBy,T.has("blocked_by"),s,a.id_prefix,a.item_format,u.type_to_folder),Bt=ae.id,Vt=[...te.warnings,...Sa(ae)],ne=be(t,i,t.runtimeFieldCommands),h=va(t,ne);if(!Object.values(h).some(Boolean))return Aa({pmRoot:s,id:e,settings:a,typeRegistry:u});C.push(...await Ea({options:t,fieldFlags:h,workflowEnforcement:p,typeWorkflows:f,statusRegistry:n,typeRegistry:u,pmRoot:s,id:e,settings:a}));let re=await Ta({options:t,fieldFlags:h,statusRegistry:n,workflowTransitionWarnings:C,global:r,id:e});if(re)return re;Ka(t);let A=h.dep||h.depRemove||h.blockedBy?await ze(s,a.item_format,u.type_to_folder,void 0,a.schema):void 0,w=await We({pmRoot:s,settings:a,typeToFolder:u.type_to_folder,id:e,op:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0?"update_ownership_bypass":"update",author:m,message:t.message,force:t.force,bypassAssigneeConflict:t.ownershipMetadataBypass===!0||t.ownershipDependencyBypass===!0,extensionFieldNames:d,skipNoop:!0,mutate(y){return A=A?.map(se=>se.id===y.metadata.id?structuredClone(y.metadata):se),qa(y,{options:t,settings:a,typeRegistry:u,statusRegistry:n,runtimeFieldRegistry:i,extensionRegistrations:l,extensionFieldNames:d,clearItemMetadataKeys:T,dependencyUpdates:Ot,dependencyRemovals:Mt,commentUpdates:Ct,noteUpdates:Nt,learningUpdates:Lt,fileUpdates:Pt,testUpdates:$t,docUpdates:Gt,resolvedParentValue:te.resolvedParentValue,resolvedBlockedByDependencyId:Bt,runtimeFieldUpdates:ne,nowValue:ee,nowIso:v,author:m,pmRoot:s})}}),jt=A?dt(A,A.map(y=>y.id===w.item.id?w.item:y),w.item.id):[];return{item:w.item,changed_fields:w.changedFields,warnings:[...C,...Vt,...jt,...w.warnings]}}var cn={applyStatusAndCloseReasonMutations:Dt,collectProvidedUpdatePolicyOptions:It,buildOwnershipBypassRestrictedOptionsError:X,enforceOwnershipBypassScope:bt,enforceTypeWorkflowTransition:Kt,matchesDependencySelector:kt,normalizeLegacyNoneUpdateOptions:At,normalizeUpdatePolicyOptionKey:Z,parseDependencyAdditions:St,parseDependencyRemovals:Et,parseUpdateUnsetTargets:x,reconcileBlockedByDependency:Tt,resolveRuntimeUnsetDefinition:(e,t)=>Y(e,"update",t)};export{Ha as a,cn as b};
|
|
3
|
-
//# sourceMappingURL=chunk-
|
|
3
|
+
//# sourceMappingURL=chunk-VN5VITU3.js.map
|