@unbrained/pm-cli 2026.11.30 → 2026.12.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/commander-usage.js +10 -10
  3. package/dist/cli/error-guidance.js +5 -5
  4. package/dist/cli/extension-command-help.js +6 -6
  5. package/dist/cli/help-json-payload.js +7 -7
  6. package/dist/cli/main.js +5 -5
  7. package/dist/cli/register-list-query.js +10 -10
  8. package/dist/cli/register-mutation.js +3 -3
  9. package/dist/cli/runtime/invocation-command-path.js +2 -0
  10. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  11. package/dist/cli-bundle/bundle-manifest.json +1 -1
  12. package/dist/cli-bundle/chunks/{chunk-DCWGM7CY.js → chunk-3HKPVOAN.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-Z7YL2SUM.js → chunk-3KEMIPKG.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-IGEFPHV7.js → chunk-4YQMQOUO.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-TX74QJ4W.js → chunk-4YYFY33T.js} +2 -2
  16. package/dist/cli-bundle/chunks/chunk-A5ZEMOVR.js +2 -0
  17. package/dist/cli-bundle/chunks/{chunk-5PNOVDVO.js → chunk-AHV3CSQG.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-AJLU6KLW.js +2 -0
  19. package/dist/cli-bundle/chunks/{chunk-KCVSSONY.js → chunk-C6WM6ZN4.js} +3 -3
  20. package/dist/cli-bundle/chunks/chunk-CBUC4X7Q.js +127 -0
  21. package/dist/cli-bundle/chunks/{chunk-47ZS6RPL.js → chunk-CWPR234D.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-I4SPJQQI.js +3 -0
  23. package/dist/cli-bundle/chunks/{chunk-Q4VZSMUL.js → chunk-L2ZSSMYY.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-NHBG5ET3.js → chunk-MZZ4ZJ5Z.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-CCKM5YQM.js → chunk-NA6D75V5.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-NRQCBUYD.js +113 -0
  27. package/dist/cli-bundle/chunks/{chunk-YVTALIN3.js → chunk-OBPO6V7H.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-NZSXWIX7.js → chunk-OKEJ4U2I.js} +7 -7
  29. package/dist/cli-bundle/chunks/{chunk-KXTKLDKD.js → chunk-OXC5KBIQ.js} +2 -2
  30. package/dist/cli-bundle/chunks/{chunk-HXQ3OHQR.js → chunk-PCDTWL6V.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-FECZV72T.js → chunk-Q6GLSAJY.js} +2 -2
  32. package/dist/cli-bundle/chunks/{chunk-AOTI76Q6.js → chunk-Q6K7HWZ7.js} +2 -2
  33. package/dist/cli-bundle/chunks/chunk-QDV7S2QS.js +2 -0
  34. package/dist/cli-bundle/chunks/{chunk-2SBTXR6C.js → chunk-SY5C3U32.js} +3 -3
  35. package/dist/cli-bundle/chunks/{chunk-WFYE34TO.js → chunk-U7RBJGLF.js} +23 -23
  36. package/dist/cli-bundle/chunks/chunk-WSEIEDEK.js +2 -0
  37. package/dist/cli-bundle/chunks/{chunk-FR7ULTM4.js → chunk-XME6GIFQ.js} +2 -2
  38. package/dist/cli-bundle/chunks/{chunk-TY55UX6M.js → chunk-YSVOXCYH.js} +2 -2
  39. package/dist/cli-bundle/chunks/{chunk-ZA5NS3PL.js → chunk-ZL6J6JYT.js} +6 -6
  40. package/dist/cli-bundle/chunks/{field-option-collisions-2F2Z7R7B.js → field-option-collisions-BBGTV7AD.js} +2 -2
  41. package/dist/cli-bundle/chunks/item-revision-3LENTXYF.js +2 -0
  42. package/dist/cli-bundle/chunks/item-transaction-66RDV7PH.js +2 -0
  43. package/dist/cli-bundle/chunks/{linked-resource-value-list-WXPPYUVQ.js → linked-resource-value-list-E2DX52LY.js} +2 -2
  44. package/dist/cli-bundle/chunks/{mutation-actor-UK3QNEEB.js → mutation-actor-NHN33ITJ.js} +2 -2
  45. package/dist/cli-bundle/chunks/{mutation-admission-UTDYPFWP.js → mutation-admission-PGKJTCG6.js} +2 -2
  46. package/dist/cli-bundle/chunks/{register-list-query-DRA3CWHI.js → register-list-query-7S5QWDTI.js} +11 -11
  47. package/dist/cli-bundle/chunks/{register-mutation-WO74VLEQ.js → register-mutation-2F6JUBST.js} +5 -5
  48. package/dist/cli-bundle/chunks/{register-operations-CRBKH7WN.js → register-operations-ET3UKPYK.js} +2 -2
  49. package/dist/cli-bundle/chunks/{register-setup-6V6NQB5C.js → register-setup-I63QTFCU.js} +2 -2
  50. package/dist/cli-bundle/chunks/{stage-DYEHGASU.js → stage-4ZCF74G4.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-RQYVX2T6.js → chunk-2DGKVXFT.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-2UWKU2BQ.js +3 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-UQJ4PY2Y.js → chunk-4SCFAWAW.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-7G7JIXLL.js → chunk-6BKT6XQN.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-6IY5CVGJ.js +2 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-7A6SEZEY.js +4 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-IJ3T3W4U.js → chunk-BHNBPCHP.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-LWBZ7UGG.js → chunk-EQCQTYKO.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-FM5WQ6ZU.js → chunk-HTDYNY4L.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-L357ZAES.js → chunk-JPZGC3W4.js} +5 -5
  61. package/dist/cli-bundle/focused-chunks/{chunk-62AMZMR4.js → chunk-KNBGHCIP.js} +3 -3
  62. package/dist/cli-bundle/focused-chunks/chunk-N64AC5G6.js +100 -0
  63. package/dist/cli-bundle/focused-chunks/{chunk-IIVDBAJM.js → chunk-OG57ESZK.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{chunk-MZNV26XE.js → chunk-P2H3GTJK.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{chunk-TQQO42C2.js → chunk-PT7RT3T6.js} +26 -26
  66. package/dist/cli-bundle/focused-chunks/chunk-QZRYGYTI.js +2 -0
  67. package/dist/cli-bundle/focused-chunks/{chunk-A3DORTXS.js → chunk-SQ72CVUH.js} +2 -2
  68. package/dist/cli-bundle/focused-chunks/chunk-SQMOF65W.js +2 -0
  69. package/dist/cli-bundle/focused-chunks/chunk-T3ILWAEV.js +2 -0
  70. package/dist/cli-bundle/focused-chunks/{chunk-SXC3NVZI.js → chunk-TR22GU7M.js} +2 -2
  71. package/dist/cli-bundle/focused-chunks/{chunk-M57KDG7I.js → chunk-TXTPAFHJ.js} +2 -2
  72. package/dist/cli-bundle/focused-chunks/chunk-VK3IE3TS.js +29 -0
  73. package/dist/cli-bundle/focused-chunks/{chunk-NJTKGBSK.js → chunk-VQIC3UZB.js} +2 -2
  74. package/dist/cli-bundle/focused-chunks/{chunk-U35K7FSE.js → chunk-W4JMV7GF.js} +2 -2
  75. package/dist/cli-bundle/focused-chunks/{field-option-collisions-7TG7STO7.js → field-option-collisions-2C6DLUC4.js} +2 -2
  76. package/dist/cli-bundle/focused-chunks/item-revision-723XCQPS.js +2 -0
  77. package/dist/cli-bundle/focused-chunks/{item-transaction-2IC2MLML.js → item-transaction-2K4SFLJ7.js} +2 -2
  78. package/dist/cli-bundle/focused-chunks/{mutation-actor-LJVF2HVD.js → mutation-actor-DJMZUIZI.js} +2 -2
  79. package/dist/cli-bundle/focused-chunks/mutation-admission-SDWQVVHN.js +2 -0
  80. package/dist/cli-bundle/focused-chunks/{stage-MWR73LTZ.js → stage-QBZIK3T5.js} +2 -2
  81. package/dist/cli-bundle/main.js +27 -27
  82. package/dist/cli-bundle/sdk-authoring.js +1 -1
  83. package/dist/cli-bundle/sdk-contracts.js +1 -1
  84. package/dist/cli-bundle/sdk-core.js +1 -1
  85. package/dist/cli-bundle/sdk-governance.js +1 -1
  86. package/dist/cli-bundle/sdk-graph.js +1 -1
  87. package/dist/cli-bundle/sdk-merge.js +61 -61
  88. package/dist/cli-bundle/sdk-query.js +1 -1
  89. package/dist/cli-bundle/sdk-runtime.js +1 -1
  90. package/dist/cli-bundle/sdk-testing.js +1 -1
  91. package/dist/cli-bundle/sdk.js +2 -2
  92. package/dist/core/extensions/reserved-host-flags.js +1 -1
  93. package/dist/core/shared/secret-rules.d.ts +86 -12
  94. package/dist/core/shared/secret-rules.js +7 -5
  95. package/dist/sdk/cli-bootstrap.js +1 -1
  96. package/dist/sdk/cli-contracts/flag-contracts.d.ts +50 -0
  97. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  98. package/dist/sdk/cli-contracts/runtime-contracts.d.ts +3 -1
  99. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  100. package/dist/sdk/extension/command-options.js +1 -1
  101. package/dist/sdk/lifecycle/expect-hash-admission.d.ts +15 -0
  102. package/dist/sdk/lifecycle/expect-hash-admission.js +2 -0
  103. package/dist/sdk/lifecycle/item-revision.d.ts +4 -1
  104. package/dist/sdk/lifecycle/item-revision.js +1 -1
  105. package/dist/sdk/mutation-guard.js +1 -1
  106. package/dist/sdk/output-contracts.js +1 -1
  107. package/dist/sdk/output-projection.d.ts +1 -1
  108. package/dist/sdk/output-projection.js +1 -1
  109. package/dist/sdk/public-surface.json +1 -1
  110. package/dist/sdk/query/aggregate.js +1 -1
  111. package/dist/sdk/query/context.js +1 -1
  112. package/dist/sdk/query/list.js +1 -1
  113. package/dist/sdk/query/next.js +1 -1
  114. package/dist/sdk/query/search-contracts.js +1 -1
  115. package/dist/sdk/read-output/surfaces.js +1 -1
  116. package/dist/sdk/read-output-budget.d.ts +1 -1
  117. package/dist/sdk/read-output-budget.js +1 -1
  118. package/dist/sdk/read-output-contracts.js +1 -1
  119. package/dist/sdk/read-output-rows.js +1 -1
  120. package/docs/COMMANDS.md +37 -0
  121. package/docs/MUTATION_INTEGRITY.md +226 -10
  122. package/docs/SDK.md +16 -6
  123. package/docs/agent-task-token-baseline.json +1 -1
  124. package/marketplace.json +1 -1
  125. package/package.json +1 -1
  126. package/packages/pm-beads/package.json +1 -1
  127. package/packages/pm-calendar/package.json +1 -1
  128. package/packages/pm-command-kit/package.json +1 -1
  129. package/packages/pm-digital-twin/package.json +1 -1
  130. package/packages/pm-governance-audit/package.json +1 -1
  131. package/packages/pm-guide-shell/package.json +1 -1
  132. package/packages/pm-kanban/package.json +1 -1
  133. package/packages/pm-lifecycle-hooks/package.json +1 -1
  134. package/packages/pm-linked-test-adapters/package.json +1 -1
  135. package/packages/pm-search-advanced/package.json +1 -1
  136. package/packages/pm-templates/package.json +1 -1
  137. package/packages/pm-todos/package.json +1 -1
  138. package/packages/pm-vcs/package.json +1 -1
  139. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  140. package/plugins/pm-claude/package.json +1 -1
  141. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  142. package/plugins/pm-codex/package.json +1 -1
  143. package/plugins/pm-codex/plugin.json +1 -1
  144. package/runtime-dependencies.json +1 -1
  145. package/dist/cli-bundle/chunks/chunk-3TXEWHQX.js +0 -125
  146. package/dist/cli-bundle/chunks/chunk-JPJNJHQW.js +0 -2
  147. package/dist/cli-bundle/chunks/chunk-NVYDPNQP.js +0 -2
  148. package/dist/cli-bundle/chunks/chunk-SJWIPGZW.js +0 -113
  149. package/dist/cli-bundle/chunks/chunk-USBTXMKS.js +0 -2
  150. package/dist/cli-bundle/chunks/chunk-VCXQ6A35.js +0 -3
  151. package/dist/cli-bundle/chunks/chunk-YPMNXG2C.js +0 -2
  152. package/dist/cli-bundle/chunks/item-revision-UAF6L47R.js +0 -2
  153. package/dist/cli-bundle/chunks/item-transaction-RJECL53Y.js +0 -2
  154. package/dist/cli-bundle/focused-chunks/chunk-2UUBS4BG.js +0 -2
  155. package/dist/cli-bundle/focused-chunks/chunk-4ER3VMST.js +0 -2
  156. package/dist/cli-bundle/focused-chunks/chunk-4YBMHMBJ.js +0 -2
  157. package/dist/cli-bundle/focused-chunks/chunk-HXM7K6VH.js +0 -100
  158. package/dist/cli-bundle/focused-chunks/chunk-NGHT2LNG.js +0 -3
  159. package/dist/cli-bundle/focused-chunks/chunk-P55AZPFN.js +0 -2
  160. package/dist/cli-bundle/focused-chunks/chunk-WAP3DF4B.js +0 -27
  161. package/dist/cli-bundle/focused-chunks/chunk-XR745UGE.js +0 -4
  162. package/dist/cli-bundle/focused-chunks/item-revision-J7EUGCHR.js +0 -2
  163. package/dist/cli-bundle/focused-chunks/mutation-admission-SLFAUONA.js +0 -2
@@ -1,4 +1,4 @@
1
- import{a as et,b as te}from"./chunk-3AZOATC2.js";import{$b as Xe,Ib as Ke,Nb as I,Ub as Ge,Xb as Ye,bc as N,fb as j,lh as Qe,mf as G,nf as Y,ph as Ze,xa as Be,za as Je}from"./chunk-SJWIPGZW.js";import{p as $e,r as q}from"./chunk-GSLOAEY2.js";import{Q as H,a as S,b as x,d as u,x as Ue}from"./chunk-VCXQ6A35.js";import{D as We,P as B,V as J,Z as K,aa as He,r as Ve}from"./chunk-TE6FBDHP.js";import{A as p,C as h,E as Fe,F as ee,H as E,J as De,K as ye,L as U,v as Me,y as c,z as $}from"./chunk-K672XXGQ.js";import tt from"node:fs/promises";import M from"node:path";var C="_workspace";function R(e){return M.join(e,"history",`${C}.jsonl`)}function we(e,t){return{metadata:{id:C,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function z(e,t=e.length){let n=Ge();for(let r of e.slice(0,t))n=Xe(n,r.patch).document;return Ye(n)}function F(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function D(e){throw new h(`Workspace history verification failed: ${e.join(", ")}`,p.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function ne(e,t){let n=M.resolve(t),r=M.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||M.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function hr(e){let t=await I(R(e),C),n=N(t);n.ok||D(n.errors);let r=F(t.length===0?$:z(t)),o=[],i=[],a=[],s=[];for(let l of Object.keys(r).sort()){let d;try{let _=ne(e,M.resolve(e,l));if(d=await E(_.absolutePath),d===null){a.push(l);continue}let f=JSON.parse(d);(S(f)===S(r[l])?o:i).push(l)}catch{s.push(l)}}return{ok:i.length===0&&a.length===0&&s.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:a,unreadable_documents:s}}async function nt(e){let t=R(e.pmRoot),n=await I(t,C),r=N(n);r.ok||D(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(f=>f.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=H(),a=n.length===0?$:z(n),s=F(a),l=s[e.documentPath];if(l!==void 0&&S(l)!==S(e.before))throw new h(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,p.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=we({...s,[e.documentPath]:e.after},n.length===0?i:a.metadata.created_at),_=G({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:a,after:d,message:e.message});return await Y(t,_),{entry:_,historyPath:t}}async function yr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await nt(e)}finally{await t()}}async function wr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=R(e.pmRoot),r=await I(n,C),o=N(r);o.ok||D(o.errors);let i=r.length===0?$:z(r),a=G({nowIso:H(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Y(n,a),{entry:a,historyPath:n}}finally{await t()}}async function rt(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await U(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await nt({pmRoot:e.pmRoot,documentPath:M.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await tt.rm(e.filePath,{force:!0}):await U(e.filePath,t),o}return!0}async function ot(e){let{documentPath:t}=ne(e.pmRoot,e.filePath),n=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await E(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await I(R(e.pmRoot),C),a=N(i);a.ok||D(a.errors);let s=F(i.length===0?$:z(i))[t];if(s!==void 0&&S(s)!==S(r===null?null:JSON.parse(r)))throw new h(`Workspace history state for "${t}" changed outside the audited mutation path.`,p.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(l=>l.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await rt({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function kr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await rt(e,await E(e.filePath))}finally{await t()}}async function gr(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=ne(e.pmRoot,e.filePath),i=R(e.pmRoot),a=await I(i,C),s=N(a);s.ok||D(s.errors);let l=z(a),d=F(l);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let _=await E(o);if(_===null)throw new TypeError(`Workspace history document is missing: ${r}`);let f=JSON.parse(_);if(S(d[r])===S(f))return{changed:!1,historyPath:i};let w=H(),W=G({nowIso:w,author:e.author,op:e.op,before:l,after:we({...d,[r]:f},l.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Y(i,W),{changed:!0,entry:W,historyPath:i}}finally{await n()}}async function br(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=ne(e.pmRoot,e.filePath),o=await I(R(e.pmRoot),C),i=N(o);if(i.ok||D(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let a=F(z(o,e.targetVersion))[n];if(a===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let s=await E(r),l=`${JSON.stringify(a,null,2)}
1
+ import{a as et,b as te}from"./chunk-3AZOATC2.js";import{$b as Xe,Ib as Ke,Nb as I,Ub as Ge,Xb as Ye,bc as N,fb as j,gh as Qe,hf as G,if as Y,kh as Ze,xa as Be,za as Je}from"./chunk-NRQCBUYD.js";import{p as $e,r as q}from"./chunk-GSLOAEY2.js";import{Q as H,a as S,b as x,d as u,x as Ue}from"./chunk-I4SPJQQI.js";import{D as We,P as B,V as J,Z as K,aa as He,r as Ve}from"./chunk-TE6FBDHP.js";import{A as p,C as h,E as Fe,F as ee,H as E,J as De,K as ye,L as U,v as Me,y as c,z as $}from"./chunk-K672XXGQ.js";import tt from"node:fs/promises";import M from"node:path";var C="_workspace";function R(e){return M.join(e,"history",`${C}.jsonl`)}function we(e,t){return{metadata:{id:C,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function z(e,t=e.length){let n=Ge();for(let r of e.slice(0,t))n=Xe(n,r.patch).document;return Ye(n)}function F(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function D(e){throw new h(`Workspace history verification failed: ${e.join(", ")}`,p.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function ne(e,t){let n=M.resolve(t),r=M.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||M.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function hr(e){let t=await I(R(e),C),n=N(t);n.ok||D(n.errors);let r=F(t.length===0?$:z(t)),o=[],i=[],a=[],s=[];for(let l of Object.keys(r).sort()){let d;try{let _=ne(e,M.resolve(e,l));if(d=await E(_.absolutePath),d===null){a.push(l);continue}let f=JSON.parse(d);(S(f)===S(r[l])?o:i).push(l)}catch{s.push(l)}}return{ok:i.length===0&&a.length===0&&s.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:a,unreadable_documents:s}}async function nt(e){let t=R(e.pmRoot),n=await I(t,C),r=N(n);r.ok||D(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(f=>f.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=H(),a=n.length===0?$:z(n),s=F(a),l=s[e.documentPath];if(l!==void 0&&S(l)!==S(e.before))throw new h(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,p.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=we({...s,[e.documentPath]:e.after},n.length===0?i:a.metadata.created_at),_=G({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:a,after:d,message:e.message});return await Y(t,_),{entry:_,historyPath:t}}async function yr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await nt(e)}finally{await t()}}async function wr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=R(e.pmRoot),r=await I(n,C),o=N(r);o.ok||D(o.errors);let i=r.length===0?$:z(r),a=G({nowIso:H(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Y(n,a),{entry:a,historyPath:n}}finally{await t()}}async function rt(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await U(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await nt({pmRoot:e.pmRoot,documentPath:M.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await tt.rm(e.filePath,{force:!0}):await U(e.filePath,t),o}return!0}async function ot(e){let{documentPath:t}=ne(e.pmRoot,e.filePath),n=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await E(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await I(R(e.pmRoot),C),a=N(i);a.ok||D(a.errors);let s=F(i.length===0?$:z(i))[t];if(s!==void 0&&S(s)!==S(r===null?null:JSON.parse(r)))throw new h(`Workspace history state for "${t}" changed outside the audited mutation path.`,p.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(l=>l.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await rt({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function kr(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await rt(e,await E(e.filePath))}finally{await t()}}async function gr(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=ne(e.pmRoot,e.filePath),i=R(e.pmRoot),a=await I(i,C),s=N(a);s.ok||D(s.errors);let l=z(a),d=F(l);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let _=await E(o);if(_===null)throw new TypeError(`Workspace history document is missing: ${r}`);let f=JSON.parse(_);if(S(d[r])===S(f))return{changed:!1,historyPath:i};let w=H(),W=G({nowIso:w,author:e.author,op:e.op,before:l,after:we({...d,[r]:f},l.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Y(i,W),{changed:!0,entry:W,historyPath:i}}finally{await n()}}async function br(e){let t=await j(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=ne(e.pmRoot,e.filePath),o=await I(R(e.pmRoot),C),i=N(o);if(i.ok||D(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let a=F(z(o,e.targetVersion))[n];if(a===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let s=await E(r),l=`${JSON.stringify(a,null,2)}
2
2
  `;if(s===l)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let d=z(o),_=H(),f=G({nowIso:_,author:e.author,op:e.op,before:d,after:we({...F(d),[n]:a},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await U(r,l);try{await Y(R(e.pmRoot),f)}catch(w){throw s===null?await tt.rm(r,{force:!0}):await U(r,s),w}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}import{AsyncLocalStorage as Qt}from"node:async_hooks";import{lstat as Zt,realpath as pt}from"node:fs/promises";import ht from"node:path";function re(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ke(e,t,n,r=[]){if(x(e,t)&&(r.length>0||re(n)))return n;if(x(e,n)||x(t,n))return t;if((e===void 0||re(e))&&re(t)&&re(n)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(n)]);return Object.fromEntries([...i].flatMap(a=>{let s=ke(Object.hasOwn(o,a)?o[a]:void 0,Object.hasOwn(t,a)?t[a]:void 0,Object.hasOwn(n,a)?n[a]:void 0,[...r,a]);return s===void 0?[]:[[a,s]]}))}throw new h(`Settings changed concurrently at ${r.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,p.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}var Jt={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},it=120;function ge(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function st(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var Kt=st(Jt),at=new WeakMap;function Gt(e){let t=at.get(e);if(t)return t;let n=st(e);return at.set(e,n),n}function Or(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return it;if(t){let o=Gt(t).get(n);if(ge(o))return Math.floor(o)}let r=Kt.get(n);return ge(r)?Math.floor(r):it}function be(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!ge(r)||(t[o]=Math.floor(r))}return t}import{stat as Yt}from"node:fs/promises";var oe=new Map;function ct(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function Xt(e){try{let t=await Yt(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function O(e){let t=ct(e),n=await Promise.all(t.map(r=>Xt(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function X(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function lt(e){return oe.get(e)}function ie(e,t){let n=ct(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));oe.set(e,{tracked_paths:n,signatures:r,value:t.value})}function L(e){if(e){oe.delete(e);return}oe.clear()}var Ee=new Qt;async function Gr(e,t,n=()=>!0){let r=new Set([ht.resolve(e)]);try{r.add(await pt(e))}catch{}let o=!1,i=[r,()=>!o&&n()];try{return await Ee.run([...Ee.getStore()??[],i],t)}finally{o=!0}}function en(e){let t=ht.resolve(e);return Ee.getStore()?.some(([n,r])=>n.has(t)&&r())??!1}var tn="settings:write",yt=Symbol("pm.settings.persist_source"),wt=Symbol("pm.settings.fallback_origin"),kt=Symbol("pm.settings.fallback_baseline"),nn=128,rn=new Set(["off","advisory","strict"]);function dt(e){return structuredClone(Me[e])}function on(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:c.governance.preset}var an=new Set(Ve);function gt(e){return an.has(e)}function ut(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),gt(t.start_blocker_enforcement)&&(e.start_blocker_enforcement=t.start_blocker_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function sn(e){return e.preset==="custom"?ut({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):ut({preset:e.preset},e)}function cn(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),gt(e.start_blocker_enforcement)&&(n.start_blocker_enforcement=e.start_blocker_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),rn.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function bt(e){let t=e.governance??{},n=on(t.preset),r=cn(t);if(n==="custom"){let a=dt("default"),s=r.require_close_reason??a.require_close_reason;return{preset:n,ownership_enforcement:t.ownership_enforcement??a.ownership_enforcement,create_mode_default:t.create_mode_default??a.create_mode_default,close_validation_default:t.close_validation_default??a.close_validation_default,parent_reference:t.parent_reference??a.parent_reference,metadata_profile:t.metadata_profile??a.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??a.force_required_for_stale_lock,...r,require_close_reason:s,duplicate_detection_mode:r.duplicate_detection_mode??a.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??a.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??a.duplicate_detection_limit}}let o=dt(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Te(){return structuredClone(c)}function xt(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:c.search.mutation_refresh_policy}function vt(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function St(e){return typeof e=="boolean"?e:c.search.query_expansion.enabled}function Et(e){return typeof e!="string"?c.search.query_expansion.provider:e.trim()}function Ct(e){return typeof e=="boolean"?e:c.search.rerank.enabled}function Ot(e){return typeof e!="string"?c.search.rerank.model:e.trim()}function Tt(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:c.search.rerank.top_k}function At(e){if(typeof e!="string")return c.vector_store.collection_name;let n=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,nn);return n.length>0?n:c.vector_store.collection_name}function xe(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function Pt(e,t){let n=e.schema,r=xe(n?.statuses),o=xe(n?.fields),i=xe(n?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:V(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:V(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function ce(e,t){Object.defineProperty(e,yt,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Ae(e){let t=e[yt];if(!(!t||typeof t!="object"))return t}function Yr(e){let t=Ae(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,ce(e,n)}}function ae(e){let t=structuredClone(e.settings),n=Ae(e.settings);n&&ce(t,n);let r=Pe(e.settings);return r!==void 0&&jt(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function ln(e,t,n){let r=J(t);return[n,K(e,r.files.types,B.types),K(e,r.files.statuses,B.statuses),K(e,r.files.fields,B.fields),K(e,r.files.workflows,B.workflows)]}async function dn(e,t,n){let r=await O(t);ie(e,{tracked_paths:t,signatures:r,value:ae(n)})}async function un(e,t,n){try{await dn(e,t,n)}catch{L(e)}}function _t(e,t){return e.find(n=>n.path===t)}function _n(e,t,n){for(let r of n){let o=_t(e,r),i=_t(t,r);if(!o||!i||!X([o],[i]))return!1}return!0}async function ve(e,t,n,r,o){try{let i=await O(t);if(!_n(r,i,o)){L(e);return}ie(e,{tracked_paths:t,signatures:i,value:ae(n)})}catch{L(e)}}function fn(e,t){let n=J(e.schema),r=V(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=x(r,t.runtime_item_type_definitions),a=x(n.statuses,t.runtime_schema_statuses),s=x(n.fields,t.runtime_schema_fields),l=x(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?V(t.source_item_type_definitions):[]:r,schema_statuses:a?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:s?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:l?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function jt(e,t){Object.defineProperty(e,wt,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Xr(e){return Pe(e)!==void 0}function Pe(e){let t=e[wt];return typeof t=="string"?t:void 0}function mn(e){return e[kt]}function pn(e,t){Object.defineProperty(e,kt,{value:t,writable:!0,configurable:!0,enumerable:!1})}function v(e){let t=Te();return e!==void 0&&jt(t,e),{settings:t,metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function It(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Ce(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Nt(e){let t=c.agent_guidance,n=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:Ce(e?.last_checked_files??t.last_checked_files)}}function b(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function hn(e){return e==="off"||e==="warn"||e==="enforce"?e:c.extensions.policy.mode}function yn(e){return e==="off"||e==="warn"||e==="enforce"?e:c.extensions.policy.trust_mode}function Rt(e){return e==="none"||e==="restricted"||e==="strict"?e:c.extensions.policy.default_sandbox_profile}function wn(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=Rt(e.sandbox_profile));let r=b(e.allowed_capabilities),o=b(e.blocked_capabilities),i=b(e.allowed_surfaces),a=b(e.blocked_surfaces),s=b(e.allowed_commands),l=b(e.blocked_commands),d=b(e.allowed_actions),_=b(e.blocked_actions),f=b(e.allowed_services),w=b(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),a.length>0&&(n.blocked_surfaces=a),s.length>0&&(n.allowed_commands=s),l.length>0&&(n.blocked_commands=l),d.length>0&&(n.allowed_actions=d),_.length>0&&(n.blocked_actions=_),f.length>0&&(n.allowed_services=f),w.length>0&&(n.blocked_services=w),n}function kn(e){let t=new Map;for(let n of e??[]){let r=wn(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Se(e){return e==="block"||e==="warn"?e:void 0}function gn(e){if(typeof e=="string")return Se(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Se(e.global),n=Se(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function k(e,t){return b(e?.[t]??c.extensions.policy[t])}function zt(e){let t=gn(e?.pm_max_version_exceeded_mode);return{mode:hn(e?.mode),trust_mode:yn(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:k(e,"trusted_extensions"),default_sandbox_profile:Rt(e?.default_sandbox_profile),allowed_extensions:k(e,"allowed_extensions"),blocked_extensions:k(e,"blocked_extensions"),allowed_capabilities:k(e,"allowed_capabilities"),blocked_capabilities:k(e,"blocked_capabilities"),allowed_surfaces:k(e,"allowed_surfaces"),blocked_surfaces:k(e,"blocked_surfaces"),allowed_commands:k(e,"allowed_commands"),blocked_commands:k(e,"blocked_commands"),allowed_actions:k(e,"allowed_actions"),blocked_actions:k(e,"blocked_actions"),allowed_services:k(e,"allowed_services"),blocked_services:k(e,"blocked_services"),extension_overrides:kn(e?.extension_overrides??c.extensions.policy.extension_overrides)}}function Lt(e){return[...new Set((e??[]).map(n=>n.trim().toLowerCase().replaceAll("-","_")))].filter(n=>n.length>0).sort((n,r)=>n.localeCompare(r)).filter(n=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(n))}function T(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function m(e,t){return e===void 0?t:e}function g(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Oe(e){return Array.isArray(e)?e:[]}function bn(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:Lt(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:T(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:T(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:T(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:T(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:be(e.validation?.estimate_defaults_by_type)}}function xn(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function vn(e,t){return{...t.search,...e.search,default_mode:vt(e.search?.default_mode),mutation_refresh_policy:xt(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:St(e.search?.query_expansion?.enabled),provider:Et(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Ct(e.search?.rerank?.enabled),model:Ot(e.search?.rerank?.model),top_k:Tt(e.search?.rerank?.top_k)}}}function Sn(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:At(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function En(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function Cn(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??t.context.next_ranking_policy,sections:{...t.context.sections,...e.context?.sections}}}function On(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}async function Tn(e,t){let n=await He(e,t.schema);return{settings:{...t,item_types:{definitions:V([...t.item_types.definitions,...Oe(n.type_definitions_from_file)])},schema:n.schema},warnings:n.warnings}}function V(e){let t=(e??[]).map(r=>We(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function se(e){let t=Te(),n=bt({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:En(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:bn(e,t,n),governance:n,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:xn(e,t),agent_guidance:Nt(e.agent_guidance??t.agent_guidance),item_types:{definitions:V(e.item_types?.definitions)},schema:J(e.schema??t.schema),context:Cn(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:zt(e.extensions.policy??t.extensions.policy)},search:vn(e,t),providers:On(e,t),vector_store:Sn(e,t)}}function An(e){e.agent_identity=u(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=u(g(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Oe(e.agent_identity.harness_signals).map(n=>u(g(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=u(e.locks,["ttl_seconds","wait_ms"]),e.ids=u(e.ids,["token_length"]),e.mutation_guard=u(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=u(e.checkpoints,["retention_days"]),e.output=u(e.output,["default_format"]),e.ux=u(e.ux,["deprecation_hints"]),e.history=u(e.history,["missing_stream","compact_policy"]),e.validation=u(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=u(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=u(e.workflow,["definition_of_done"]),e.testing=u(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=u(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=u(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=u(e.item_types,["definitions"]),e.schema=u(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=u(g(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=u(g(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=u(e.context,["default_depth","activity_limit","stale_threshold_days","next_ranking_policy","sections"]),e.context.sections=u(g(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=u(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=u(g(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),e.extensions.policy.extension_overrides=Oe(e.extensions.policy.extension_overrides).map(n=>u(g(n),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=u(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=u(g(e.search.query_expansion),["enabled","provider"]),e.search.rerank=u(g(e.search.rerank),["enabled","model","top_k"]),e.providers=u(e.providers,["openai","ollama"]),e.providers.openai=u(g(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=u(g(e.providers.ollama),["base_url","model"]),e.vector_store=u(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=u(g(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=u(g(e.vector_store.lancedb),["path"])}function Pn(e){return{...e,locks:m(e.locks,c.locks),ids:m(e.ids,c.ids),agent_identity:m(e.agent_identity,c.agent_identity),mutation_guard:m(e.mutation_guard,c.mutation_guard),checkpoints:m(e.checkpoints,c.checkpoints),output:m(e.output,c.output),ux:m(e.ux,c.ux),history:m(e.history,c.history),validation:m(e.validation,c.validation),workflow:m(e.workflow,c.workflow),testing:m(e.testing,c.testing),telemetry:m(e.telemetry,c.telemetry),agent_guidance:m(e.agent_guidance,c.agent_guidance),item_types:m(e.item_types,c.item_types),schema:m(e.schema,c.schema),context:m(e.context,c.context),extensions:m(e.extensions,c.extensions),search:m(e.search,c.search),providers:m(e.providers,c.providers),vector_store:m(e.vector_store,c.vector_store)}}function jn(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:Lt(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:T(e.validation?.lifecycle_stale_blocker_reason_patterns??c.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:T(e.validation?.lifecycle_closure_like_blocked_reason_patterns??c.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:T(e.validation?.lifecycle_closure_like_resolution_patterns??c.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:T(e.validation?.lifecycle_closure_like_actual_result_patterns??c.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:be(e.validation?.estimate_defaults_by_type)}}function In(e){return{...c.search,...e.search,default_mode:vt(e.search?.default_mode),mutation_refresh_policy:xt(e.search?.mutation_refresh_policy),query_expansion:{...c.search.query_expansion,...e.search?.query_expansion,enabled:St(e.search?.query_expansion?.enabled),provider:Et(e.search?.query_expansion?.provider)},rerank:{...c.search.rerank,...e.search?.rerank,enabled:Ct(e.search?.rerank?.enabled),model:Ot(e.search?.rerank?.model),top_k:Tt(e.search?.rerank?.top_k)}}}function Nn(e){return{default_depth:e.context?.default_depth??c.context.default_depth,activity_limit:e.context?.activity_limit??c.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??c.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??c.context.next_ranking_policy,sections:{...c.context.sections,...e.context?.sections}}}function Rn(e){return{...e.vector_store,adapter:e.vector_store?.adapter??c.vector_store.adapter,collection_name:At(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function zn(e,t,n,r){return{...e,item_format:"toon",validation:jn(e,t),governance:t,agent_guidance:Nt(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:In(e),context:Nn(e),extensions:{enabled:Ce(e.extensions?.enabled),disabled:Ce(e.extensions?.disabled),policy:zt(e.extensions?.policy)},vector_store:Rn(e)}}function qt(e,t){for(let n of Object.keys(t)){let r=Reflect.get(t,n),o=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?qt(o,r):e[n]=structuredClone(r)}}function je(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],a=n[o];if(!x(i,a)){if(a===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof a=="object"&&a!==null&&!Array.isArray(a)){let s=e[o],l=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:{};je(l,i,a),Object.keys(l).length>0?e[o]=l:delete e[o];continue}e[o]=structuredClone(a)}}}var le=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function ft(e,t){let n=Pn(e),r=bt(n),o=J(n.schema),i=fn(n,t),a=zn(n,r,o,i),s=u({...a,governance:sn(r)},le);return An(s),s}function Mt(e,t={}){let n=t.source===void 0?t.persist_source:Pt(t.source.validated,se(t.source.validated)),r=ft(e,n);if(n){let o=se(n.source_settings);o.item_types={definitions:structuredClone(n.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(n.runtime_schema_statuses),fields:structuredClone(n.runtime_schema_fields),type_workflows:structuredClone(n.runtime_schema_type_workflows)};let i=ft(o,n);t.source!==void 0&&qt(i,t.source.validated);let a=structuredClone(t.source===void 0?n.source_settings:t.source.raw);return je(a,i,r),`${JSON.stringify(u(a,le),null,2)}
3
3
  `}return`${JSON.stringify(r,null,2)}
4
4
  `}async function Ln(e){let t;try{t=await pt(e)}catch(s){if(ee(s))return v();throw s}let n=q(t),r;try{r=await Zt(n)}catch(s){if(ee(s))return v();throw s}if(!r.isFile())throw ye("settings.json");let o;try{o=await De(n,ye("settings.json"))}catch(s){if(ee(s))return v();throw s}let i;try{i=JSON.parse(o)}catch{return v("settings_read_invalid_json")}let a=te(i);return a.success?{settings:se(a.data),metadata:{has_explicit_item_format:It(i)},warnings:a.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:v("settings_read_invalid_schema")}async function Ft(e){if(en(e))return Ln(e);let t=q(e),n=[t];await Ze({path:t,scope:"project"});let r=lt(e);if(r){let d=await O(r.tracked_paths);if(X(d,r.signatures))return ae(r.value)}let o=await O([t]),i;try{i=await E(t)}catch{return v("settings_read_fs_error")}if(i===null){let d=v();return await ve(e,[t],d,o,[t]),d}let a=await O([t]);if(!X(o,a))return L(e),Ft(e);let s;try{s=JSON.parse(i)}catch{let d=v("settings_read_invalid_json");return await ve(e,[t],d,a,[t]),d}let l=te(s);if(!l.success){let d=v("settings_read_invalid_schema");return await ve(e,[t],d,a,[t]),d}try{let d=se(l.data),_=ln(e,d.schema,t);n=_;let f=await O(_),w=await Tn(e,d),W=await O(_),he=w.settings;ce(he,Pt(l.data,he));let qe={settings:he,metadata:{has_explicit_item_format:It(s)},warnings:[...l.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...w.warnings]};return X(f,W)?ie(e,{tracked_paths:_,signatures:W,value:ae(qe)}):L(e),qe}catch{let d=v("settings_read_merge_failed");return await un(e,n,d),d}}function qn(e,t=[],n=null){let r=Ie(n)??{},o=t.filter(a=>!Object.hasOwn(r,a));if(o.length===0)return e;let i=JSON.parse(e);for(let a of o)Reflect.deleteProperty(i,a);return`${JSON.stringify(i,null,2)}
@@ -6,4 +6,4 @@ import{a as et,b as te}from"./chunk-3AZOATC2.js";import{$b as Xe,Ib as Ke,Nb as
6
6
  `}function Un(e){try{return JSON.parse(e)}catch{throw new h("Existing settings.json is malformed; the settings write was refused.",p.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}}async function Qr(e){return(await Ft(e)).settings}async function Zr(e,t,n=tn,r={}){let o=r.assignedPaths??[];Dn(o);let i=q(e),a=Ae(t),s=a?void 0:Pe(t),l=Mt(t,{persist_source:a}),d=JSON.parse(l),_=!1;try{if(await ot({pmRoot:e,filePath:i,mutate:f=>{let w=f===null?null:Un(f);return f!==null&&r.skipIfStored?.(w)===!0?(_=!0,{raw:f,result:void 0}):s!==void 0&&f!==null?{raw:$n(w,d,s,o,mn(t)),result:void 0}:{raw:a?`${JSON.stringify(u(ke(a.persisted_settings,d,w),le),null,2)}
7
7
  `:qn(l,r.omitSections,w),result:void 0}},op:n,author:Ke(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),_)return;a?ce(t,{...a,persisted_settings:structuredClone(d)}):s!==void 0&&pn(t,structuredClone(d)),await Qe({path:i,scope:"project",op:n})}finally{L(e)}}import Vt from"node:fs";import Q from"node:path";import{createRequire as Hn}from"node:module";var Z="@unbrained/pm-cli",Bn=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),Wt=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),Re=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,fe="2026.8.31";function y(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function Ne(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||y(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var Jn={changelog:(e,t)=>{if(t[0]==="generate")return!y(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(y(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>y(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>y(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Ne,files:(e,t)=>y(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&y(e,["--apply"]),health:e=>!y(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>y(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>y(e,["--add","--delete","--edit","--file","--stdin"]),package:Ne,packages:Ne,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(y(e,["--infer"])&&!y(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>y(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>y(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function ue(e){let t=e.match(Re);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function A(e,t){let n=ue(e),r=ue(t);if(!n||!r)return null;for(let o=0;o<n.length;o+=1){let i=n[o]-r[o];if(i!==0)return Math.sign(i)}return 0}function de(e){return A(e,fe)!==-1?3:2}function Kn(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>A(n.version,r.version))[0]}function _e(e){try{let t=JSON.parse(Vt.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function Gn(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function Yn(e){let t=e.split("||").map(n=>Gn(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let o=A(fe,r.version);return o!==null&&(r.inclusive?o!==1:o===-1)}))}}function $t(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[Z];return typeof r=="string"?[r.trim()]:[]})}function Xn(e){return $t(e).flatMap(t=>{let n=/^[<!]/u.test(t)?void 0:t.match(Re)?.[0];if(!n)return[];let r=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=Yn(t);return[{version:n,constraint:r?"exact":o.bounded?"range":"minimum",...r?{}:{declaration:t},history_epoch_compatible:r?A(n,fe)!==-1:o.compatible}]})}function Qn(e){let n=_e(Q.join(e,"package-lock.json"))?.packages;if(typeof n!="object"||n===null)return;let r=n["node_modules/@unbrained/pm-cli"];if(typeof r!="object"||r===null)return;let o=r.version;return typeof o=="string"?o:void 0}function Zn(e,t){try{let n=Vt.readFileSync(Q.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(l=>l.includes(Z));if(r<0)return;let o=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let l=r+1;l<n.length;l+=1){let d=n[l],_=d.trim(),f=d.match(/^\s*/u)[0].length;if(_.length>0&&f<=o)break;i.push(d)}return i.join(`
8
8
  `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(Re)?.[0]}catch{return}}function Ut(e){let t=[],n=_e(Q.join(e,"package.json"));n&&t.push(...Xn(n).map(a=>({...a,source:"package.json"})));let o=_e(Q.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof o=="string"&&ue(o)&&t.push({version:o,source:"installed-package",constraint:"exact",history_epoch_compatible:de(o)===3});let i=Qn(e);i&&ue(i)&&t.push({version:i,source:"package-lock.json",constraint:"exact",history_epoch_compatible:de(i)===3});for(let a of["pnpm-lock.yaml","yarn.lock"]){let s=Zn(e,a);s&&t.push({version:s,source:a,constraint:"exact",history_epoch_compatible:de(s)===3})}return t}function er(e,t){if(t<=1)return;let{minVersion:n,lt:r}=Hn(import.meta.url)("semver"),o=$t(_e(Q.join(e,"package.json"))??{}).find(a=>{try{let s=n(a);return s!==null&&r(s,"2026.10.10")}catch{return!1}}),i=o===void 0?Ut(e).find(a=>A(a.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new h(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,p.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function co(e,t){let n=Je(e);n<=1||(er($e(t),n),e.pm_format_version=n)}function Ht(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(Wt.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function tr(e){let t=Ht(e);if(!t||y(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,o=[];for(let a=r+1;a<e.length;a+=1){let s=e[a];if(Wt.has(s)){a+=1;continue}s.startsWith("-")||o.push(s.toLowerCase())}let i=Jn[n];return i?i(e,o):Bn.has(n)}function nr(e){let t=Ht(e.argv)?.command,n=tr(e.argv),r=Ut(e.projectRoot).filter(_=>A(_.version,e.executingVersion)!==null).sort((_,f)=>A(f.version,_.version)),o=r[0],i=o!==void 0&&A(e.executingVersion,o.version)===-1,a=de(e.executingVersion),s=Kn(r,a),l=n&&s!==void 0,d=i&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:o.version,source:o.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${Z} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!l||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:n,stale:i,history_epoch_incompatible:l,writer_item_hash_version:a,...s?{incompatible_project_version:s.declaration,incompatible_source:s.source}:{},...d?{warning:d}:{},override_applied:n&&(i||l)&&e.allowStale===!0}}function lo(e){let t=nr(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new h(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,p.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${Z} pin to ${fe} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new h(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,p.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${Z} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import Le from"node:fs/promises";import me from"node:path";function P(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Bt(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:Ue(t),suggested_retry_args:t}}function pe(e){return new h(`Tracker root is not a directory at ${e}.`,p.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function ze(e){return new h(`Tracker root is not readable at ${e}.`,p.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function rr(e){let t=me.resolve(e),n=me.parse(t).root,r=me.dirname(t);for(;r!==n;){let o;try{o=await Le.stat(r)}catch(i){if(P(i,"ENOTDIR"))throw pe(e);if(!P(i,"ENOENT"))throw i;r=me.dirname(r);continue}if(!o.isDirectory())throw pe(e);return}}async function or(e){let t;try{t=await Le.stat(e)}catch(n){throw P(n,"ENOENT")?(await rr(e),new h(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,p.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:Bt(e)})):P(n,"ENOTDIR")?pe(e):P(n,"EACCES")||P(n,"EPERM")?ze(e):n}if(!t.isDirectory())throw pe(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw ze(e);try{await(await Le.opendir(e)).close()}catch(n){throw P(n,"EACCES")||P(n,"EPERM")?ze(e):n}}async function ko(e){if(await or(e),!await Fe(q(e)))throw new h(`Tracker is not initialized at ${e}. Run pm init first.`,p.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:Bt(e)})}export{C as a,R as b,hr as c,yr as d,wr as e,ot as f,kr as g,gr as h,br as i,Or as j,L as k,Gr as l,en as m,bt as n,Yr as o,Xr as p,Tn as q,se as r,Mt as s,Ft as t,Qr as u,Zr as v,fe as w,A as x,de as y,Ut as z,er as A,co as B,tr as C,nr as D,lo as E,Bt as F,or as G,ko as H};
9
- //# sourceMappingURL=chunk-KXTKLDKD.js.map
9
+ //# sourceMappingURL=chunk-OXC5KBIQ.js.map
@@ -1,3 +1,3 @@
1
- import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-2SBTXR6C.js";import{lb as w,mb as R,nb as k}from"./chunk-ZA5NS3PL.js";import{Ka as v,pa as p,sa as g,ta as a}from"./chunk-KCVSSONY.js";import{_ as O,kd as B}from"./chunk-3TXEWHQX.js";import{Pe as H,Ue as u,Ve as y,fh as I}from"./chunk-SJWIPGZW.js";import{A as c,C as f}from"./chunk-K672XXGQ.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
1
+ import{a as A,c as b,d as C,e as E,k as S,m as x}from"./chunk-SY5C3U32.js";import{lb as w,mb as R,nb as k}from"./chunk-ZL6J6JYT.js";import{Ka as v,pa as p,sa as g,ta as a}from"./chunk-C6WM6ZN4.js";import{_ as O,kd as B}from"./chunk-CBUC4X7Q.js";import{Ke as H,Pe as u,Qe as y,ah as I}from"./chunk-NRQCBUYD.js";import{A as c,C as f}from"./chunk-K672XXGQ.js";function _(r,e){if(typeof r!="string")return;let o=Number.parseInt(r,10);if(!/^\d+$/.test(r.trim())||!Number.isSafeInteger(o))throw new f(`history-compact ${e} must be a non-negative integer.`,c.USAGE);return o}async function D(r,e,o){let t=p(o),s=Date.now(),i=await O(a(e,"ids")),l=i===void 0?void 0:B(i),m=_(e.allOver,"--all-over"),d=_(e.minEntries,"--min-entries");if(e.closed===!0&&e.allStreams===!0)throw new f("history-compact: --closed and --all-streams are mutually exclusive; pick one lifecycle scope.",c.USAGE);let n=e.closed===!0?"closed":e.allStreams===!0?"all-streams":void 0;if((l!==void 0||m!==void 0||n!==void 0)&&typeof e.before=="string")throw new f("history-compact: --before applies only in single-id mode (bulk mode always compacts full streams).",c.USAGE);if(b(r,{ids:l,allOver:m,scope:n}),r!==void 0&&d!==void 0)throw new f("history-compact: --min-entries applies only in bulk mode (single-id mode compacts the named stream).",c.USAGE);if(r===void 0){let h=await C({ids:l,scope:n,allOver:m,minEntries:d,dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t),h.totals.items_errored>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let h=await A(r,{before:a(e,"before"),dryRun:e.dryRun===!0,author:a(e,"author"),message:a(e,"message"),force:!!e.force},t);u(h,t)}t.profile&&y(`profile:command=history-compact took_ms=${Date.now()-s}`)}async function N(r,e,o,t){let s=p(t),i=Date.now(),l=await x(r,e,{author:a(o,"author"),message:a(o,"message"),force:!!o.force},s);await v(s,l),u(l,s),s.profile&&y(`profile:command=restore took_ms=${Date.now()-i}`)}async function F(r,e){let o=p(e),t=await S({verify:a(r,"verify"),output:a(r,"output"),hashAlgorithm:a(r,"hashAlgorithm")},o);"format"in t?(I(t),o.quiet||H(`${JSON.stringify(t,null,2)}
2
2
  `)):u(t,o),"ok"in t&&!t.ok&&(process.exitCode=c.GENERIC_FAILURE)}function ee(r,e){r.command(e?"attest":"history-attest",{hidden:!e}).summary("Export or verify history proof.").option("--verify <file>","Compare retained streams with a detached JSON proof").option("--output <file>","Create a proof file and return a compact receipt").option("--hash-algorithm <name>","Bundle digest algorithm: sha256 (default) or sha512").description("Export exact-byte history commitments, or verify an independently retained proof without tracker writes.").action(F),r.command("restore",{hidden:!e}).summary("Restore a version.").argument("<id>","Item id").argument("<target>","Restore target timestamp or version number").option("--author <value>","Mutation author").option("--message <value>","History message").option("--force","Force ownership/lock override").description("Restore an item to an earlier timestamp or version.").action(N),r.command(e?"redact":"history-redact",{hidden:!e}).summary("Redact sensitive values.").argument("<id>","Item id").option("--literal <value>","Literal; repeatable",g).option("--regex <value>","Raw RegExp source (repeatable; e.g. /var/[a-z]+) or /pattern/flags. Leading-slash input is a literal only when the final unescaped slash is followed by supported JavaScript flag letters or nothing.",g).option("--replacement <value>",'Default: "[redacted]"').option("--dry-run","Preview; no item/history edits").option("--author <value>","Author").option("--message <value>","Audit marker message").option("--force","Override owner/lock").description("Redact and reseal item history.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=Array.isArray(t.literal)?t.literal:void 0,d=Array.isArray(t.regex)?t.regex:void 0,n=await E(o,{literal:m,regex:d,replacement:a(t,"replacement"),dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force},i);n.changed&&!n.dry_run&&await v(i,n),u(n,i),i.profile&&y(`profile:command=history-redact took_ms=${Date.now()-l}`)}),r.command(e?"repair":"history-repair",{hidden:!e}).summary("Repair drift.").argument("[id]","Item id (omit with --all)").option("--salvage-tail","Recover invalid tail; requires verified prefix").option("--append-only","Bridge breaks; never rewrite entries").option("--all","Scan every stream for drift and repair each drifted stream in one audited pass").option("--dry-run","Preview the re-anchor impact without writing the history file").option("--normalize-provenance","Remove invalid provenance; return aggregate-only evidence").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the repair marker entry").option("--force","Force ownership/lock override").description("Re-anchor a drifted item history chain (recompute hashes, reconcile with the on-disk item) and record an audit marker. Use --all to repair every drifted stream.").action(async(o,t,s)=>{let i=p(s),l=Date.now(),m=t.all===!0;R(o,m);let d={dryRun:t.dryRun===!0,author:a(t,"author"),message:a(t,"message"),force:!!t.force,normalizeProvenance:t.normalizeProvenance===!0,salvageTail:t.salvageTail===!0,appendOnly:t.appendOnly===!0};if(m){let n=await k(d,i);u(n,i),n.totals.failed>0&&(process.exitCode=c.GENERIC_FAILURE)}else{let n=await w(o,d,i);u(n,i)}i.profile&&y(`profile:command=history-repair took_ms=${Date.now()-l}`)}),r.command(e?"compact":"history-compact",{hidden:!e}).summary("Compact streams.").argument("[id]","Item id (omit when using a bulk selector)").option("--before <value>","Compact entries strictly before this version number or ISO timestamp (single-id mode only)").option("--ids <value>","Bulk IDs: comma/newline text, - stdin, or @path file").option("--all-over <n>","Bulk: compact every stream with more than N entries").option("--closed","Bulk: compact only closed (terminal) items' streams").option("--all-streams","Bulk: compact every history stream regardless of lifecycle state").option("--min-entries <n>","Bulk: skip streams with at most N entries (already compact; default 3)").option("--dry-run","Preview compaction impact without writing the history file").option("--author <value>","Mutation author").option("--message <value>","Audit history message for the compaction marker entry").option("--force","Force ownership/lock override").description("Compact item history streams into a synthetic baseline plus retained tail entries. Pass an item id for one stream, or a bulk selector (--ids/--all-over/--closed/--all-streams) to compact many.").action(D)}export{ee as a};
3
- //# sourceMappingURL=chunk-HXQ3OHQR.js.map
3
+ //# sourceMappingURL=chunk-PCDTWL6V.js.map
@@ -1,2 +1,2 @@
1
- import{$a as ae,Ub as ut,Vb as ft,Xb as ce,_b as pt,a as tt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-NZSXWIX7.js";import{u as dt}from"./chunk-2SBTXR6C.js";import{Xb as ct}from"./chunk-WFYE34TO.js";import{m as at}from"./chunk-Q4VZSMUL.js";import{a as nt,c as P,d as oe,e as rt,f as se,g as it}from"./chunk-IGEFPHV7.js";import{j as z,m as G}from"./chunk-KCVSSONY.js";import{Ra as ie,d as Re,ea as Ye,ga as x,qb as Xe,qc as et,t as Ie,u as Me,v as X,wb as Qe}from"./chunk-3TXEWHQX.js";import{m as Ze,u as D}from"./chunk-KXTKLDKD.js";import{b as He}from"./chunk-3AZOATC2.js";import{$g as We,Ha as De,Jb as Ke,Ma as Pe,Nb as U,Ua as ze,Va as Ge,Wa as re,ah as C,cf as F,hb as qe,hg as Je,if as Le,ja as je,mh as Be,nh as Ve,of as M}from"./chunk-SJWIPGZW.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{ta as ot,za as st}from"./chunk-JPJNJHQW.js";import{a as b,da as ne}from"./chunk-VCXQ6A35.js";import{P as Ue,V as te,Z as Fe,aa as xe,ea as v}from"./chunk-TE6FBDHP.js";import{A as f,C as u,G as Q,J as Ce,K as I,l as $e,q as R,t as Te,y as ke}from"./chunk-K672XXGQ.js";import ge from"node:crypto";import{constants as me,readFileSync as Jn}from"node:fs";import{cp as Wn,lstat as qt,mkdir as Bn,mkdtemp as Kt,open as Vn,readdir as Yn,realpath as Lt,rm as Jt,stat as _e,writeFile as Wt}from"node:fs/promises";import{tmpdir as Bt}from"node:os";import m from"node:path";import Tt from"node:crypto";var A=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...$e,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function wt(e){if(e===void 0)return;let t=e.replace(/[A-Z]/gu,n=>`_${n.toLowerCase()}`);return A.has(t)?t:e}function q(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new u(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,f.USAGE,{code:"mutation_option_value_invalid",required:'Pass estimatedMinutes as a string, for example "45", in raw mutation options.',why:"Raw options use the create/update command option types; item documents accept numeric estimated_minutes instead.",nextSteps:["Quote the estimatedMinutes value or use an item document with numeric estimated_minutes, then retry the transaction."]})}var de=["op","id","reason","options","unique","match"],sn=[...de,"ref"],gt=[...sn,"item"],an="mutate-",_t="row-",St=["schema_version","mutations"],kt="[a-z][a-z0-9._-]{0,63}",Et=new RegExp(`^${kt}$`,"u"),Rt=new RegExp(`(^|,)id=@(${kt})(?=,|$)`,"gu"),Ot=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),K=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],It=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),cn=new Set([...It,"completed_at","id"]),Mt={create:z.map(e=>e.target),update:G.map(e=>e.target),close:ot.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:st.map(e=>Ot(e.flag))};function Pr(e){let t=Tt.createHash("sha256").update(e).digest("hex");return`${an}${t.slice(0,24)}`}function zr(e){let t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new u("createCompensation must be close or delete.",f.USAGE);t.createCompensation=n}for(let r of["lockTtlSeconds","lockWaitMs"]){let i=e[r];if(i===void 0)continue;let s=typeof i=="number"||typeof i=="string"&&i.trim().length>0?Number(i):Number.NaN;if(!Number.isSafeInteger(s)||s<=0)throw new u(`${r} must be a positive safe integer.`,f.USAGE);t[r]=s}return t}function w(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function L(e,t){let n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1)),r;for(let i of t){let s=je(e,i,n);s!==null&&(r===void 0||s<r.distance)&&(r={key:i,distance:s})}return r?.key}function $(e,t,n){let r=L(t,n);return new u(r===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${r}"?`,f.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${e} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[r===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${r}".`]})}function pe(e,t){try{return JSON.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new u(`${t} must be valid JSON: ${r}`,f.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${t.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function dn(e,t){if(!w(e))throw new u(`Mutation ${t+1} must be an object.`,f.USAGE);for(let n of Object.keys(e))if(!de.includes(n))throw $(`mutation ${t+1}`,n,de);return e}function un(e,t,n,r){if(e===void 0)return;if(!w(e))throw new u(`Mutation ${n+1} options must be an object.`,f.USAGE);let i=[...Mt[t],...jt(t,r)];for(let s of Object.keys(e))if(!i.includes(s))throw $(`mutation ${n+1} ${t} options`,s,i);return q(e,t,n),e}function bt(e,t,n,r){if(e===void 0)return;let i=r==="unique"?"create":"update";if(t!==i)throw new u(`Mutation ${n+1} ${r} is only valid for ${i} operations.`,f.USAGE);let s=w(e)&&typeof e.key=="string"?e.key.trim():"";if(!w(e)||s.length===0||e.value===void 0||e.value===null)throw new u(`Mutation ${n+1} ${r} must be an object with a non-empty key and a value.`,f.USAGE);return{key:s,value:e.value}}function fn(e,t,n){let r=dn(e,t),{op:i,id:s,reason:o}=r;if(i!=="create"&&i!=="update"&&i!=="close"&&i!=="release")throw new u(`Mutation ${t+1} op must be create, update, close, or release.`,f.USAGE);let a=un(r.options,i,t,n),d=bt(r.unique,i,t,"unique"),c=bt(r.match,i,t,"match");if(typeof s!="string"||s.trim().length===0)throw new u(`Mutation ${t+1} requires a non-empty id.`,f.USAGE);let p=s.trim();if(i==="close"){if(typeof o!="string"||o.trim().length===0)throw new u(`Mutation ${t+1} close requires a non-empty reason.`,f.USAGE);return{op:i,id:p,reason:o.trim(),...a===void 0?{}:{options:a}}}if(i==="release")return{op:i,id:p,...a===void 0?{}:{options:a}};if(!w(a))throw new u(`Mutation ${t+1} ${i} requires an options object.`,f.USAGE);return{op:i,id:p,options:a,...d===void 0?{}:{unique:d},...c===void 0?{}:{match:c}}}function Ct(e,t={}){let n=pe(e,"Mutation batch"),r=Array.isArray(n)?n:w(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(r===void 0||r.length===0)throw new u("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",f.USAGE);let i=t.runtimeFields??[];return r.map((s,o)=>{let a=fn(s,o,i);return a.options!==void 0&&Ie(a.options),a})}function pn(e,t,n){let r=Tt.createHash("sha256").update(e).update("\0").update(t).digest("hex"),i=BigInt(`0x${r.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Ye(n)}${i}`}function vt(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;let n=e.slice(1),r=t[n];if(r===void 0)throw new u(`Unknown mutation reference "${e}".`,f.USAGE);return r}function At(e,t){if(typeof e!="string")return e;let n=e.replace(Rt,(r,i,s)=>{let o=t[s];if(o===void 0)throw new u(`Unknown mutation reference "@${s}".`,f.USAGE);return`${i}id=${o}`});if(/(^|,)id=@/u.test(n))throw new u(`Malformed mutation reference in dependency "${e}".`,f.USAGE);return n}function ln(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(Rt)].map(t=>t[1]).filter(t=>t!==void 0)}function mn(e,t){let n=new Map;for(let[o,a]of e.entries()){let d=t[o];if(d===void 0)continue;let c=w(a.options)?a.options:{},p=Array.isArray(c.dep)?c.dep:c.dep===void 0?[]:[c.dep];n.set(d,[c.parent,c.blockedBy,...p].flatMap(ln))}let r=new Set,i=new Set,s=o=>{if(r.has(o))throw new u(`Mutation reference cycle includes "@${o}".`,f.USAGE);if(!i.has(o)){r.add(o);for(let a of n.get(o))n.has(a)&&s(a);r.delete(o),i.add(o)}};for(let o of n.keys())s(o)}function hn(e){let n=e.split(/\r?\n/u).map((o,a)=>({line:o.trim(),number:a+1})).filter(o=>o.line.length>0);if(n.length<2)return null;let r=n.map(o=>{try{return{...o,ok:!0,value:JSON.parse(o.line)}}catch(a){return{...o,ok:!1,error:a}}}),i=r[0];if(!i.ok&&(i.line.startsWith("[")||i.line==="{"||r.at(-1).line==="}")||!r.some(o=>o.ok&&w(o.value)))return null;let s=[];for(let o of r){if(!o.ok)throw new u(`Mutation document line ${o.number} must be one valid JSON object: ${et(o.error)}`,f.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!w(o.value))throw new u(`Mutation document line ${o.number} must be a JSON object.`,f.USAGE);s.push(o.value)}return s}function yn(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function wn(e){let t;try{t=pe(e,"Mutation document")}catch(n){let r=hn(e);if(r===null)throw n;return{schema_version:1,mutations:r}}return Array.isArray(t)?{schema_version:1,mutations:t}:w(t)&&!yn(t)?{schema_version:1,mutations:[t]}:t}function gn(e,t){let n=Object.hasOwn(e,"op")?_n(e,t):Sn(e,t);if(n.op==="create"&&n.id===void 0&&w(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new u(`Mutation ${t+1} item id must be a string.`,f.USAGE);n.id=n.item.id}return n}function _n(e,t){for(let n of Object.keys(e))if(!gt.includes(n))throw $(`mutation ${t+1}`,n,gt);if(e.item!==void 0&&e.op!=="create")throw new u(`Mutation ${t+1} item documents are only valid for create operations.`,f.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new u(`Mutation ${t+1} must declare either item or options, not both.`,f.USAGE);return{...e}}function Sn(e,t){let{ref:n,id:r,item:i,...s}=e,o=i!==void 0?i:s;if(i!==void 0&&Object.keys(s).length>0)throw new u(`Mutation ${t+1} must not mix item document keys with top-level fields.`,f.USAGE);if(!w(o))throw new u(`Mutation ${t+1} item document must be an object.`,f.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...r===void 0?{}:{id:r},item:o}}function En(e){let t=wn(e);if(!w(t))throw new u("Mutation document must be a JSON array or object.",f.USAGE);for(let n of Object.keys(t))if(!St.includes(n))throw $("mutation document",n,St);if(t.schema_version!==void 0&&t.schema_version!==1)throw new u("Mutation document schema_version must be 1.",f.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new u("Mutation document requires a non-empty mutations array.",f.USAGE);return t.mutations.map((n,r)=>{if(!w(n))throw new u(`Mutation ${r+1} must be an object.`,f.USAGE);return gn(n,r)})}function On(e,t,n){let r=new Set(Object.values(Ft(t,n,Object.create(null))));for(let i of t)i.op==="create"&&typeof i.id=="string"&&i.id.trim().length>0&&r.add(x(i.id,n.idPrefix));return{...e,existing:e.existing.filter(i=>!r.has(i.id))}}function bn(e){let t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(let[n,r]of e.entries()){if(r.op!=="create"||r.ref!==void 0||typeof r.id=="string"&&r.id.trim().length>0)continue;let i=`${_t}${n+1}`;if(t.has(i))throw new u(`Mutation ${n+1} receives the synthesized ref "${i}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${_t}<n> aliases are reserved for rows without one.`,f.USAGE);r.ref=i}}function Nt(e,t,n){let r=Gn(JSON.stringify(e),t,{},n);return delete r.stdinJson,delete r.documentAnnotationSnapshot,r}function jt(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>v(n))}function vn(e,t){for(let n of e)w(n.item)&&(n.options=Nt(n.item,"create",t),delete n.item)}function Ut(e,t){return t.some(n=>n.metadata_key===e)?e:wt(e)}function ue(e,t,n){let r=t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase());if(w(e.item)){if(e.item[t]!==void 0)return e.item[t];if(Ut(r,n)===t&&e.item[r]!==void 0)return e.item[r]}let i=w(e.options)?e.options:{},s=n.find(d=>d.metadata_key===t);return s!==void 0&&i[v(s)]!==void 0?i[v(s)]:i[t]!==void 0?i[t]:i[r]!==void 0?i[r]:(Array.isArray(i.field)?i.field:[]).map(String).find(d=>d.startsWith(`${t}=`))?.slice(t.length+1)}function An(e,t){return e<t?-1:+(e!==t)}function fe(e){return Array.isArray(e)?e.map(fe):w(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>An(t,n)).map(([t,n])=>[t,fe(n)])):e}function S(e){return typeof e=="string"?e.trim():JSON.stringify(fe(e))}function $n(e,t,n,r,i){let s=t.key.trim();if(s.length===0)throw new u("Upsert key must be a non-empty field name.",f.USAGE);let o=Tn(t.existing),a=new Map,d=new Set;for(let[c,p]of e.entries()){if(p.op!=="create")continue;let l=kn(p,s,c,a,r),y=Rn(o.get(l)??[],s,l);if(y===void 0){p.unique={key:s,value:ue(p,s,r)};continue}let h=x(y,n);typeof p.ref=="string"&&(i[p.ref]=h),In(p,h,r,{key:s,value:ue(p,s,r)}),d.add(c)}return d}function Tn(e){let t=new Map;for(let n of e){if(n.value===void 0||n.value===null)continue;let r=S(n.value);t.set(r,[...t.get(r)??[],n.id])}return t}function kn(e,t,n,r,i){let s=ue(e,t,i);if(s==null||s==="")throw new u(`Mutation ${n+1} is missing the upsert key "${t}".`,f.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${t}" value when --upsert-key ${t} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});let o=S(s),a=r.get(o);if(a!==void 0)throw new u(`Mutations ${a+1} and ${n+1} share the upsert key value ${JSON.stringify(o)} for "${t}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return r.set(o,n),o}function Rn(e,t,n){if(e.length>1)throw new u(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,f.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return e[0]}function In(e,t,n,r){let i=new Set([...Mt.update,...jt("update",n)]),s=w(e.item)?Nt(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([o])=>i.has(o)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=s,e.match=r}function Ft(e,t,n){for(let[r,i]of e.entries())if(i.ref!==void 0){if(i.op!=="create")throw new u(`Mutation ${r+1} ref is only valid for create operations.`,f.USAGE);if(typeof i.ref!="string"||!Et.test(i.ref))throw new u(`Mutation ${r+1} ref must match ${Et.source}.`,f.USAGE);if(n[i.ref]!==void 0)throw new u(`Duplicate mutation ref "${i.ref}".`,f.USAGE);n[i.ref]=typeof i.id=="string"&&i.id.trim().length>0?x(i.id,t.idPrefix):pn(t.transactionId,i.ref,t.idPrefix)}return n}function Gr(e,t){let n=En(e);bn(n);let r=n.map(p=>typeof p.ref=="string"?p.ref:void 0),i=Object.create(null),s=t.upsert===void 0?new Set:$n(n,On(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],i);vn(n,t.runtimeFields??[]),Ft(n,t,i),mn(n,r);let o=n.map(p=>{let l={...p},y=typeof l.ref=="string"?l.ref:void 0;if(delete l.ref,y!==void 0?l.id=i[y]:l.id=vt(l.id,i),w(l.options)){let h={...l.options};for(let g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=vt(h[g],i));Array.isArray(h.dep)?h.dep=h.dep.map(g=>At(g,i)):h.dep!==void 0&&(h.dep=At(h.dep,i)),l.options=h}return l}),a=Ct(JSON.stringify(o),{runtimeFields:t.runtimeFields??[]}),d=a.filter(p=>p.op==="create").map(p=>p.id);if(new Set(d).size!==d.length)throw new u("Duplicate resolved create id in mutation document.",f.USAGE);let c=a.map((p,l)=>{let y=r[l];return{index:l,...typeof y=="string"?{ref:y}:{},id:p.id,op:p.op,...s.has(l)?{upserted:!0}:{}}});return{schema_version:1,mutations:a,references:i,rows:c}}function Mn(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{let r=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(r)?JSON.stringify(r):r}`}).join(",")}function Cn(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(w))throw new u(`${n} must be an array of objects.`,f.USAGE);return e.map(r=>Mn(r,t))}}function Nn(e,t){return e==="tags"&&Array.isArray(t)&&t.every(n=>typeof n=="string")?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"?String(t):t}function $t(e,t,n=!1){for(let[r,i,s]of ct){let o=t[r],a=Cn(n&&["comments","notes","learnings"].includes(r)&&Array.isArray(o)?o.filter(d=>!w(d)||d.created_at===void 0):o,s,r);a!==void 0&&a.length>0&&(e[i]=a)}}function jn(e,t){for(let n of Object.keys(e)){if(t){if(!K.includes(n))throw $("item envelope",n,K);continue}if(!A.has(n)&&L(n,[...A])===void 0&&L(n,K)==="item")throw $("item envelope",n,K)}}function Un(e){let t=Object.hasOwn(e,"item");jn(e,t);let n=t?e.item:e;if(!w(n))throw new u("Item document item must be an object.",f.USAGE);return{item:n,...t&&w(e.linked)?{linked:e.linked}:{}}}function Fn(e,t,n,r,i,s){if((r==="update"?cn:It).has(t))return;let a=i.find(d=>d.metadata_key===t&&d.commands.includes(r));if(a!==void 0){let d=ne(s,a);e[v(a)]=d!==void 0?d:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!A.has(t)){if(L(t,[...A])!==void 0)throw $("item document",t,[...A]);let c=Array.isArray(e.field)?e.field:[];c.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=c;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase())]=Nn(t,n))}function xn(e){return{command_to_fields:new Map([["create",e.filter(t=>t.commands.includes("create"))]])}}function Dn(e,t,n,r){let i=r.filter(c=>c.commands.includes("create")),s=new Set([...De.filter(c=>t.has(c.option)).map(c=>c.field),...i.filter(c=>t.has(v(c))).map(c=>c.metadata_key),...at(Array.isArray(n)?n.map(String):[],xn(i)).metadataKeys]),o=(Array.isArray(e)?e:[]).filter(w).filter(c=>typeof c.field=="string"&&!s.has(c.field));if(o.length===0)return{};let a=o.map(c=>typeof c.reason=="string"?c.reason.trim():""),d=o.map(c=>c.field);return t.has("deferReason")?{defer:d}:a.every(c=>c.length>0)?{defer:d,deferReason:[...new Set(a)].join("; ")}:{defer:d}}function Pn(e,t,n){let r=new Set(Object.entries(e).filter(([,s])=>s!==void 0).map(([s])=>s)),i=t==="create"?z:G;for(let{target:s,keys:o}of i)o.some(a=>r.has(a))&&r.add(s);for(let s of n.filter(o=>o.commands.includes(t)))ne(e,s)!==void 0&&r.add(v(s));return r}function zn(e,t,n){let r=t==="create"?z:G;for(let{target:i}of r)i!=="field"&&n.has(i)&&delete e[i]}function Gn(e,t,n={},r=[]){let i=pe(e,"Item document");if(!w(i))throw new u("Item document must be a JSON object.",f.USAGE);let{item:s,linked:o}=Un(i),a={};for(let[l,y]of Object.entries(s)){let h=Ut(l,r);h!==l&&Object.hasOwn(s,h)||Fn(a,h,y,t,r,n)}$t(a,s,t==="update"),o!==void 0&&$t(a,o);let d=Pn(n,t,r);if(zn(a,t,d),t==="create"&&!d.has("defer")&&Object.assign(a,Dn(s.deferred_fields,d,n.unset,r)),t==="update"){let l=Object.fromEntries(["comments","notes","learnings"].filter(y=>Object.hasOwn(s,y)&&!d.has(y.slice(0,-1))).map(y=>[y,s[y].filter(h=>w(h)&&h.created_at!==void 0)]));Object.keys(l).length>0&&(a.documentAnnotationSnapshot=l)}let c={...a,...Object.fromEntries(Object.entries(n).filter(([,l])=>l!==void 0)),...Array.isArray(a.field)&&Array.isArray(n.field)?{field:[...a.field,...n.field]}:{},stdinJson:void 0},p=Object.keys(a).filter(l=>!d.has(l));return Me(Re(c,p),p)}function qr(e){return Ct(JSON.stringify(e))}var qn=["id","updated_at","pm_format_version","type"],Kn="import";function xt(e,t){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e)||e in Object.prototype)throw new TypeError(`${t} names an invalid field ${JSON.stringify(e)}; use a front-matter field name of letters, digits and underscores`);if(qn.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function J(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Ln=["__proto__","constructor","prototype"];function Dt(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function N(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(N):Dt(e)?Object.entries(e).every(([t,n])=>!Ln.includes(t)&&N(n)):!1}function le(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!Dt(n))throw new TypeError(`${t} set must be a plain object of front-matter fields`);if(r!==void 0&&!Array.isArray(r))throw new TypeError(`${t} unset must be an array of front-matter field names`);let i=Object.keys(n??{}),s=r??[];if(i.length+s.length===0)throw new TypeError(`${t} requires at least one field in set or unset`);for(let o of i)if(xt(o,t),n[o]===null||!N(n[o]))throw new TypeError(`${t} set "${o}" must be a non-null JSON value (no undefined, non-finite number, sparse array, class instance, or __proto__/constructor/prototype key); remove a field with unset`);for(let o of s){if(xt(o,t),o==="body"||o==="front_matter")throw new TypeError(`${t} cannot unset "${o}"; the item format reserves that name`);if(i.includes(o))throw new TypeError(`${t} both sets and unsets "${o}"`)}if(new Set(s).size!==s.length)throw new TypeError(`${t} unset repeats a field`)}async function Pt(e){le(e,`Finalization of ${e.id}`);let t=await D(e.pmRoot),n={schema:t.schema,extensionFieldNames:Je(C())},r=await Qe({pmRoot:e.pmRoot,settings:t,id:e.id,op:Kn,author:e.author,message:e.message,force:e.force===!0,extensionFieldNames:n.extensionFieldNames,mutate:i=>{let s=structuredClone(i.metadata),o=i.metadata;for(let[c,p]of Object.entries(e.set??{}))o[c]=structuredClone(p);for(let c of e.unset??[])delete o[c];let a;try{Pe(i.metadata);let c=re(i,n),p=re(ze(Ge(c,n),n),n);if(b(p)!==b(c))throw new TypeError("the stored item reads back as a different document; a set field collides with a name the item format reserves");a=c.metadata;let l=Object.entries(e.set??{}).find(([y,h])=>J(a[y])!==J(h));if(l!==void 0)throw new TypeError(`set "${l[0]}" is not stored as declared (${J(l[1])} normalizes to ${a[l[0]]===void 0?"an absent field":J(a[l[0]])})`)}catch(c){throw new u(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,f.USAGE,{code:"finalization_invalid_document",item_id:e.id,required:"Declare set and unset fields that leave a valid item under the workspace schema, with each set value in the shape its field stores.",why:"A finalization writes front-matter fields exactly, so the patched document is read back through the item reader, and each declared value is checked against what would be stored, before anything is written.",nextSteps:[`Run pm get ${e.id} --json to compare the current fields with the finalization, then correct the patch and retry the transaction.`]})}return{changedFields:[...new Set([...Object.keys(s),...Object.keys(a)])].filter(c=>Object.hasOwn(s,c)!==Object.hasOwn(a,c)||b(s[c])!==b(a[c])).sort((c,p)=>c.localeCompare(p))}}});return{item:r.item,changedFields:r.changedFields}}async function Hn(e,t){if(!Ze(e))return{schema:te(t.schema),typeDefinitionsFromFile:[]};let n=await fr(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Zn(e,t,n,r){let i=ee({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},C());return(await Xe(e,t.item_format,i.type_to_folder,void 0,n.schema)).flatMap(o=>{let a=o[r];return a==null?[]:[{id:o.id,value:a}]})}function Se(e){let t=new Map,n=async r=>{let i=await D(e),s=await Hn(e,i),o=new Map;for(let a of await Zn(e,i,s,r)){let d=S(a.value);o.set(d,[...o.get(d)??[],a.id])}return o};return{lookup(r){let i=t.get(r)??n(r);return t.set(r,i),i},async recordCreate(r){for(let[i,s]of t){let o=r[i];if(o==null)continue;let a=await s,d=S(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function Xn(e,t){let n=S(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new u(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,f.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function Vt(e,t,n){let r=e.metadata[n.key],i=S(n.value);if(S(r)!==i)throw new u(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,f.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function zt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.key=="string"&&t.key.trim().length>0&&t.value!==void 0&&t.value!==null}function Y(e,t){let n={...e,...t};return e===void 0?n:X(e,n)}async function E(e,t){try{let r=(await ae(t,{},{pmRoot:e})).item;return{id:r.id,closedAt:r.closed_at,updatedAt:r.updated_at,assignee:r.assignee,claimPrincipal:r.claim_principal}}catch(n){if(n instanceof u&&n.exitCode===f.NOT_FOUND)return;throw n}}function Ee(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=ge.createHash("sha256").update(b(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Qn(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function _(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function Oe(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function k(e,t,n,r){let i=await U(m.join(e,"history",`${t}.jsonl`),t),s=_(n,r,"apply"),o=_(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(Oe(d,s))return!0;if(d===o)return!1}return!1}async function H(e,t){let n=await E(e,t.id);if(n?.updatedAt===void 0)throw new u(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,f.NOT_FOUND);let r=await U(m.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new u(`Bulk ${t.op} target ${t.id} has no restorable history`,f.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(ie(r)+r.length),target_history_hash:F(r),target_history_length:r.length}}function T(e,t,n){return new u(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,f.CONFLICT,{code:"transaction_partial_mutation",item_id:t,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${t} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function Yt(e,t){let n=`bulk-item-transaction ${t} `;return[e.message,e.context?.item_transaction_step].some(r=>typeof r=="string"&&r.startsWith(n))}function er(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(F(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||F(e.slice(0,i))!==r||s!==String(ie(e)+i))throw T(n,n.itemId,n.stepId);let o=_(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=y=>Oe(y.message,o)||y.context?.item_transaction_step===o,c=_(n.transactionId,n.stepId,"compensate");if(a.filter(y=>d(y)||y.message===c).at(-1)?.message===c)return!1;let p=a.filter(d);if(p.length===0)return!1;let l=e.at(-1).after_hash===p.at(-1).after_hash&&a.every(y=>Yt(y,n.transactionId));if(p.length!==a.length&&!l)throw T(n,n.itemId,n.stepId);return!0}async function Ht(e,t){let n=m.join(e,"history",`${t}.jsonl`),r=await Ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=Jn(n).equals(r.raw_bytes)&&Le(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function j(e,t,n,r){let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;if(i===void 0||typeof i.target_updated_at!="string")return;let s=i.target_updated_at,o=await E(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await Ht(e.pmRoot,o.id),c=i.target_history_hash,p=typeof c=="string";if(typeof c=="string"){if(!er(a,{expectedHistory:c,length:i.target_history_length,version:i.target_version},{...e,itemId:o.id,stepId:n}))return}else{if(o.updatedAt===s)return;if(!await k(e.pmRoot,o.id,e.transactionId,n))throw T(e,o.id,n)}let l=()=>mt(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:_(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await M({pmRoot:e.pmRoot,id:o.id,validate:y=>{d(y,()=>T(e,o.id,n))},compensation:Xt(e,t,n,"restore",p)},l)}var Zt=new WeakMap;function Xt(e,t,n,r,i){let s=i?nt(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:Zt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function Qt(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await U(m.join(e.pmRoot,"history",`${r.id}.jsonl`),r.id),s=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(i.filter(d=>d.op==="close").at(-1)?.patch.some(d=>d.op==="add"||d.op==="replace"?d.path==="/metadata/close_reason"&&d.value===s:!1)??!1)throw new u(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,f.CONFLICT,{code:"transaction_create_compensated",item_id:r.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${r.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:r.id,op:"create"}}},async apply(){t.unique!==void 0&&await Xn(e.uniqueIndex,t.unique);let r=await ut(Y(t.options,{author:e.author,id:t.id,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=r.item;return e.onCreateWarnings?.(String(i.id),r.warnings),await e.uniqueIndex.recordCreate(i),{id:String(i.id),op:"create"}},async compensate(){await tr(e,t.id,n)}}}async function tr(e,t,n){let r=await E(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await Ht(e.pmRoot,r.id),o=_(e.transactionId,n,"apply"),a=_(e.transactionId,n,"compensate"),d=i.filter(c=>Oe(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>Yt(c,e.transactionId)))throw T(e,r.id,n);await M({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>T(e,r.id,n))},compensation:Xt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await lt(t,c,{pmRoot:e.pmRoot}):await ce(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function nr(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let r=()=>ft(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await M({pmRoot:e.pmRoot,id:await en(e.pmRoot,t.id),validate:d=>{s!==void 0&&Vt(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:_(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await j(e,t.id,n,r)}}}async function en(e,t){return String((await ae(t,{},{pmRoot:e})).item.id)}function rr(e,t,n){let r=_(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await E(e.pmRoot,t.id);return i===void 0||!await k(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=await en(e.pmRoot,t.id),{match:s}=t;return await yt(e.pmRoot,()=>M({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&Vt(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>Pt({pmRoot:e.pmRoot,id:i,author:e.author,message:r,force:t.force,...t.set===void 0?{}:{set:t.set},...t.unset===void 0?{}:{unset:t.unset}}))),e.uniqueIndex.invalidate(),{id:i,op:t.op}},async compensate(i){await j(e,t.id,n,i)}}}function ir(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"close"}}:r.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"close"}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=(await ce(t.id,t.reason,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await j(e,t.id,n,r)}}}function or(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"release"}}:r.assignee!==void 0||r.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"release"}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=(await pt(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await j(e,t.id,n,r)}}}function be(e,t,n){let r=Ee(t,n),i=sr(e,t,r);return Zt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function sr(e,t,n){switch(t.op){case"create":return Qt(e,t,n);case"update":return nr(e,t,n);case"close":return ir(e,t,n);case"release":return or(e,t,n);case"finalize":return rr(e,t,n)}}function ar(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`Bulk mutation ${t+1} must be an object`);if(!["create","update","close","release","finalize"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, release, or finalize`);if(typeof e.id!="string"||e.id.trim().length===0)throw new TypeError(`Bulk mutation ${t+1} requires a non-empty id`);if(e.op==="close"&&(typeof e.reason!="string"||e.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${t+1} requires a non-empty reason`);if(cr(e,t),e.op==="finalize"){dr(e,t);return}q(e.options,e.op,t)}function cr(e,t){if(e.op==="create"&&e.unique!==void 0&&!zt(e.unique))throw new TypeError(`Bulk create mutation ${t+1} unique must be an object with a non-empty key and a value`);if((e.op==="update"||e.op==="finalize")&&e.match!==void 0&&!zt(e.match))throw new TypeError(`Bulk ${e.op} mutation ${t+1} match must be an object with a non-empty key and a value`)}var Gt=["op","id","set","unset","match","force"];function dr(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!Gt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${Gt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!N(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);le(e,n)}function we(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,r]of e.entries()){if(ar(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=S(s),d=o.get(a);if(d!==void 0)throw new u(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});o.set(a,n),t.set(i,o)}}function tn(e){let t=[...e];we(t);let n=t.map(r=>{let i=structuredClone(r);return r.op!=="finalize"&&i.op!=="finalize"&&r.options!==void 0&&i.options!==void 0&&X(r.options,i.options),i});return we(n),n}function nn(e,t=""){return e===null||typeof e!="object"?[]:Object.entries(e).flatMap(([n,r])=>{let i=`${t}/${n.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(n)?[i]:nn(r,i)})}async function he(e,t,n){try{return await n()}catch(r){throw r instanceof u?new u(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function rn(e,t,n,r){let i=m.relative(e,t),s=i.split(m.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))?!1:["locks","runtime","search"].includes(i.split(m.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))}async function B(e,t){let n=await qt(t);if(n.isSymbolicLink())await _e(t);else if(n.isDirectory()||n.isFile())return n;throw I(m.relative(e,t))}async function ur(e,t){let n=await Vn(t,me.O_RDONLY|me.O_NOFOLLOW|me.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw I(m.relative(e,t));let i=ge.createHash("sha256");if(r.size>0)for await(let s of n.createReadStream({highWaterMark:64*1024,end:r.size-1,autoClose:!1}))i.update(s);return i.digest()}finally{await n.close()}}async function ye(e,t,n){let r=ge.createHash("sha256");async function i(s){for(let o of(await Yn(s)).sort()){let a=m.join(s,o);rn(e,a,t,n)&&((await B(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(m.relative(e,a))),r.update(await ur(e,a))))}}return await i(e),r.digest("hex")}function W(){return new u("Tracker changed while preparing the transaction preview; retry against stable state.",f.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ve(e){if(!Q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=m.resolve(t),r=n;for(;;)try{let i=await qt(r);return r!==n&&i.isDirectory()}catch(i){if(!Q(i))return!1;let s=m.dirname(r);if(s===r)return!1;r=s}}async function V(e,t){let n=m.join(e,t);try{let r=e;for(let i of t.split(m.sep).slice(0,-1))r=m.join(r,i),await B(e,r);if(!(await B(e,n)).isFile())throw I(t);return await Ce(n,I(t))}catch(r){if(await ve(r))return;throw r}}async function on(e,t,n,r){let i=te(n);for(let[s,o]of Object.entries(i.files)){let a=m.relative(e,Fe(e,o,Ue[s]));if(a===""||!m.resolve(e,a).startsWith(m.join(e,m.sep)))throw new u("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",f.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await V(e,a);if(r?.set(a,d),d!==void 0){let c=m.join(t,a);await Bn(m.dirname(c),{recursive:!0}),await Wt(c,d)}}return xe(t,i)}async function fr(e,t){await _e(e);let n=await Kt(m.join(Bt(),"pm-schema-plan-"));try{let r=await Lt(e);return await on(r,m.join(n,"configuration"),t)}catch(r){throw await ve(r)?W():r}finally{await Jt(n,{recursive:!0,force:!0})}}async function pr(e,t,n){let r=new Map,i=await V(e,R);r.set(R,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=He(s),a=o.success?o.data:void 0,d=await on(e,t,a?.schema,r),c=d.schema,p=m.relative(e,qe(e));r.set(p,await V(e,p));let l=ee({...ke,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),y=Ne(e)===e?[...Te.filter(Boolean),R,tt,"transactions",...l.folders,...r.keys()].map(g=>m.normalize(g)):void 0,h=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:y,stagedSettings:h,registryFolders:l.folders}}async function lr(e,t,n){await _e(e);try{let r=await Lt(e),i=await pr(r,m.join(m.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>m.normalize(c)),o=await ye(r,i.ownedPaths,s);await Wn(r,t,{recursive:!0,dereference:!1,filter:async c=>rn(r,c,i.ownedPaths,s)?(await B(r,c),!0):!1});let[a,d]=await Promise.all([ye(r,i.ownedPaths,s),ye(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw W();for(let[c,p]of i.configuration)if(await V(t,c)!==p)throw W();i.stagedSettings!==void 0&&await Wt(m.join(t,R),i.stagedSettings)}catch(r){throw await ve(r)?W():r}}async function Mi(e){let t=P(e),n=tn(e.mutations),r=C(),i=Ve(),s=await Kt(m.join(Bt(),"pm-transaction-preview-")),o=m.join(s,"tracker");try{await lr(t.pmRoot,o,r);let a=!1,d=[],c=[],p=new Set;return await Be(i,()=>ht({path:o,noExtensions:!0},async()=>{We(r);let l={...t,pmRoot:o,createCompensation:"close",uniqueIndex:Se(o)},y=n.map((h,g)=>{let O=be({...l,onCreateWarnings:(Z,Ae)=>{Ae.length>0&&d.push({index:g,id:Z,op:"create",warnings:Ae})}},h,g);return{...O,inspect:()=>he(h,g,()=>O.inspect()),prepareCompensation:()=>he(h,g,async()=>O.prepareCompensation?.()),apply:()=>he(h,g,async()=>{let Z=await O.apply();return p.add(g),Z})}});if(await oe({...t,pmRoot:o,steps:y,onTransition:({transition:h})=>{h==="committed"&&(a=!0)}}),a)for(let[h,g]of n.entries()){let O=(await dt(g.id,{path:o},{full:!0})).item;c.push({index:h,id:String(O.id),op:g.op,execution:p.has(h)?"applied":"adopted",item:O,commit_time_fields:nn(O)})}})),{records:c,validated:a,state:a?"staged_snapshot":"replayed_committed_plan",warnings:d,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await Jt(s,{recursive:!0,force:!0})}}async function mr(e){let t=P(e),n=tn(e.mutations),r=e.createCompensation??"close";if(!["close","delete"].includes(r))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={...t,createCompensation:r,uniqueIndex:Se(t.pmRoot)},s=await oe({...t,steps:n.map((a,d)=>be(i,a,d)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations:n,createCompensation:r})),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}}),o={};for(let[a,d]of n.entries()){let c=Ee(d,a),p=s.results[c];o[Qn(d,a)]=p}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function hr(e){let t=[];return e.evidence!==void 0&&Object.keys(e.evidence).length>0&&t.push({op:"update",id:e.id,options:e.evidence}),t.push({op:"close",id:e.id,reason:e.reason,...e.closeOptions===void 0?{}:{options:e.closeOptions}},{op:"release",id:e.id,...e.releaseOptions===void 0?{}:{options:e.releaseOptions}}),t}function Ci(e){return mr({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:hr(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Ni={buildCreateStep:Qt,bulkHistoryMarker:_,compensateByRestore:j,deriveStepId:Ee,isUpdateMarkerApplied:k,readItemSnapshot:E};async function ji(e,t){let n=await rt(e,t);return n===void 0?void 0:{journal:n,planDigest:se(n)}}function yr(e,t){let n=t.recoveryData;if(n===null||typeof n!="object"||Array.isArray(n)||n.kind!=="item-mutations-v1"||!Array.isArray(n.mutations)||!["close","delete"].includes(String(n.createCompensation)))throw new u("Transaction has no supported item recovery plan",f.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});let r=n.mutations;we(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:Se(e.pmRoot)};return r.map((s,o)=>be(i,s,o))}async function Ui(e){let t=P(e),n=await it({...e,...t,resolveSteps:r=>yr({...e,...t},r)});return{journal:n,planDigest:se(n)}}export{wt as a,Pr as b,zr as c,Ct as d,S as e,Gr as f,Gn as g,qr as h,Hn as i,Zn as j,fr as k,Mi as l,mr as m,hr as n,Ci as o,Ni as p,ji as q,Ui as r};
2
- //# sourceMappingURL=chunk-FECZV72T.js.map
1
+ import{$a as ae,Ub as ut,Vb as ft,Xb as ce,_b as pt,a as rt,ac as lt,bc as mt,xc as ht,yc as yt}from"./chunk-OKEJ4U2I.js";import{u as dt}from"./chunk-SY5C3U32.js";import{Xb as ct}from"./chunk-U7RBJGLF.js";import{m as at}from"./chunk-L2ZSSMYY.js";import{a as it,c as P,d as oe,e as ot,f as se,g as st}from"./chunk-4YQMQOUO.js";import{j as z,m as G}from"./chunk-C6WM6ZN4.js";import{Ra as ie,d as Re,ea as Ye,ga as x,qb as Xe,qc as et,t as Ie,u as Me,v as X,wb as Qe}from"./chunk-CBUC4X7Q.js";import{m as Ze,u as D}from"./chunk-OXC5KBIQ.js";import{b as He}from"./chunk-3AZOATC2.js";import{Ha as De,Jb as Ke,Ma as Pe,Nb as U,Ua as ze,Va as Ge,Wa as re,Wg as We,Xg as C,Ze as F,cg as Je,df as Le,hb as qe,hh as Be,ih as Ve,ja as je,jf as M}from"./chunk-NRQCBUYD.js";import{g as ee,p as Ne}from"./chunk-GSLOAEY2.js";import{Aa as tt,Ga as nt}from"./chunk-A5ZEMOVR.js";import{a as b,da as ne}from"./chunk-I4SPJQQI.js";import{P as Ue,V as te,Z as Fe,aa as xe,ea as v}from"./chunk-TE6FBDHP.js";import{A as f,C as u,G as Q,J as Ce,K as I,l as $e,q as R,t as Te,y as ke}from"./chunk-K672XXGQ.js";import ge from"node:crypto";import{constants as me,readFileSync as Jn}from"node:fs";import{cp as Wn,lstat as qt,mkdir as Bn,mkdtemp as Kt,open as Vn,readdir as Yn,realpath as Lt,rm as Jt,stat as _e,writeFile as Wt}from"node:fs/promises";import{tmpdir as Bt}from"node:os";import m from"node:path";import Tt from"node:crypto";var A=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...$e,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);function wt(e){if(e===void 0)return;let t=e.replace(/[A-Z]/gu,n=>`_${n.toLowerCase()}`);return A.has(t)?t:e}function q(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new u(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,f.USAGE,{code:"mutation_option_value_invalid",required:'Pass estimatedMinutes as a string, for example "45", in raw mutation options.',why:"Raw options use the create/update command option types; item documents accept numeric estimated_minutes instead.",nextSteps:["Quote the estimatedMinutes value or use an item document with numeric estimated_minutes, then retry the transaction."]})}var de=["op","id","reason","options","unique","match"],sn=[...de,"ref"],gt=[...sn,"item"],an="mutate-",_t="row-",St=["schema_version","mutations"],kt="[a-z][a-z0-9._-]{0,63}",Et=new RegExp(`^${kt}$`,"u"),Rt=new RegExp(`(^|,)id=@(${kt})(?=,|$)`,"gu"),Ot=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase()),K=["item","item_hash","linked","schedule","claim_state","children","omission_receipt","row_contract","context_intent"],It=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),cn=new Set([...It,"completed_at","id"]),Mt={create:z.map(e=>e.target),update:G.map(e=>e.target),close:tt.map(e=>Ot(e.flag)).filter(e=>e!=="reason"),release:nt.map(e=>Ot(e.flag))};function Pr(e){let t=Tt.createHash("sha256").update(e).digest("hex");return`${an}${t.slice(0,24)}`}function zr(e){let t={},n=e.createCompensation;if(n!==void 0){if(n!=="close"&&n!=="delete")throw new u("createCompensation must be close or delete.",f.USAGE);t.createCompensation=n}for(let r of["lockTtlSeconds","lockWaitMs"]){let i=e[r];if(i===void 0)continue;let s=typeof i=="number"||typeof i=="string"&&i.trim().length>0?Number(i):Number.NaN;if(!Number.isSafeInteger(s)||s<=0)throw new u(`${r} must be a positive safe integer.`,f.USAGE);t[r]=s}return t}function w(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function L(e,t){let n=Math.max(1,Math.min(3,Math.floor(e.length/4)+1)),r;for(let i of t){let s=je(e,i,n);s!==null&&(r===void 0||s<r.distance)&&(r={key:i,distance:s})}return r?.key}function $(e,t,n){let r=L(t,n);return new u(r===void 0?`${e} does not recognize key "${t}". Allowed keys: ${n.join(", ")}.`:`${e} does not recognize key "${t}". Did you mean "${r}"?`,f.USAGE,{code:"stdin_json_unknown_key",required:`Use documented ${e} keys only.`,why:"Strict structured input prevents silent typos from creating incomplete or unintended mutations.",nextSteps:[r===void 0?`Remove or correct "${t}".`:`Replace "${t}" with "${r}".`]})}function pe(e,t){try{return JSON.parse(e)}catch(n){let r=n instanceof Error?n.message:String(n);throw new u(`${t} must be valid JSON: ${r}`,f.USAGE,{code:"stdin_json_invalid",required:`Pipe one valid JSON ${t.toLowerCase()} into stdin.`,why:"Structured mutation input must parse deterministically before any tracker write begins."})}}function dn(e,t){if(!w(e))throw new u(`Mutation ${t+1} must be an object.`,f.USAGE);for(let n of Object.keys(e))if(!de.includes(n))throw $(`mutation ${t+1}`,n,de);return e}function un(e,t,n,r){if(e===void 0)return;if(!w(e))throw new u(`Mutation ${n+1} options must be an object.`,f.USAGE);let i=[...Mt[t],...jt(t,r)];for(let s of Object.keys(e))if(!i.includes(s))throw $(`mutation ${n+1} ${t} options`,s,i);return q(e,t,n),e}function bt(e,t,n,r){if(e===void 0)return;let i=r==="unique"?"create":"update";if(t!==i)throw new u(`Mutation ${n+1} ${r} is only valid for ${i} operations.`,f.USAGE);let s=w(e)&&typeof e.key=="string"?e.key.trim():"";if(!w(e)||s.length===0||e.value===void 0||e.value===null)throw new u(`Mutation ${n+1} ${r} must be an object with a non-empty key and a value.`,f.USAGE);return{key:s,value:e.value}}function fn(e,t,n){let r=dn(e,t),{op:i,id:s,reason:o}=r;if(i!=="create"&&i!=="update"&&i!=="close"&&i!=="release")throw new u(`Mutation ${t+1} op must be create, update, close, or release.`,f.USAGE);let a=un(r.options,i,t,n),d=bt(r.unique,i,t,"unique"),c=bt(r.match,i,t,"match");if(typeof s!="string"||s.trim().length===0)throw new u(`Mutation ${t+1} requires a non-empty id.`,f.USAGE);let p=s.trim();if(i==="close"){if(typeof o!="string"||o.trim().length===0)throw new u(`Mutation ${t+1} close requires a non-empty reason.`,f.USAGE);return{op:i,id:p,reason:o.trim(),...a===void 0?{}:{options:a}}}if(i==="release")return{op:i,id:p,...a===void 0?{}:{options:a}};if(!w(a))throw new u(`Mutation ${t+1} ${i} requires an options object.`,f.USAGE);return{op:i,id:p,options:a,...d===void 0?{}:{unique:d},...c===void 0?{}:{match:c}}}function Ct(e,t={}){let n=pe(e,"Mutation batch"),r=Array.isArray(n)?n:w(n)&&Array.isArray(n.mutations)?n.mutations:void 0;if(r===void 0||r.length===0)throw new u("Mutation batch must be a non-empty JSON array or an object with a non-empty mutations array.",f.USAGE);let i=t.runtimeFields??[];return r.map((s,o)=>{let a=fn(s,o,i);return a.options!==void 0&&Ie(a.options),a})}function pn(e,t,n){let r=Tt.createHash("sha256").update(e).update("\0").update(t).digest("hex"),i=BigInt(`0x${r.slice(0,16)}`).toString(36).padStart(13,"0").slice(-12);return`${Ye(n)}${i}`}function vt(e,t){if(typeof e!="string"||!e.startsWith("@"))return e;let n=e.slice(1),r=t[n];if(r===void 0)throw new u(`Unknown mutation reference "${e}".`,f.USAGE);return r}function At(e,t){if(typeof e!="string")return e;let n=e.replace(Rt,(r,i,s)=>{let o=t[s];if(o===void 0)throw new u(`Unknown mutation reference "@${s}".`,f.USAGE);return`${i}id=${o}`});if(/(^|,)id=@/u.test(n))throw new u(`Malformed mutation reference in dependency "${e}".`,f.USAGE);return n}function ln(e){return typeof e!="string"?[]:e.startsWith("@")?[e.slice(1)]:[...e.matchAll(Rt)].map(t=>t[1]).filter(t=>t!==void 0)}function mn(e,t){let n=new Map;for(let[o,a]of e.entries()){let d=t[o];if(d===void 0)continue;let c=w(a.options)?a.options:{},p=Array.isArray(c.dep)?c.dep:c.dep===void 0?[]:[c.dep];n.set(d,[c.parent,c.blockedBy,...p].flatMap(ln))}let r=new Set,i=new Set,s=o=>{if(r.has(o))throw new u(`Mutation reference cycle includes "@${o}".`,f.USAGE);if(!i.has(o)){r.add(o);for(let a of n.get(o))n.has(a)&&s(a);r.delete(o),i.add(o)}};for(let o of n.keys())s(o)}function hn(e){let n=e.split(/\r?\n/u).map((o,a)=>({line:o.trim(),number:a+1})).filter(o=>o.line.length>0);if(n.length<2)return null;let r=n.map(o=>{try{return{...o,ok:!0,value:JSON.parse(o.line)}}catch(a){return{...o,ok:!1,error:a}}}),i=r[0];if(!i.ok&&(i.line.startsWith("[")||i.line==="{"||r.at(-1).line==="}")||!r.some(o=>o.ok&&w(o.value)))return null;let s=[];for(let o of r){if(!o.ok)throw new u(`Mutation document line ${o.number} must be one valid JSON object: ${et(o.error)}`,f.USAGE,{code:"stdin_json_invalid",required:"Provide one JSON object per line (JSON Lines), a JSON array, or a {schema_version, mutations} document.",why:"Structured mutation input must parse deterministically before any tracker write begins."});if(!w(o.value))throw new u(`Mutation document line ${o.number} must be a JSON object.`,f.USAGE);s.push(o.value)}return s}function yn(e){return Object.hasOwn(e,"mutations")||Object.hasOwn(e,"schema_version")}function wn(e){let t;try{t=pe(e,"Mutation document")}catch(n){let r=hn(e);if(r===null)throw n;return{schema_version:1,mutations:r}}return Array.isArray(t)?{schema_version:1,mutations:t}:w(t)&&!yn(t)?{schema_version:1,mutations:[t]}:t}function gn(e,t){let n=Object.hasOwn(e,"op")?_n(e,t):Sn(e,t);if(n.op==="create"&&n.id===void 0&&w(n.item)&&n.item.id!==void 0){if(typeof n.item.id!="string")throw new u(`Mutation ${t+1} item id must be a string.`,f.USAGE);n.id=n.item.id}return n}function _n(e,t){for(let n of Object.keys(e))if(!gt.includes(n))throw $(`mutation ${t+1}`,n,gt);if(e.item!==void 0&&e.op!=="create")throw new u(`Mutation ${t+1} item documents are only valid for create operations.`,f.USAGE);if(e.item!==void 0&&e.options!==void 0)throw new u(`Mutation ${t+1} must declare either item or options, not both.`,f.USAGE);return{...e}}function Sn(e,t){let{ref:n,id:r,item:i,...s}=e,o=i!==void 0?i:s;if(i!==void 0&&Object.keys(s).length>0)throw new u(`Mutation ${t+1} must not mix item document keys with top-level fields.`,f.USAGE);if(!w(o))throw new u(`Mutation ${t+1} item document must be an object.`,f.USAGE);return{op:"create",...n===void 0?{}:{ref:n},...r===void 0?{}:{id:r},item:o}}function En(e){let t=wn(e);if(!w(t))throw new u("Mutation document must be a JSON array or object.",f.USAGE);for(let n of Object.keys(t))if(!St.includes(n))throw $("mutation document",n,St);if(t.schema_version!==void 0&&t.schema_version!==1)throw new u("Mutation document schema_version must be 1.",f.USAGE);if(!Array.isArray(t.mutations)||t.mutations.length===0)throw new u("Mutation document requires a non-empty mutations array.",f.USAGE);return t.mutations.map((n,r)=>{if(!w(n))throw new u(`Mutation ${r+1} must be an object.`,f.USAGE);return gn(n,r)})}function On(e,t,n){let r=new Set(Object.values(Ft(t,n,Object.create(null))));for(let i of t)i.op==="create"&&typeof i.id=="string"&&i.id.trim().length>0&&r.add(x(i.id,n.idPrefix));return{...e,existing:e.existing.filter(i=>!r.has(i.id))}}function bn(e){let t=new Set(e.map(n=>n.ref).filter(n=>typeof n=="string"));for(let[n,r]of e.entries()){if(r.op!=="create"||r.ref!==void 0||typeof r.id=="string"&&r.id.trim().length>0)continue;let i=`${_t}${n+1}`;if(t.has(i))throw new u(`Mutation ${n+1} receives the synthesized ref "${i}", but another row declares that ref. Rename it or give mutation ${n+1} its own ref; ${_t}<n> aliases are reserved for rows without one.`,f.USAGE);r.ref=i}}function Nt(e,t,n){let r=Gn(JSON.stringify(e),t,{},n);return delete r.stdinJson,delete r.documentAnnotationSnapshot,r}function jt(e,t){return e!=="create"&&e!=="update"?[]:t.filter(n=>n.commands.includes(e)).map(n=>v(n))}function vn(e,t){for(let n of e)w(n.item)&&(n.options=Nt(n.item,"create",t),delete n.item)}function Ut(e,t){return t.some(n=>n.metadata_key===e)?e:wt(e)}function ue(e,t,n){let r=t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase());if(w(e.item)){if(e.item[t]!==void 0)return e.item[t];if(Ut(r,n)===t&&e.item[r]!==void 0)return e.item[r]}let i=w(e.options)?e.options:{},s=n.find(d=>d.metadata_key===t);return s!==void 0&&i[v(s)]!==void 0?i[v(s)]:i[t]!==void 0?i[t]:i[r]!==void 0?i[r]:(Array.isArray(i.field)?i.field:[]).map(String).find(d=>d.startsWith(`${t}=`))?.slice(t.length+1)}function An(e,t){return e<t?-1:+(e!==t)}function fe(e){return Array.isArray(e)?e.map(fe):w(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>An(t,n)).map(([t,n])=>[t,fe(n)])):e}function S(e){return typeof e=="string"?e.trim():JSON.stringify(fe(e))}function $n(e,t,n,r,i){let s=t.key.trim();if(s.length===0)throw new u("Upsert key must be a non-empty field name.",f.USAGE);let o=Tn(t.existing),a=new Map,d=new Set;for(let[c,p]of e.entries()){if(p.op!=="create")continue;let l=kn(p,s,c,a,r),y=Rn(o.get(l)??[],s,l);if(y===void 0){p.unique={key:s,value:ue(p,s,r)};continue}let h=x(y,n);typeof p.ref=="string"&&(i[p.ref]=h),In(p,h,r,{key:s,value:ue(p,s,r)}),d.add(c)}return d}function Tn(e){let t=new Map;for(let n of e){if(n.value===void 0||n.value===null)continue;let r=S(n.value);t.set(r,[...t.get(r)??[],n.id])}return t}function kn(e,t,n,r,i){let s=ue(e,t,i);if(s==null||s==="")throw new u(`Mutation ${n+1} is missing the upsert key "${t}".`,f.USAGE,{code:"upsert_key_missing",required:`Every create record must carry a non-empty "${t}" value when --upsert-key ${t} is set.`,why:"Keyed upsert identifies existing items by that field; a record without it cannot be matched or safely created."});let o=S(s),a=r.get(o);if(a!==void 0)throw new u(`Mutations ${a+1} and ${n+1} share the upsert key value ${JSON.stringify(o)} for "${t}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each record must carry a distinct upsert key value within one batch.",why:"Two records with the same key would race for the same existing item."});return r.set(o,n),o}function Rn(e,t,n){if(e.length>1)throw new u(`Upsert key "${t}" value ${JSON.stringify(n)} matches ${e.length} existing items: ${e.join(", ")}.`,f.CONFLICT,{code:"upsert_key_ambiguous",required:"Resolve the duplicate existing items or choose a key that is unique per item.",why:"An ambiguous key cannot select one item to update without guessing."});return e[0]}function In(e,t,n,r){let i=new Set([...Mt.update,...jt("update",n)]),s=w(e.item)?Nt(e.item,"update",n):Object.fromEntries(Object.entries(e.options).filter(([o])=>i.has(o)));delete e.item,delete e.ref,e.op="update",e.id=t,e.options=s,e.match=r}function Ft(e,t,n){for(let[r,i]of e.entries())if(i.ref!==void 0){if(i.op!=="create")throw new u(`Mutation ${r+1} ref is only valid for create operations.`,f.USAGE);if(typeof i.ref!="string"||!Et.test(i.ref))throw new u(`Mutation ${r+1} ref must match ${Et.source}.`,f.USAGE);if(n[i.ref]!==void 0)throw new u(`Duplicate mutation ref "${i.ref}".`,f.USAGE);n[i.ref]=typeof i.id=="string"&&i.id.trim().length>0?x(i.id,t.idPrefix):pn(t.transactionId,i.ref,t.idPrefix)}return n}function Gr(e,t){let n=En(e);bn(n);let r=n.map(p=>typeof p.ref=="string"?p.ref:void 0),i=Object.create(null),s=t.upsert===void 0?new Set:$n(n,On(t.upsert,n,t),t.idPrefix,t.runtimeFields??[],i);vn(n,t.runtimeFields??[]),Ft(n,t,i),mn(n,r);let o=n.map(p=>{let l={...p},y=typeof l.ref=="string"?l.ref:void 0;if(delete l.ref,y!==void 0?l.id=i[y]:l.id=vt(l.id,i),w(l.options)){let h={...l.options};for(let g of["parent","blockedBy"])h[g]!==void 0&&(h[g]=vt(h[g],i));Array.isArray(h.dep)?h.dep=h.dep.map(g=>At(g,i)):h.dep!==void 0&&(h.dep=At(h.dep,i)),l.options=h}return l}),a=Ct(JSON.stringify(o),{runtimeFields:t.runtimeFields??[]}),d=a.filter(p=>p.op==="create").map(p=>p.id);if(new Set(d).size!==d.length)throw new u("Duplicate resolved create id in mutation document.",f.USAGE);let c=a.map((p,l)=>{let y=r[l];return{index:l,...typeof y=="string"?{ref:y}:{},id:p.id,op:p.op,...s.has(l)?{upserted:!0}:{}}});return{schema_version:1,mutations:a,references:i,rows:c}}function Mn(e,t){return t.filter(n=>e[n]!==void 0&&e[n]!==null).map(n=>{let r=String(e[n]);return`${n}=${/[",\n\r\\]/u.test(r)?JSON.stringify(r):r}`}).join(",")}function Cn(e,t,n){if(e!==void 0){if(!Array.isArray(e)||!e.every(w))throw new u(`${n} must be an array of objects.`,f.USAGE);return e.map(r=>Mn(r,t))}}function Nn(e,t){return e==="tags"&&Array.isArray(t)&&t.every(n=>typeof n=="string")?JSON.stringify(t):typeof t=="number"||typeof t=="boolean"?String(t):t}function $t(e,t,n=!1){for(let[r,i,s]of ct){let o=t[r],a=Cn(n&&["comments","notes","learnings"].includes(r)&&Array.isArray(o)?o.filter(d=>!w(d)||d.created_at===void 0):o,s,r);a!==void 0&&a.length>0&&(e[i]=a)}}function jn(e,t){for(let n of Object.keys(e)){if(t){if(!K.includes(n))throw $("item envelope",n,K);continue}if(!A.has(n)&&L(n,[...A])===void 0&&L(n,K)==="item")throw $("item envelope",n,K)}}function Un(e){let t=Object.hasOwn(e,"item");jn(e,t);let n=t?e.item:e;if(!w(n))throw new u("Item document item must be an object.",f.USAGE);return{item:n,...t&&w(e.linked)?{linked:e.linked}:{}}}function Fn(e,t,n,r,i,s){if((r==="update"?cn:It).has(t))return;let a=i.find(d=>d.metadata_key===t&&d.commands.includes(r));if(a!==void 0){let d=ne(s,a);e[v(a)]=d!==void 0?d:a.type==="array"||a.type==="object"?JSON.stringify(n):n;return}if(!A.has(t)){if(L(t,[...A])!==void 0)throw $("item document",t,[...A]);let c=Array.isArray(e.field)?e.field:[];c.push(`${t}=${typeof n=="string"?n:JSON.stringify(n)}`),e.field=c;return}["dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"].includes(t)||(e[t.replaceAll(/_([a-z])/gu,(d,c)=>c.toUpperCase())]=Nn(t,n))}function xn(e){return{command_to_fields:new Map([["create",e.filter(t=>t.commands.includes("create"))]])}}function Dn(e,t,n,r){let i=r.filter(c=>c.commands.includes("create")),s=new Set([...De.filter(c=>t.has(c.option)).map(c=>c.field),...i.filter(c=>t.has(v(c))).map(c=>c.metadata_key),...at(Array.isArray(n)?n.map(String):[],xn(i)).metadataKeys]),o=(Array.isArray(e)?e:[]).filter(w).filter(c=>typeof c.field=="string"&&!s.has(c.field));if(o.length===0)return{};let a=o.map(c=>typeof c.reason=="string"?c.reason.trim():""),d=o.map(c=>c.field);return t.has("deferReason")?{defer:d}:a.every(c=>c.length>0)?{defer:d,deferReason:[...new Set(a)].join("; ")}:{defer:d}}function Pn(e,t,n){let r=new Set(Object.entries(e).filter(([,s])=>s!==void 0).map(([s])=>s)),i=t==="create"?z:G;for(let{target:s,keys:o}of i)o.some(a=>r.has(a))&&r.add(s);for(let s of n.filter(o=>o.commands.includes(t)))ne(e,s)!==void 0&&r.add(v(s));return r}function zn(e,t,n){let r=t==="create"?z:G;for(let{target:i}of r)i!=="field"&&n.has(i)&&delete e[i]}function Gn(e,t,n={},r=[]){let i=pe(e,"Item document");if(!w(i))throw new u("Item document must be a JSON object.",f.USAGE);let{item:s,linked:o}=Un(i),a={};for(let[l,y]of Object.entries(s)){let h=Ut(l,r);h!==l&&Object.hasOwn(s,h)||Fn(a,h,y,t,r,n)}$t(a,s,t==="update"),o!==void 0&&$t(a,o);let d=Pn(n,t,r);if(zn(a,t,d),t==="create"&&!d.has("defer")&&Object.assign(a,Dn(s.deferred_fields,d,n.unset,r)),t==="update"){let l=Object.fromEntries(["comments","notes","learnings"].filter(y=>Object.hasOwn(s,y)&&!d.has(y.slice(0,-1))).map(y=>[y,s[y].filter(h=>w(h)&&h.created_at!==void 0)]));Object.keys(l).length>0&&(a.documentAnnotationSnapshot=l)}let c={...a,...Object.fromEntries(Object.entries(n).filter(([,l])=>l!==void 0)),...Array.isArray(a.field)&&Array.isArray(n.field)?{field:[...a.field,...n.field]}:{},stdinJson:void 0},p=Object.keys(a).filter(l=>!d.has(l));return Me(Re(c,p),p)}function qr(e){return Ct(JSON.stringify(e))}var qn=["id","updated_at","pm_format_version","type"],Kn="import";function xt(e,t){if(typeof e!="string"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(e)||e in Object.prototype)throw new TypeError(`${t} names an invalid field ${JSON.stringify(e)}; use a front-matter field name of letters, digits and underscores`);if(qn.includes(e))throw new TypeError(`${t} cannot change "${e}"; the item writer derives it, or an update row owns it`)}function J(e){return Array.isArray(e)?`array of ${e.length}`:typeof e}var Ln=["__proto__","constructor","prototype"];function Dt(e){return e!==null&&typeof e=="object"&&Object.getPrototypeOf(e)===Object.prototype}function N(e){return e===null||typeof e=="string"||typeof e=="boolean"?!0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?Array.from(e).every(N):Dt(e)?Object.entries(e).every(([t,n])=>!Ln.includes(t)&&N(n)):!1}function le(e,t){let{set:n,unset:r}=e;if(n!==void 0&&!Dt(n))throw new TypeError(`${t} set must be a plain object of front-matter fields`);if(r!==void 0&&!Array.isArray(r))throw new TypeError(`${t} unset must be an array of front-matter field names`);let i=Object.keys(n??{}),s=r??[];if(i.length+s.length===0)throw new TypeError(`${t} requires at least one field in set or unset`);for(let o of i)if(xt(o,t),n[o]===null||!N(n[o]))throw new TypeError(`${t} set "${o}" must be a non-null JSON value (no undefined, non-finite number, sparse array, class instance, or __proto__/constructor/prototype key); remove a field with unset`);for(let o of s){if(xt(o,t),o==="body"||o==="front_matter")throw new TypeError(`${t} cannot unset "${o}"; the item format reserves that name`);if(i.includes(o))throw new TypeError(`${t} both sets and unsets "${o}"`)}if(new Set(s).size!==s.length)throw new TypeError(`${t} unset repeats a field`)}async function Pt(e){le(e,`Finalization of ${e.id}`);let t=await D(e.pmRoot),n={schema:t.schema,extensionFieldNames:Je(C())},r=await Qe({pmRoot:e.pmRoot,settings:t,id:e.id,op:Kn,author:e.author,message:e.message,force:e.force===!0,extensionFieldNames:n.extensionFieldNames,mutate:i=>{let s=structuredClone(i.metadata),o=i.metadata;for(let[c,p]of Object.entries(e.set??{}))o[c]=structuredClone(p);for(let c of e.unset??[])delete o[c];let a;try{Pe(i.metadata);let c=re(i,n),p=re(ze(Ge(c,n),n),n);if(b(p)!==b(c))throw new TypeError("the stored item reads back as a different document; a set field collides with a name the item format reserves");a=c.metadata;let l=Object.entries(e.set??{}).find(([y,h])=>J(a[y])!==J(h));if(l!==void 0)throw new TypeError(`set "${l[0]}" is not stored as declared (${J(l[1])} normalizes to ${a[l[0]]===void 0?"an absent field":J(a[l[0]])})`)}catch(c){throw new u(`Finalization of ${e.id} would not store a readable item with the declared fields: ${c.message}`,f.USAGE,{code:"finalization_invalid_document",item_id:e.id,required:"Declare set and unset fields that leave a valid item under the workspace schema, with each set value in the shape its field stores.",why:"A finalization writes front-matter fields exactly, so the patched document is read back through the item reader, and each declared value is checked against what would be stored, before anything is written.",nextSteps:[`Run pm get ${e.id} --json to compare the current fields with the finalization, then correct the patch and retry the transaction.`]})}return{changedFields:[...new Set([...Object.keys(s),...Object.keys(a)])].filter(c=>Object.hasOwn(s,c)!==Object.hasOwn(a,c)||b(s[c])!==b(a[c])).sort((c,p)=>c.localeCompare(p))}}});return{item:r.item,changedFields:r.changedFields}}async function Hn(e,t){if(!Ze(e))return{schema:te(t.schema),typeDefinitionsFromFile:[]};let n=await fr(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function Zn(e,t,n,r){let i=ee({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},C());return(await Xe(e,t.item_format,i.type_to_folder,void 0,n.schema)).flatMap(o=>{let a=o[r];return a==null?[]:[{id:o.id,value:a}]})}function Se(e){let t=new Map,n=async r=>{let i=await D(e),s=await Hn(e,i),o=new Map;for(let a of await Zn(e,i,s,r)){let d=S(a.value);o.set(d,[...o.get(d)??[],a.id])}return o};return{lookup(r){let i=t.get(r)??n(r);return t.set(r,i),i},async recordCreate(r){for(let[i,s]of t){let o=r[i];if(o==null)continue;let a=await s,d=S(o);a.set(d,[...a.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function Xn(e,t){let n=S(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new u(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,f.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function Vt(e,t,n){let r=e.metadata[n.key],i=S(n.value);if(S(r)!==i)throw new u(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,f.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function zt(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.key=="string"&&t.key.trim().length>0&&t.value!==void 0&&t.value!==null}function Y(e,t){let n={...e,...t};return e===void 0?n:X(e,n)}async function E(e,t){try{let r=(await ae(t,{},{pmRoot:e})).item;return{id:r.id,closedAt:r.closed_at,updatedAt:r.updated_at,assignee:r.assignee,claimPrincipal:r.claim_principal}}catch(n){if(n instanceof u&&n.exitCode===f.NOT_FOUND)return;throw n}}function Ee(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=ge.createHash("sha256").update(b(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function Qn(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function _(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function Oe(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function k(e,t,n,r){let i=await U(m.join(e,"history",`${t}.jsonl`),t),s=_(n,r,"apply"),o=_(n,r,"compensate");for(let a=i.length-1;a>=0;a-=1){let d=i[a].message;if(Oe(d,s))return!0;if(d===o)return!1}return!1}async function H(e,t){let n=await E(e,t.id);if(n?.updatedAt===void 0)throw new u(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,f.NOT_FOUND);let r=await U(m.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new u(`Bulk ${t.op} target ${t.id} has no restorable history`,f.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(ie(r)+r.length),target_history_hash:F(r),target_history_length:r.length}}function T(e,t,n){return new u(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,f.CONFLICT,{code:"transaction_partial_mutation",item_id:t,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${t} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function Yt(e,t){let n=`bulk-item-transaction ${t} `;return[e.message,e.context?.item_transaction_step].some(r=>typeof r=="string"&&r.startsWith(n))}function er(e,t,n){let{expectedHistory:r,length:i,version:s}=t;if(F(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||F(e.slice(0,i))!==r||s!==String(ie(e)+i))throw T(n,n.itemId,n.stepId);let o=_(n.transactionId,n.stepId,"apply"),a=e.slice(i),d=y=>Oe(y.message,o)||y.context?.item_transaction_step===o,c=_(n.transactionId,n.stepId,"compensate");if(a.filter(y=>d(y)||y.message===c).at(-1)?.message===c)return!1;let p=a.filter(d);if(p.length===0)return!1;let l=e.at(-1).after_hash===p.at(-1).after_hash&&a.every(y=>Yt(y,n.transactionId));if(p.length!==a.length&&!l)throw T(n,n.itemId,n.stepId);return!0}async function Ht(e,t){let n=m.join(e,"history",`${t}.jsonl`),r=await Ke(n,t);return{history:r.entries,assertOwnedUnderLock:(i,s)=>{let o;try{o=Jn(n).equals(r.raw_bytes)&&Le(i)===r.entries.at(-1).after_hash}catch(a){throw Object.assign(s(),{cause:a})}if(!o)throw s()}}}async function j(e,t,n,r){let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;if(i===void 0||typeof i.target_updated_at!="string")return;let s=i.target_updated_at,o=await E(e.pmRoot,t);if(o===void 0)return;let{history:a,assertOwnedUnderLock:d}=await Ht(e.pmRoot,o.id),c=i.target_history_hash,p=typeof c=="string";if(typeof c=="string"){if(!er(a,{expectedHistory:c,length:i.target_history_length,version:i.target_version},{...e,itemId:o.id,stepId:n}))return}else{if(o.updatedAt===s)return;if(!await k(e.pmRoot,o.id,e.transactionId,n))throw T(e,o.id,n)}let l=()=>mt(t,typeof i.target_version=="string"?i.target_version:s,{force:!0,author:e.author,message:_(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await M({pmRoot:e.pmRoot,id:o.id,validate:y=>{d(y,()=>T(e,o.id,n))},compensation:Xt(e,t,n,"restore",p)},l)}var Zt=new WeakMap;function Xt(e,t,n,r,i){let s=i?it(e.pmRoot,e.transactionId):void 0,o=s===void 0?void 0:Zt.get(s);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function Qt(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await U(m.join(e.pmRoot,"history",`${r.id}.jsonl`),r.id),s=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(i.filter(d=>d.op==="close").at(-1)?.patch.some(d=>d.op==="add"||d.op==="replace"?d.path==="/metadata/close_reason"&&d.value===s:!1)??!1)throw new u(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,f.CONFLICT,{code:"transaction_create_compensated",item_id:r.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${r.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:r.id,op:"create"}}},async apply(){t.unique!==void 0&&await Xn(e.uniqueIndex,t.unique);let r=await ut(Y(t.options,{author:e.author,id:t.id,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=r.item;return e.onCreateWarnings?.(String(i.id),r.warnings),await e.uniqueIndex.recordCreate(i),{id:String(i.id),op:"create"}},async compensate(){await tr(e,t.id,n)}}}async function tr(e,t,n){let r=await E(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:s}=await Ht(e.pmRoot,r.id),o=_(e.transactionId,n,"apply"),a=_(e.transactionId,n,"compensate"),d=i.filter(c=>Oe(c.message,o)||c.message===a).at(-1);if(d?.message!==a){if(d===void 0||!i.every(c=>Yt(c,e.transactionId)))throw T(e,r.id,n);await M({pmRoot:e.pmRoot,id:r.id,validate:c=>{s(c,()=>T(e,r.id,n))},compensation:Xt(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let c={force:!0,author:e.author,message:a};e.createCompensation==="delete"?await lt(t,c,{pmRoot:e.pmRoot}):await ce(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...c,validateClose:"off"},{pmRoot:e.pmRoot})})}}function nr(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let r=()=>ft(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,s=i,a=(await M({pmRoot:e.pmRoot,id:await en(e.pmRoot,t.id),validate:d=>{s!==void 0&&Vt(d,t.id,s)},committed:d=>{i!==void 0&&(s={key:i.key,value:structuredClone(d.metadata[i.key])})},historyContext:{item_transaction_step:_(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(a.id),op:"update"}},async compensate(r){await j(e,t.id,n,r)}}}async function en(e,t){return String((await ae(t,{},{pmRoot:e})).item.id)}function rr(e,t,n){let r=_(e.transactionId,n,"apply");return{id:n,compensatePending:!0,async inspect(){let i=await E(e.pmRoot,t.id);return i===void 0||!await k(e.pmRoot,i.id,e.transactionId,n)?{state:"pending"}:{state:"applied",result:{id:i.id,op:t.op}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=await en(e.pmRoot,t.id),{match:s}=t;return await yt(e.pmRoot,()=>M({pmRoot:e.pmRoot,id:i,validate:o=>{s!==void 0&&Vt(o,t.id,s)},historyContext:{item_transaction_step:r}},()=>Pt({pmRoot:e.pmRoot,id:i,author:e.author,message:r,force:t.force,...t.set===void 0?{}:{set:t.set},...t.unset===void 0?{}:{unset:t.unset}}))),e.uniqueIndex.invalidate(),{id:i,op:t.op}},async compensate(i){await j(e,t.id,n,i)}}}function ir(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"close"}}:r.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"close"}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=(await ce(t.id,t.reason,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"close"}},async compensate(r){await j(e,t.id,n,r)}}}function or(e,t,n){return{id:n,async inspect(){let r=await E(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await k(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"release"}}:r.assignee!==void 0||r.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"release"}}},async prepareCompensation(){return H(e.pmRoot,t)},async apply(){let i=(await pt(t.id,Y(t.options,{author:e.author,message:_(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(i.id),op:"release"}},async compensate(r){await j(e,t.id,n,r)}}}function be(e,t,n){let r=Ee(t,n),i=sr(e,t,r);return Zt.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function sr(e,t,n){switch(t.op){case"create":return Qt(e,t,n);case"update":return nr(e,t,n);case"close":return ir(e,t,n);case"release":return or(e,t,n);case"finalize":return rr(e,t,n)}}function ar(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`Bulk mutation ${t+1} must be an object`);if(!["create","update","close","release","finalize"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, release, or finalize`);if(typeof e.id!="string"||e.id.trim().length===0)throw new TypeError(`Bulk mutation ${t+1} requires a non-empty id`);if(e.op==="close"&&(typeof e.reason!="string"||e.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${t+1} requires a non-empty reason`);if(cr(e,t),e.op==="finalize"){dr(e,t);return}q(e.options,e.op,t)}function cr(e,t){if(e.op==="create"&&e.unique!==void 0&&!zt(e.unique))throw new TypeError(`Bulk create mutation ${t+1} unique must be an object with a non-empty key and a value`);if((e.op==="update"||e.op==="finalize")&&e.match!==void 0&&!zt(e.match))throw new TypeError(`Bulk ${e.op} mutation ${t+1} match must be an object with a non-empty key and a value`)}var Gt=["op","id","set","unset","match","force"];function dr(e,t){let n=`Bulk finalize mutation ${t+1}`,r=Object.keys(e).filter(i=>!Gt.includes(i));if(r.length>0)throw new TypeError(`${n} has unsupported keys: ${r.join(", ")}; a finalization carries only ${Gt.join(", ")}`);if(e.force!==void 0&&typeof e.force!="boolean")throw new TypeError(`${n} force must be a boolean`);if(e.match!==void 0&&!N(e.match))throw new TypeError(`${n} match must be a plain object with a JSON value`);le(e,n)}function we(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,r]of e.entries()){if(ar(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:s}=r.unique,o=t.get(i)??new Map,a=S(s),d=o.get(a);if(d!==void 0)throw new u(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(a)} for "${i}".`,f.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});o.set(a,n),t.set(i,o)}}function tn(e){let t=[...e];we(t);let n=t.map(r=>{let i=structuredClone(r);return r.op!=="finalize"&&i.op!=="finalize"&&r.options!==void 0&&i.options!==void 0&&X(r.options,i.options),i});return we(n),n}function nn(e,t=""){return e===null||typeof e!="object"?[]:Object.entries(e).flatMap(([n,r])=>{let i=`${t}/${n.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(n)?[i]:nn(r,i)})}async function he(e,t,n){try{return await n()}catch(r){throw r instanceof u?new u(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function rn(e,t,n,r){let i=m.relative(e,t),s=i.split(m.sep);return s[0]==="extensions"&&s[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))?!1:["locks","runtime","search"].includes(i.split(m.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${m.sep}`)||o.startsWith(`${i}${m.sep}`))}async function B(e,t){let n=await qt(t);if(n.isSymbolicLink())await _e(t);else if(n.isDirectory()||n.isFile())return n;throw I(m.relative(e,t))}async function ur(e,t){let n=await Vn(t,me.O_RDONLY|me.O_NOFOLLOW|me.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw I(m.relative(e,t));let i=ge.createHash("sha256");if(r.size>0)for await(let s of n.createReadStream({highWaterMark:64*1024,end:r.size-1,autoClose:!1}))i.update(s);return i.digest()}finally{await n.close()}}async function ye(e,t,n){let r=ge.createHash("sha256");async function i(s){for(let o of(await Yn(s)).sort()){let a=m.join(s,o);rn(e,a,t,n)&&((await B(e,a)).isDirectory()?await i(a):(r.update(JSON.stringify(m.relative(e,a))),r.update(await ur(e,a))))}}return await i(e),r.digest("hex")}function W(){return new u("Tracker changed while preparing the transaction preview; retry against stable state.",f.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ve(e){if(!Q(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=m.resolve(t),r=n;for(;;)try{let i=await qt(r);return r!==n&&i.isDirectory()}catch(i){if(!Q(i))return!1;let s=m.dirname(r);if(s===r)return!1;r=s}}async function V(e,t){let n=m.join(e,t);try{let r=e;for(let i of t.split(m.sep).slice(0,-1))r=m.join(r,i),await B(e,r);if(!(await B(e,n)).isFile())throw I(t);return await Ce(n,I(t))}catch(r){if(await ve(r))return;throw r}}async function on(e,t,n,r){let i=te(n);for(let[s,o]of Object.entries(i.files)){let a=m.relative(e,Fe(e,o,Ue[s]));if(a===""||!m.resolve(e,a).startsWith(m.join(e,m.sep)))throw new u("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",f.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${s}`});i.files[s]=a;let d=await V(e,a);if(r?.set(a,d),d!==void 0){let c=m.join(t,a);await Bn(m.dirname(c),{recursive:!0}),await Wt(c,d)}}return xe(t,i)}async function fr(e,t){await _e(e);let n=await Kt(m.join(Bt(),"pm-schema-plan-"));try{let r=await Lt(e);return await on(r,m.join(n,"configuration"),t)}catch(r){throw await ve(r)?W():r}finally{await Jt(n,{recursive:!0,force:!0})}}async function pr(e,t,n){let r=new Map,i=await V(e,R);r.set(R,i);let s;try{s=JSON.parse(i??"null")}catch{s=null}let o=He(s),a=o.success?o.data:void 0,d=await on(e,t,a?.schema,r),c=d.schema,p=m.relative(e,qe(e));r.set(p,await V(e,p));let l=ee({...ke,item_types:{definitions:[...a?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),y=Ne(e)===e?[...Te.filter(Boolean),R,rt,"transactions",...l.folders,...r.keys()].map(g=>m.normalize(g)):void 0,h=a===void 0?void 0:JSON.stringify({...s,schema:{...a.schema,files:c.files}});return{configuration:r,ownedPaths:y,stagedSettings:h,registryFolders:l.folders}}async function lr(e,t,n){await _e(e);try{let r=await Lt(e),i=await pr(r,m.join(m.dirname(t),"configuration"),n),s=[...i.configuration.keys(),...i.registryFolders].map(c=>m.normalize(c)),o=await ye(r,i.ownedPaths,s);await Wn(r,t,{recursive:!0,dereference:!1,filter:async c=>rn(r,c,i.ownedPaths,s)?(await B(r,c),!0):!1});let[a,d]=await Promise.all([ye(r,i.ownedPaths,s),ye(t,i.ownedPaths,s)]);if(o!==a||o!==d)throw W();for(let[c,p]of i.configuration)if(await V(t,c)!==p)throw W();i.stagedSettings!==void 0&&await Wt(m.join(t,R),i.stagedSettings)}catch(r){throw await ve(r)?W():r}}async function Mi(e){let t=P(e),n=tn(e.mutations),r=C(),i=Ve(),s=await Kt(m.join(Bt(),"pm-transaction-preview-")),o=m.join(s,"tracker");try{await lr(t.pmRoot,o,r);let a=!1,d=[],c=[],p=new Set;return await Be(i,()=>ht({path:o,noExtensions:!0},async()=>{We(r);let l={...t,pmRoot:o,createCompensation:"close",uniqueIndex:Se(o)},y=n.map((h,g)=>{let O=be({...l,onCreateWarnings:(Z,Ae)=>{Ae.length>0&&d.push({index:g,id:Z,op:"create",warnings:Ae})}},h,g);return{...O,inspect:()=>he(h,g,()=>O.inspect()),prepareCompensation:()=>he(h,g,async()=>O.prepareCompensation?.()),apply:()=>he(h,g,async()=>{let Z=await O.apply();return p.add(g),Z})}});if(await oe({...t,pmRoot:o,steps:y,onTransition:({transition:h})=>{h==="committed"&&(a=!0)}}),a)for(let[h,g]of n.entries()){let O=(await dt(g.id,{path:o},{full:!0})).item;c.push({index:h,id:String(O.id),op:g.op,execution:p.has(h)?"applied":"adopted",item:O,commit_time_fields:nn(O)})}})),{records:c,validated:a,state:a?"staged_snapshot":"replayed_committed_plan",warnings:d,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await Jt(s,{recursive:!0,force:!0})}}async function mr(e){let t=P(e),n=tn(e.mutations),r=e.createCompensation??"close";if(!["close","delete"].includes(r))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={...t,createCompensation:r,uniqueIndex:Se(t.pmRoot)},s=await oe({...t,steps:n.map((a,d)=>be(i,a,d)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations:n,createCompensation:r})),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}}),o={};for(let[a,d]of n.entries()){let c=Ee(d,a),p=s.results[c];o[Qn(d,a)]=p}return{transactionId:s.transactionId,status:"committed",recovered:s.recovered,results:o}}function hr(e){let t=[];return e.evidence!==void 0&&Object.keys(e.evidence).length>0&&t.push({op:"update",id:e.id,options:e.evidence}),t.push({op:"close",id:e.id,reason:e.reason,...e.closeOptions===void 0?{}:{options:e.closeOptions}},{op:"release",id:e.id,...e.releaseOptions===void 0?{}:{options:e.releaseOptions}}),t}function Ci(e){return mr({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:hr(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var Ni={buildCreateStep:Qt,bulkHistoryMarker:_,compensateByRestore:j,deriveStepId:Ee,isUpdateMarkerApplied:k,readItemSnapshot:E};async function ji(e,t){let n=await ot(e,t);return n===void 0?void 0:{journal:n,planDigest:se(n)}}function yr(e,t){let n=t.recoveryData;if(n===null||typeof n!="object"||Array.isArray(n)||n.kind!=="item-mutations-v1"||!Array.isArray(n.mutations)||!["close","delete"].includes(String(n.createCompensation)))throw new u("Transaction has no supported item recovery plan",f.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});let r=n.mutations;we(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:Se(e.pmRoot)};return r.map((s,o)=>be(i,s,o))}async function Ui(e){let t=P(e),n=await st({...e,...t,resolveSteps:r=>yr({...e,...t},r)});return{journal:n,planDigest:se(n)}}export{wt as a,Pr as b,zr as c,Ct as d,S as e,Gr as f,Gn as g,qr as h,Hn as i,Zn as j,fr as k,Mi as l,mr as m,hr as n,Ci as o,Ni as p,ji as q,Ui as r};
2
+ //# sourceMappingURL=chunk-Q6GLSAJY.js.map
@@ -1,8 +1,8 @@
1
- import{d as q}from"./chunk-OGVSGXQX.js";import{a as X,b as R,c as _,d as J}from"./chunk-AA52P34H.js";import{H as K,n as H,u as E,z as V}from"./chunk-KXTKLDKD.js";import{Ib as W,Rf as U,fb as $}from"./chunk-SJWIPGZW.js";import{g as B,o as P}from"./chunk-GSLOAEY2.js";import{Q as L}from"./chunk-VCXQ6A35.js";import{A as b,C as k,E as S,G as F,H as G,L as N}from"./chunk-K672XXGQ.js";var ce="PM_SOURCE_CONTEXT_ACCESS",le="PM_ALLOW_SOURCE_CONTEXT_WRITES";function z(e){let n=e[ce],r=n===void 0||n.trim().toLowerCase()==="write"?"write":"read_only",t=r==="read_only"&&e[le]?.trim()==="1";return{access:r,write_override_applied:t,source_writes_allowed:r==="write"||t}}import{access as ue,lstat as ee,readFile as T,realpath as h}from"node:fs/promises";import{constants as me}from"node:fs";import{execFile as pe}from"node:child_process";import a from"node:path";import{promisify as de}from"node:util";var v=de(pe),C="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",x="# pm-cli:merge-drivers:v2:start",te="# pm-cli:merge-drivers:v2:end",ge="merge-fence",he="merge-attributes";function A(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function we(e,n){let r=await h(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(r))return;let{stdout:t}=await v(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()===n?r:void 0}async function ye(){let e=U(import.meta.url,["../../.."]),n=process.execPath,r=!1,t=await h(process.execPath),o=process.versions.bun,i=(process.env.PATH??"").split(a.delimiter).filter(s=>a.isAbsolute(s)).map(s=>a.join(s,o===void 0?a.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),c=o===void 0?i:[process.env.npm_execpath??"",...i,t].filter(s=>a.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(a.basename(s)));for(let s of c)try{if(await ue(s,me.X_OK),o!==void 0){let p=await we(s,o);if(p!==void 0){n=p,r=!0;break}continue}if(s!==t&&await h(s)===t){n=s;break}}catch{}if(o!==void 0&&!r)throw new k("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",b.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${A(n)} ${A(a.join(e,"dist","cli.js"))}`}var re=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function _e(e){let n=e.explicitPath?.trim(),r=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),t=e.environment.PM_SOURCE_PM_PATH?.trim(),o=z(e.environment),i=!!(r&&t),c=n===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(n!==void 0){let s=P(e.cwd,n);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return c?{pm_root:a.resolve(t),workspace_start:a.resolve(r),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?P(e.cwd,".agents/pm"):P(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function M(e){try{let{stdout:n}=await v("git",["rev-parse","--show-toplevel"],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await h(R(n))}catch{return null}}async function ne(e){let n=await M(e);if(n===null)throw new k("pm merge install requires a git repository (merge drivers are git configuration).",b.USAGE);return n}function O(e,n){return a.relative(e,n).split(a.sep).join("/")}function Y(e){return e.replace(/[\\*?[\]!]/gu,"\\$&")}function g(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Q(e,n){if(e[n]!=="'")return null;let r="";for(let t=n+1;t<e.length;t+=1){if(e.startsWith(`'"'"'`,t)){r+="'",t+=4;continue}if(e[t]==="'")return{value:r,nextOffset:t+1};r+=e[t]}return null}async function ve(e,n,r){if(V(n).filter(i=>i.constraint==="exact").some(i=>i.version!==r))return!1;let o=await M(e);if(o!==null&&o!==await h(n)){let i=await Promise.all([o,n].map(async c=>{let s=await v("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:c,env:_(),timeout:1e4});return h(s.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function be(e,n,r){let t=Q(e,0);if(t===null||e[t.nextOffset]!==" ")return!1;let o=Q(e,t.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==n||!/^(?:node|bun)(?:\.exe)?$/iu.test(a.basename(t.value))||a.basename(o.value)!=="cli.js"||a.basename(a.dirname(o.value))!=="dist"||!await S(t.value)||!await S(o.value))return!1;try{let i=a.dirname(a.dirname(o.value)),c=JSON.parse(await T(a.join(i,"package.json"),"utf8")),s=typeof c.bin=="string"?c.bin:c.bin?.pm;return await ve(i,r,c.version)?c.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function j(e,n){let r=e.length>0?`${Y(e)}/`:"",t=[`${g(`${r}**/*.toon`)} merge=pm-item-toon`,`${g(`${r}**/*.md`)} merge=pm-item-markdown`];for(let o of n){let i=Y(o);t.push(`${g(`${r}${i}/*.toon`)} merge=pm-item-toon`),t.push(`${g(`${r}${i}/*.md`)} merge=pm-item-markdown`)}return t.push(`${g(`${r}**/*.jsonl`)} merge=pm-relationship`),t.push(`${g(`${r}history/*.jsonl`)} merge=pm-history`),t.push(`${g(`${r}settings.json`)} merge=pm-json`),t.push(`${g(`${r}**/*.json`)} merge=pm-json`),t.push(`${g(`${r}extensions/**`)} merge=text`),t.push(`${g(`${r}extensions/.managed-extensions.json`)} merge=pm-json`),t}function oe(e){let n=[],r=0;for(;r<e.length;){let t=e.indexOf(C,r),o=e.indexOf(x,r),i=t===-1?o:o===-1?t:Math.min(t,o);if(i===-1)break;let c=i===o,s=c?x:C,p=c?te:fe,d=e.indexOf(p,i+s.length),u=d===-1?e.length:d+p.length;n.push({start:i,end:u,closed:d!==-1,lines:e.slice(i+s.length,d===-1?u:d).split(`
1
+ import{d as q}from"./chunk-OGVSGXQX.js";import{a as X,b as R,c as _,d as J}from"./chunk-AA52P34H.js";import{H as K,n as H,u as E,z as V}from"./chunk-OXC5KBIQ.js";import{Ib as W,Mf as U,fb as $}from"./chunk-NRQCBUYD.js";import{g as B,o as P}from"./chunk-GSLOAEY2.js";import{Q as L}from"./chunk-I4SPJQQI.js";import{A as b,C as k,E as S,G as F,H as G,L as N}from"./chunk-K672XXGQ.js";var ce="PM_SOURCE_CONTEXT_ACCESS",le="PM_ALLOW_SOURCE_CONTEXT_WRITES";function z(e){let n=e[ce],r=n===void 0||n.trim().toLowerCase()==="write"?"write":"read_only",t=r==="read_only"&&e[le]?.trim()==="1";return{access:r,write_override_applied:t,source_writes_allowed:r==="write"||t}}import{access as ue,lstat as ee,readFile as T,realpath as h}from"node:fs/promises";import{constants as me}from"node:fs";import{execFile as pe}from"node:child_process";import a from"node:path";import{promisify as de}from"node:util";var v=de(pe),C="# pm-cli:merge-drivers:start",fe="# pm-cli:merge-drivers:end",x="# pm-cli:merge-drivers:v2:start",te="# pm-cli:merge-drivers:v2:end",ge="merge-fence",he="merge-attributes";function A(e){return`'${e.replaceAll("'",`'"'"'`)}'`}async function we(e,n){let r=await h(e);if(/(?:^|[\\/])bun-node-[^\\/]+[\\/]bun(?:\.exe)?$/iu.test(r))return;let{stdout:t}=await v(e,["--version"],{encoding:"utf8",windowsHide:!0,timeout:1e4});return t.trim()===n?r:void 0}async function ye(){let e=U(import.meta.url,["../../.."]),n=process.execPath,r=!1,t=await h(process.execPath),o=process.versions.bun,i=(process.env.PATH??"").split(a.delimiter).filter(s=>a.isAbsolute(s)).map(s=>a.join(s,o===void 0?a.basename(process.execPath):process.platform==="win32"?"bun.exe":"bun")),c=o===void 0?i:[process.env.npm_execpath??"",...i,t].filter(s=>a.isAbsolute(s)&&/^(?:bun|bun\.exe)$/iu.test(a.basename(s)));for(let s of c)try{if(await ue(s,me.X_OK),o!==void 0){let p=await we(s,o);if(p!==void 0){n=p,r=!0;break}continue}if(s!==t&&await h(s)===t){n=s;break}}catch{}if(o!==void 0&&!r)throw new k("Cannot install Bun merge drivers without a durable executable matching the current Bun version.",b.DEPENDENCY_FAILED,{code:"merge_bun_launcher_unavailable",why:"The current Bun process may be a temporary bunx launcher that Git cannot reuse after this command exits.",nextSteps:["Run with a durable version-matched Bun executable, expose one on an absolute PATH entry, or invoke pm through a Bun runner that publishes an absolute npm_execpath.","Retry pm merge install, then check pm health --strict-exit before merging branches."]});return`${A(n)} ${A(a.join(e,"dist","cli.js"))}`}var re=[{key:"pm-item-toon",name:"pm field-aware TOON item document merge",artifact:"item",itemPath:"%P"},{key:"pm-item-markdown",name:"pm field-aware JSON-markdown item document merge",artifact:"item",itemPath:"%P"},{key:"pm-history",name:"pm append-only history stream merge",artifact:"history",itemPath:void 0},{key:"pm-relationship",name:"pm append-only relationship event store merge",artifact:"relationship",itemPath:void 0},{key:"pm-json",name:"pm key-level JSON config merge",artifact:"json",itemPath:void 0}];function _e(e){let n=e.explicitPath?.trim(),r=e.environment.PM_SOURCE_WORKSPACE_ROOT?.trim(),t=e.environment.PM_SOURCE_PM_PATH?.trim(),o=z(e.environment),i=!!(r&&t),c=n===void 0&&i&&(e.dryRun||o.source_writes_allowed);if(n!==void 0){let s=P(e.cwd,n);return{pm_root:s,workspace_start:s,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}return c?{pm_root:a.resolve(t),workspace_start:a.resolve(r),source_coordinates_available:!0,source_context_selected:!0,source_policy:o}:{pm_root:i?P(e.cwd,".agents/pm"):P(e.cwd),workspace_start:e.cwd,source_coordinates_available:i,source_context_selected:!1,source_policy:o}}async function M(e){try{let{stdout:n}=await v("git",["rev-parse","--show-toplevel"],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4});return await h(R(n))}catch{return null}}async function ne(e){let n=await M(e);if(n===null)throw new k("pm merge install requires a git repository (merge drivers are git configuration).",b.USAGE);return n}function O(e,n){return a.relative(e,n).split(a.sep).join("/")}function Y(e){return e.replace(/[\\*?[\]!]/gu,"\\$&")}function g(e){return`"${e.replaceAll("\\","\\\\").replaceAll('"','\\"')}"`}function Q(e,n){if(e[n]!=="'")return null;let r="";for(let t=n+1;t<e.length;t+=1){if(e.startsWith(`'"'"'`,t)){r+="'",t+=4;continue}if(e[t]==="'")return{value:r,nextOffset:t+1};r+=e[t]}return null}async function ve(e,n,r){if(V(n).filter(i=>i.constraint==="exact").some(i=>i.version!==r))return!1;let o=await M(e);if(o!==null&&o!==await h(n)){let i=await Promise.all([o,n].map(async c=>{let s=await v("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:c,env:_(),timeout:1e4});return h(s.stdout.trim())}));if(i[0]===i[1])return!1}return!0}async function be(e,n,r){let t=Q(e,0);if(t===null||e[t.nextOffset]!==" ")return!1;let o=Q(e,t.nextOffset+1);if(o===null||e.slice(o.nextOffset)!==n||!/^(?:node|bun)(?:\.exe)?$/iu.test(a.basename(t.value))||a.basename(o.value)!=="cli.js"||a.basename(a.dirname(o.value))!=="dist"||!await S(t.value)||!await S(o.value))return!1;try{let i=a.dirname(a.dirname(o.value)),c=JSON.parse(await T(a.join(i,"package.json"),"utf8")),s=typeof c.bin=="string"?c.bin:c.bin?.pm;return await ve(i,r,c.version)?c.name==="@unbrained/pm-cli"&&s==="dist/cli.js":!1}catch{return!1}}function j(e,n){let r=e.length>0?`${Y(e)}/`:"",t=[`${g(`${r}**/*.toon`)} merge=pm-item-toon`,`${g(`${r}**/*.md`)} merge=pm-item-markdown`];for(let o of n){let i=Y(o);t.push(`${g(`${r}${i}/*.toon`)} merge=pm-item-toon`),t.push(`${g(`${r}${i}/*.md`)} merge=pm-item-markdown`)}return t.push(`${g(`${r}**/*.jsonl`)} merge=pm-relationship`),t.push(`${g(`${r}history/*.jsonl`)} merge=pm-history`),t.push(`${g(`${r}settings.json`)} merge=pm-json`),t.push(`${g(`${r}**/*.json`)} merge=pm-json`),t.push(`${g(`${r}extensions/**`)} merge=text`),t.push(`${g(`${r}extensions/.managed-extensions.json`)} merge=pm-json`),t}function oe(e){let n=[],r=0;for(;r<e.length;){let t=e.indexOf(C,r),o=e.indexOf(x,r),i=t===-1?o:o===-1?t:Math.min(t,o);if(i===-1)break;let c=i===o,s=c?x:C,p=c?te:fe,d=e.indexOf(p,i+s.length),u=d===-1?e.length:d+p.length;n.push({start:i,end:u,closed:d!==-1,lines:e.slice(i+s.length,d===-1?u:d).split(`
2
2
  `).map(l=>l.trim()).filter(Boolean)}),r=u}return n}function ie(e,n,r){let t=new Set(n),o=g(r.length>0?`${r}/`:"").slice(0,-1);return e.some(i=>t.has(i)||i.startsWith(o)&&/^[^/]+\/\*\.(?:toon|md)" merge=pm-item-(?:toon|markdown)$/u.test(i.slice(o.length)))}async function se(e,n,r,t){let o=a.join(e,".gitattributes"),i=t?null:R((await v("git",["rev-parse","--absolute-git-dir"],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4})).stdout),c=i===null?null:await $(i,he,120,"merge-fence",!1,!0,5e3);try{let s=await G(o)??"",p=[x,...r,te].join(`
3
3
  `),d=oe(s),u=d.filter(m=>ie(m.lines,r,n));u.length===0&&n===".agents/pm"&&d.length===1&&d[0].lines.every(m=>!m.includes("/"))&&u.push(d[0]);let l;if(u.length>0){let m=u[0];l=s;for(let y of u.slice(1).reverse())l=`${l.slice(0,y.start)}${l.slice(y.end)}`;l=`${l.slice(0,m.start)}${p}${l.slice(m.end)}`}else{let m=s.trimEnd();l=`${m.length>0?`${m}
4
4
 
5
5
  `:""}${p}
6
6
  `}return l===s&&!(await ee(o)).isSymbolicLink()?{path:o,changed:!1}:(t||await N(o,l),{path:o,changed:!0})}finally{await c?.()}}function ae(e){let n=B(e,null);return[...new Set(Object.values(n.type_to_folder))].sort((r,t)=>r.localeCompare(t))}async function Z(e){try{return await h(e)}catch{return null}}function ke(e,n){let r=a.relative(e,n);return r===""||!a.isAbsolute(r)&&r.split(a.sep)[0]!==".."}async function xe(e){try{return(await ee(e)).isFile()?await T(e,"utf8"):null}catch{return null}}async function Pe(e){try{return await T(e,"utf8")}catch{return null}}async function $e(e,n){let r=n===void 0?await M(e):n;if(r===null)return{trackerRoot:e,topLevel:null};let[t,o]=await Promise.all([Z(e),Z(r)]);return t===null||o===null||!ke(o,t)?null:{trackerRoot:t,topLevel:o}}async function Ee(e){let n=e.topLevel===null?Pe:xe,r=e.trackerRoot;for(let t=0;e.topLevel!==null||t<8;t+=1){let o=await n(a.join(r,".gitattributes"));if(o!==null&&(o.includes(x)||o.includes(C)))return{directory:r,content:o};let i=a.dirname(r);if(i===r||e.topLevel!==null&&a.relative(e.topLevel,r)==="")return null;r=i}return null}async function Ye(e,n,r={}){let t=await $e(a.resolve(e),r.gitWorkspaceRoot),o=t===null?null:await Ee(t);if(t===null||o===null)return{status:"not_installed",missing_patterns:[],stale_patterns:[],schema_scope:"project"};let i=o.directory,c=o.content,s=a.join(i,".gitattributes"),p=O(i,t.trackerRoot),d=oe(c),u=j(p,n),l=d.filter(w=>ie(w.lines,u,p)),m=l.flatMap(w=>w.closed?w.lines:[]),y=new Set(m),f=new Set(u),I=u.filter(w=>!y.has(w)),D=m.filter(w=>!f.has(w));return{status:l.length!==1||!l[0].closed||I.length>0||D.length>0?"drift":"ok",path:s,missing_patterns:I,stale_patterns:D,schema_scope:"project"}}async function Qe(e){let n=[],r=[];for(let t of re){let o=`merge.${t.key}.driver`,i=` merge driver ${t.artifact} "%O" "%A" "%B"${t.itemPath===void 0?"":` --item-path ${t.itemPath}`}`;try{let{stdout:c}=await v("git",["config","--get",o],{cwd:e,env:_(),encoding:"utf8",windowsHide:!0,timeout:1e4}),s=c.trim();await be(s,i,e)||r.push(o)}catch{n.push(o)}}return{status:n.length>0?"missing":r.length>0?"drift":"ok",missing_keys:n,drifted_keys:r}}async function Ze(e){let n;try{n=await ne(a.resolve(e))}catch{return{status:"no_git"}}let r=O(n,a.resolve(e)),t=await E(e),o=W(void 0,t.author_default),i=await $(e,ge,t.locks.ttl_seconds,o,!1,H(t).force_required_for_stale_lock,t.locks.wait_ms);try{let c=a.join(n,".gitattributes"),s;try{s=await T(c,"utf8")}catch(l){if(l instanceof Error&&"code"in l&&F(l))return{status:"not_installed",path:c};throw l}if(!s.includes(x)&&!s.includes(C))return{status:"not_installed",path:c};let p=await E(e),d=ae(p),u=await se(n,r,j(r,d),!1);return{status:u.changed?"refreshed":"unchanged",path:u.path}}finally{await i()}}async function et(e,n){let r=_e({cwd:process.cwd(),explicitPath:n.path,dryRun:e.dryRun===!0,environment:process.env}),t=r.pm_root;await K(t);let o=await ne(r.workspace_start);return Te({pmRoot:t,workspaceRoot:o,dryRun:e.dryRun===!0,preCommitHook:e.preCommitHook===!0})}async function Ce(e,n){let r=(await v("git",["rev-parse","--path-format=absolute","--git-common-dir"],{cwd:e,env:_(),timeout:1e4})).stdout.trim(),t=await $(r,"merge-driver-config",120,"merge-install",!1,!0,5e3);try{let o=await J(e),i;try{i=(await v("git",["config",o,"--null","--get-regexp","."],{cwd:e,env:_(),timeout:1e4})).stdout}catch(s){if(typeof s!="object"||s===null||!("code"in s)||s.code!==1)throw s;i=""}let c=new Map(i.split("\0").filter(Boolean).map(s=>{let p=s.indexOf(`
7
7
  `);return[s.slice(0,p),s.slice(p+1)]}));for(let s of n)c.get(s.key)!==s.value&&await X(e,[o,s.key,s.value])}finally{await t()}}async function Te(e){let n=a.resolve(e.pmRoot),r=a.resolve(e.workspaceRoot),t=e.dryRun===!0,o,i;try{[o,i]=await Promise.all([h(n),h(r)])}catch(f){throw new k(`Cannot resolve tracker root ${n} or workspace root ${r}: ${String(f)}`,b.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 c=O(i,o);if(q(c))throw new k(`Tracker root ${n} is outside the git repository ${r}; there is nothing to configure for this repository.`,b.USAGE);let s=await E(o),p=ae(s),d=j(c,p),u=[],l=await ye(),m=e.preCommitHook===!0?await import("./settlement-hook-BIVNGBZF.js").then(async f=>({plan:await f.prepareMergeSettlementHook(i,`${l} --pm-path ${A(c||".")}`),write:f.writeMergeSettlementHook})):void 0;for(let f of re)u.push({key:`merge.${f.key}.name`,value:f.name}),u.push({key:`merge.${f.key}.driver`,value:`${l} merge driver ${f.artifact} "%O" "%A" "%B"${f.itemPath===void 0?"":` --item-path ${f.itemPath}`}`});if(!t)try{await Ce(i,u)}catch{throw new k(`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.`,b.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 y=await se(i,c,d,t);return m!==void 0&&!t&&await m.write(m.plan),{ok:!0,dry_run:t,workspace_root:i,pm_root:o,gitattributes:{path:y.path,changed:y.changed,patterns:d,schema_scope:"project"},git_config:u,...m===void 0?{}:{settlement_hook:{path:m.plan.path,changed:m.plan.changed}},guidance:["Commit .gitattributes so every branch and collaborator shares the merge mapping.",'git config is per-clone: each collaborator (and each fresh worktree/clone) runs "pm merge install" once.','After merging branches, run "pm merge reconcile --dry-run" to inspect the complete receipt and history repair, then apply "pm merge reconcile"; use --force only after explicitly accepting any discarded values.',"Custom item types registered later refresh this fence automatically (pm schema add-type/remove-type); rerun pm merge install only after out-of-band type-folder edits."],generated_at:L()}}export{ce as a,le as b,z as c,C as d,fe as e,x as f,te as g,_e as h,M as i,j,ae as k,Ye as l,Qe as m,Ze as n,et as o,Te as p};
8
- //# sourceMappingURL=chunk-AOTI76Q6.js.map
8
+ //# sourceMappingURL=chunk-Q6K7HWZ7.js.map
@@ -0,0 +1,2 @@
1
+ import{b as ke}from"./chunk-AHV3CSQG.js";import{Ad as v,Jc as ve,kc as ge,lc as ye,mb as k,nb as E,tb as Ie,zd as x}from"./chunk-CBUC4X7Q.js";import{u as xe}from"./chunk-OXC5KBIQ.js";import{Fa as y,Ga as w,H as X,Hf as h,Nb as re,Xg as _e,df as se,kf as A,lf as ce,mf as N,nf as ae,of as de,rf as le,sf as ue,tf as fe,uf as pe,vf as me,wf as he,xf as T,y as j}from"./chunk-NRQCBUYD.js";import{a as J,g as Q,i as Z,o as ee,u as te}from"./chunk-GSLOAEY2.js";import{E as we}from"./chunk-A5ZEMOVR.js";import{y as ne,z as oe}from"./chunk-I4SPJQQI.js";import{ba as ie}from"./chunk-TE6FBDHP.js";import{A as p,C as u,z as W}from"./chunk-K672XXGQ.js";var Ee=new Set(j),Pe=new Set(["files lookup","item files lookup"]);function B(e){let n=e.trim().replace(/^packages(?=\s|$)/u,"package").replace(/\s+/gu,"-");return Ee.has(n)?n:e}function O(e){let n=e.trim().replace(/\s+/gu," ");if(we.has(n)||Pe.has(n))return!1;let t=B(e);return!(Ee.has(t)&&(!ve(t)||t==="deps")&&!X.has(t))}import{readdir as ze}from"node:fs/promises";import $ from"node:path";function D(e,n){return(n===void 0?void 0:Z(e,n))?.execution_role??J[e.trim().toLowerCase()]??"agent"}var M="blocked_by",be="blocks",$e=Object.freeze([M,be]),L="no-active-blocker";function d(e){return e.trim().toLowerCase()}function b(e,n){return n?`external:${e}`:`local:${d(e)}`}function _(e){let n=new Map,t=typeof e.blocked_by=="string"?e.blocked_by.trim():"";if(t.length>0&&d(t)!==L){let o=x(t);n.set(b(t,o),o?t:d(t))}for(let o of e.dependencies??[]){let i=typeof o.id=="string"?o.id.trim():"";if(h(o.kind)===M&&i.length>0&&d(i)!==L){let r=x(i)||v(o.source_kind);n.set(b(i,r),r?i:d(i))}}return[...n.values()].sort((o,i)=>o.localeCompare(i))}function C(e){let n=new Map;for(let t of e){let o=d(t.id);o.length!==0&&n.set(o,new Set(_(t)))}for(let t of e){let o=d(t.id);if(o.length!==0)for(let i of t.dependencies??[]){let r=h(i.kind)===be&&typeof i.id=="string"?d(i.id):"";if(r.length===0||r===L)continue;let s=n.get(r)??new Set;s.add(o),n.set(r,s)}}return new Map([...n].map(([t,o])=>[t,[...o].sort((i,r)=>i.localeCompare(r))]))}function Ce(e,n){let t=d(e.id);return t.length>0?C(n).get(t)??_(e):_(e)}function H(e,n,t,o){let i=e,r=typeof i.id=="string"?o?.get(d(i.id))??Ce(i,[...n.values()]):_(e),s=new Set((e.dependencies??[]).filter(c=>h(c.kind)===M&&v(c.source_kind)&&typeof c.id=="string"&&c.id.trim().length>0).map(c=>b(c.id.trim(),!0)));return r.map(c=>{if(x(c)||s.has(b(c,!0)))return{id:c,title:null,status:null,resolved:!1,external:!0,...typeof e.updated_at=="string"?{blocked_since:e.updated_at}:{},resolver:null};let a=n.get(d(c));return a?{id:c,title:a.title,status:a.status,resolved:w(a.status,t)}:{id:c,title:null,status:null,resolved:!1}})}function P(e,n,t){return H(e,n,t)}function Fe(e,n){let t=new Map(e.map(s=>[d(s.id),s])),o=C(e),i=new Set([...Re(n),...n.blocked_statuses]),r=new Set;for(let s of e){let c=y(s.status,n);if(!i.has(c))continue;(n.blocked_statuses.has(c)||H(s,t,n,o).some(l=>!l.resolved))&&r.add(d(s.id))}return r}function Ke(e,n,t={},o){let i=[...e.ready,...e.decisions,...e.gates];t.includeContainers===!0&&i.push(...e.containers.filter(s=>s.open_blockers.length===0&&!n.blocked_statuses.has(y(s.item.status,n))));let r={ready:[],decisions:[],gates:[]};for(let s of i){let c=D(s.item.type,o);c==="human"&&t.includeDecisions!==!0?r.decisions.push(s):c==="gate"&&t.includeGates!==!0?r.gates.push(s):r.ready.push(s)}return r}function Re(e){return e.active_statuses.size>0?e.active_statuses:new Set([e.open_status])}function Ue(e,n,t){let o=[d(e)],i=new Set;for(;o.length>0;){let r=o.pop();if(!i.has(r)){i.add(r);for(let s of n.get(r)??[]){if(!w(s.status,t))return!0;o.push(d(s.id))}}}return!1}function Ge(e){let n=new Map,t=new Map,o=new Map,i=C(e);for(let r of e){n.set(d(r.id),r);let s=typeof r.parent=="string"?r.parent.trim():"";if(s.length>0){let c=d(s),a=t.get(c)??[];a.push(r),t.set(c,a)}for(let c of i.get(d(r.id))){let a=d(c),l=o.get(a)??[];l.push(r.id),o.set(a,l)}}return{itemsById:n,childrenByParent:t,blockedByReverse:o,blockerIdsByItem:i}}function qe(e,n,t,o){let{itemsById:i,childrenByParent:r,blockedByReverse:s,blockerIdsByItem:c}=Ge(n),a=new Set([...Re(t),...t.blocked_statuses]),l=new Set(n.filter(f=>!w(f.status,t)).map(f=>d(f.id))),U=[],G=[],S=[],q=[],z=[],V=0;for(let f of e){if(!a.has(y(f.status,t)))continue;V+=1;let Y=H(f,i,t,c).filter(m=>!m.resolved),De=(s.get(d(f.id))??[]).filter(m=>l.has(d(m))).sort((m,He)=>m.localeCompare(He)),g={item:f,open_blockers:Y,unblocks:De};if(Ue(f.id,r,t)){S.push(g);continue}let Me=t.blocked_statuses.has(y(f.status,t));if(Y.length===0&&!Me){let m=D(f.type,o);m==="human"?q.push(g):m==="gate"?z.push(g):U.push(g)}else G.push(g)}return{ready:U,blocked:G,containers:S,decisions:q,gates:z,active_count:V,container_count:S.length}}function Ve(e,n){let t=new Map;for(let o of e){let i=o.external?o.id:n.get(o.id.toLowerCase())?.id??o.id;t.set(o.external?`external:${i}`:`local:${i.toLowerCase()}`,{...o,id:i})}return[...t.values()]}async function F(e,n){let t=$.basename(e),i=(await ze($.dirname(e)).catch(r=>{throw ge("Cannot verify the blocker's physical file identity",{exitCode:p.GENERIC_FAILURE,context:{code:"blocker_identity_read_failed",required:"Restore access to the blocker item directory, then retry the item read."},cause:r})})).filter(r=>r.toLowerCase()===t.toLowerCase()).sort((r,s)=>+(s===t)-+(r===t)||r.localeCompare(s)).map(r=>$.parse(r).name)[0];if(i===void 0)throw new u(`Blocker canonical file disappeared during identity verification: ${n}`,p.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker file and validate storage integrity before retrying the item read."});return i}async function wt(e){let n=_(e.metadata);if(n.length===0)return[];let t=new Map([e.metadata.blocked_by,...(e.metadata.dependencies??[]).filter(i=>h(i.kind)==="blocked_by").map(i=>i.id)].filter(i=>typeof i=="string").map(i=>[i.trim().toLowerCase(),i.trim()])),o=new Map;for(let i of n){if(x(i)||!/^(?!\.{1,2}$)[^/\\:\0]+$/u.test(i)||e.metadata.dependencies?.some(c=>c.id.trim()===i&&h(c.kind)==="blocked_by"&&v(c.source_kind)))continue;let r=await k(e.pmRoot,t.get(i),e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(r===null)continue;let s=await E(r,{schema:e.settings.schema});if(r.id=await F(r.itemPath,r.id),s.document.metadata.id!==r.id)throw new u(`Blocker identity differs from its canonical file: ${r.id}`,p.CONFLICT,{code:"item_identity_conflict",required:"Restore the canonical blocker identity and validate storage integrity before retrying the item read."});o.set(i.toLowerCase(),s.document.metadata)}return Ve(P({blocked_by:e.metadata.blocked_by,dependencies:e.metadata.dependencies,updated_at:e.metadata.updated_at},o,ie(e.settings.schema)),o)}var Se="item_revision_conflict",Ye=10,Ae=/^[0-9a-f]{64}$/u;function I(e,n){return new u(`Invalid expected revision ${JSON.stringify(e)}: ${n}.`,p.USAGE,{code:"expect_hash_invalid",value:e,required:"Pass the 64-character item_hash from pm get <id> --json, optionally as <id>=<item_hash>.",examples:["--expect-hash <item_hash>","--expect-hash pm-a1b2=<item_hash>"]})}function Ne(e){let n=typeof e=="string"?e.trim().toLowerCase():"";if(!Ae.test(n))throw I(String(e),"the revision is not a 64-character hexadecimal item_hash");return n}function We(e){return(e===void 0?[]:typeof e=="string"?[e]:e).flatMap(t=>{if(typeof t!="string")throw I(String(t),"expected a string");let o=t.split(",").map(r=>r.trim()).filter(r=>r.length>0);if(o.length===0)throw I(t,"the value is empty");let i=r=>oe(t)===t?r:ne;return o.map(r=>{let s=r.lastIndexOf("="),c=s===-1?void 0:r.slice(0,s).trim();if(c!==void 0&&c.length===0)throw I(i(r),"the item id before = is empty");let a=s===-1?r:r.slice(s+1);if(!Ae.test(a.trim().toLowerCase()))throw I(i(a),"the revision is not a 64-character hexadecimal item_hash");let l=Ne(a);return c===void 0?{itemHash:l}:{id:c,itemHash:l}})})}async function Te(e,n){let t=await xe(e),o=Q(t,_e()).type_to_folder,i=await k(e,n,t.id_prefix,t.item_format,o);if(i){let{document:r}=await E(i,{schema:t.schema});if(r.metadata.id!==await F(i.itemPath,i.id))throw new u(`Item file ${i.id} embeds the id ${r.metadata.id}; no revision can be bound to an item whose identity is in conflict.`,p.CONFLICT,{code:"item_identity_conflict",item_id:i.id,required:`Repair ${i.id}'s identity first (pm validate reports it; pm restore ${i.id} <version> recovers a recorded state), then read its item_hash again.`});return{id:r.metadata.id,document:r}}try{return{id:(await ke(e,n,t,o)).id,document:W}}catch{throw await Ie(e,n,t.id_prefix,o)}}function K(e){return ee(e.cwd??process.cwd(),e.pmRoot)}async function Ft(e,n={}){let t=await Te(K(n),e);return{id:t.id,item_hash:se(t.document)}}async function Be(e,n,t){let o=[];for(let i of n){let r=i.id??t;if(r===void 0||r.trim().length===0)throw new u("A bare expected revision needs an item to bind to.",p.USAGE,{code:"expect_hash_target_required",required:"This command has no single item argument; name each target as --expect-hash <id>=<item_hash>.",examples:["--expect-hash pm-a1b2=<item_hash>"]});o.push({id:(await Te(e,r)).id,itemHash:i.itemHash})}return o}function je(e){return[...new Set(e.patch.map(n=>{let t=n.path.split("/");return String(t[1]==="metadata"?t[2]:t[1])}))].sort()}async function Xe(e,n,t){let o;try{o=await re(te(e,n),n)}catch{return}let i=-1;for(let c=o.length-1;c>=0;c-=1){let a=o[c];if(a.after_hash===t){i=c+1;break}if(a.before_hash===t){i=c;break}}if(i===-1)return{expected_revision_recorded:!1,changes_since:[],changes_since_omitted:0};let r=o.slice(i),s=r.slice(-Ye);return{expected_revision_recorded:!0,changes_since:s.map(c=>({ts:c.ts,op:c.op,author:c.author,fields:je(c)})),changes_since_omitted:r.length-s.length}}async function Kt(e,n){if(!R(e))return{};let t=await Oe(e,n);return{error_code:Se,expected_revision:String(t.context.expected_revision),current_revision:String(t.context.current_revision),details:t.context.details}}function R(e){return ye(e)&&e.context.code===Se}function Ut(e){let n=e.find(t=>R(t));if(n!==void 0)throw n}function Gt(){return new u("--expect-hash cannot guard an invocation an extension override rewrote: which item it writes is not provable.",p.USAGE,{code:"expect_hash_invocation_rewritten",required:"Run the command without the rewriting extension (--no-extensions), or drop --expect-hash.",why:"An extension parser or preflight override changed this invocation's tracker or arguments, and final dispatch, the extension SDK client and the guard do not share one rewritten view."})}function Je(e,n){if(n===void 0||!R(e)||typeof e.context.item_id!="string"||me(e))return e;let t=e.context.reason===ue;if(!t&&e.context.reason!==le)return e;let o=he(T(e,new u(e.message,e.exitCode,{...e.context,...fe(e.context.item_id,t,n)})));return o.stack=e.stack,o}async function Oe(e,n,t){if(!pe(e,n))return e;let o=Je(e,t);if(!R(o)||o.context.details!==void 0)return o;let i=o.context.item_id,r=o.context.expected_revision;if(typeof i!="string"||typeof r!="string")return o;let s;try{s=await Xe(n,i,r)}catch{return o}if(s===void 0)return o;let c={expected_revision_recorded:s.expected_revision_recorded,changes_since:s.changes_since.map(l=>({ts:l.ts,op:l.op,author:l.author,fields:[...l.fields]})),changes_since_omitted:s.changes_since_omitted},a=T(o,new u(o.message,o.exitCode,{...o.context,details:c}));return a.stack=o.stack,a}async function Le(e,n,t){try{return{result:await ce(e,n),...ae(e)}}catch(o){throw e.pmRoot===void 0?o:await Oe(o,e.pmRoot,t)}}function Qe(e){return e.cwd===void 0&&e.pmRoot===void 0?void 0:{scopeArgs:["--pm-path",K(e)]}}async function qt(e,n,t={}){return Le(await Ze(e,t),n,Qe(t))}async function Ze(e,n={}){let t=K(n),o=e.map(({id:r,itemHash:s})=>({id:r,itemHash:Ne(s)})),i=A();return N(i,t,await Be(t,o)),i}function zt(e){let n=de(e);return n===void 0||n.length>0}function et(e){return`expect_hash_unchecked:${e}:no_locked_write_reached_this_item`}function tt(e,n={}){let t=B(e);if(!O(e))throw nt(t);if((t==="test"||t==="test-all")&&n.background===!0)throw new u(`--expect-hash cannot guard ${t} --background: the worker runs in another process.`,p.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${t} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function nt(e){return new u(`--expect-hash guards item writes, and ${e} is not a mutation.`,p.USAGE,{code:"expect_hash_requires_mutation",required:"Use --expect-hash (MCP/SDK expectHash) only on a command or action that writes items."})}function ot(e,n){if(n.length===0||typeof e!="object"||e===null||Array.isArray(e))return e;let t=e,o=Array.isArray(t.warnings)?t.warnings:[];return{...t,warnings:[...o,...n.map(et)]}}async function Vt(e){let n=e.expectHash;if(n!==void 0&&typeof n!="string"&&!(Array.isArray(n)&&n.every(r=>typeof r=="string")))throw I(JSON.stringify(n)??String(n),"expected a string or an array of strings");let t=We(n);if(t.length===0)return e.run();tt(e.action,{background:e.background===!0||e.options?.background===!0});let o=A();N(o,e.pmRoot,await Be(e.pmRoot,t,e.defaultId));let i=await Le(o,e.run,e.invocation);return ot(i.result,i.unchecked)}export{O as a,D as b,$e as c,_ as d,C as e,Ce as f,P as g,Fe as h,Ke as i,qe as j,wt as k,Se as l,Ye as m,Ne as n,We as o,Ft as p,Be as q,Xe as r,Kt as s,R as t,Ut as u,Gt as v,Je as w,Oe as x,Le as y,qt as z,Ze as A,zt as B,et as C,tt as D,nt as E,Vt as F};
2
+ //# sourceMappingURL=chunk-QDV7S2QS.js.map