@unbrained/pm-cli 2026.11.10 → 2026.11.11

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 (120) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +12 -0
  3. package/dist/cli/commander-usage.js +2 -2
  4. package/dist/cli/error-guidance.js +3 -3
  5. package/dist/cli/help-json-payload.js +1 -1
  6. package/dist/cli/main.js +4 -4
  7. package/dist/cli/runtime/refusal-credential-redaction.js +2 -0
  8. package/dist/cli-bundle/bundle-manifest.json +1 -1
  9. package/dist/cli-bundle/chunks/{chunk-NNE63MSM.js → chunk-4RHXGQMK.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-YSWD2NXB.js → chunk-5N3JMGXU.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-TBBWPEF5.js → chunk-DIWTFDU7.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-OJ2KEDUX.js → chunk-DV7WBAKQ.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-F6FBGLR7.js → chunk-EBAHNZJT.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-BSJSGDA3.js → chunk-FM375BHH.js} +2 -2
  15. package/dist/cli-bundle/chunks/{chunk-F7P2NZEG.js → chunk-GOLQYO6M.js} +4 -4
  16. package/dist/cli-bundle/chunks/chunk-GZ52WAY2.js +124 -0
  17. package/dist/cli-bundle/chunks/{chunk-EHDGHFMJ.js → chunk-JESMEJTD.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-CZETQYKO.js → chunk-JLQ7O6UV.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-FYD6LSJA.js → chunk-L3SA3354.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-U7LILCUN.js → chunk-NIOOJ3AG.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-WNEUWDUE.js → chunk-PZI6CR24.js} +46 -46
  22. package/dist/cli-bundle/chunks/{chunk-NZAFLDSH.js → chunk-QCTA2UFR.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-4FLAKTZW.js → chunk-SPERPX27.js} +2 -2
  24. package/dist/cli-bundle/chunks/{chunk-T2MNRM3S.js → chunk-SVVFJPNW.js} +2 -2
  25. package/dist/cli-bundle/chunks/{chunk-5CAMQHEW.js → chunk-WEAF3OY4.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-UL64P6MR.js → chunk-WWW5WHHJ.js} +2 -2
  27. package/dist/cli-bundle/chunks/{chunk-X7NM5HVQ.js → chunk-XJUYJXHZ.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-L4WWG2H6.js → chunk-XN2BRWDD.js} +2 -2
  29. package/dist/cli-bundle/chunks/chunk-Z4YEH7VQ.js +2 -0
  30. package/dist/cli-bundle/chunks/{chunk-7NAAW5EX.js → chunk-ZJDYBXMC.js} +2 -2
  31. package/dist/cli-bundle/chunks/{chunk-4AASUCHO.js → chunk-ZSL6U53K.js} +2 -2
  32. package/dist/cli-bundle/chunks/{item-revision-M7KXLQXF.js → item-revision-LNIHK36Q.js} +2 -2
  33. package/dist/cli-bundle/chunks/item-transaction-TMUYPSMR.js +2 -0
  34. package/dist/cli-bundle/chunks/{mutation-admission-374UR7NI.js → mutation-admission-WZY22LVH.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-list-query-GSB7PP5P.js → register-list-query-DYGPLVRL.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-mutation-ZBF6ITYK.js → register-mutation-MP5JCBAJ.js} +2 -2
  37. package/dist/cli-bundle/chunks/{register-operations-PWF6GOHE.js → register-operations-QEASK3EF.js} +2 -2
  38. package/dist/cli-bundle/chunks/{register-setup-QDZ2Y3CI.js → register-setup-G66U2WFV.js} +2 -2
  39. package/dist/cli-bundle/chunks/{stage-67WGPKPH.js → stage-VIDXGF3T.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/{chunk-WK773UVA.js → chunk-2ZS3I5ZP.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/chunk-33EK522E.js +26 -0
  42. package/dist/cli-bundle/focused-chunks/{chunk-BE2GK2G7.js → chunk-3A6XMQZJ.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-PAGW6A2X.js → chunk-3FN4ON2Z.js} +2 -2
  44. package/dist/cli-bundle/focused-chunks/{chunk-3DWNH72D.js → chunk-3SH3L3DB.js} +2 -2
  45. package/dist/cli-bundle/focused-chunks/{chunk-ALLOWZSH.js → chunk-6ICHSVEY.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-QK7FX4O5.js → chunk-6TJXTKZD.js} +4 -4
  47. package/dist/cli-bundle/focused-chunks/{chunk-QHGGO7SY.js → chunk-AXPRCCYM.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-UIZVD36C.js → chunk-DW5S67LO.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-HTMQDNVC.js → chunk-GBW2EAAG.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-ZBOCYFBE.js → chunk-HIKZYZ26.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-QCHCEFTO.js → chunk-JYWVRXLD.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-M5FZTPFA.js +2 -0
  53. package/dist/cli-bundle/focused-chunks/{chunk-2SQUWQP3.js → chunk-MK7UQEE5.js} +18 -18
  54. package/dist/cli-bundle/focused-chunks/{chunk-2Y4H4LIX.js → chunk-NMU3QFAU.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-LY3JXL25.js → chunk-NP5C2TQM.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-RFMKS7VD.js → chunk-NSOXVVQX.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{chunk-WJHDUON5.js → chunk-NY65XTX7.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-67M7E2Z3.js → chunk-P6KYUJD4.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{chunk-LWMPQRJT.js → chunk-UCUESVFW.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{chunk-NZQYHPUN.js → chunk-V27M5UQH.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/{chunk-3K2MYE7R.js → chunk-VVGXPF4W.js} +2 -2
  62. package/dist/cli-bundle/focused-chunks/{item-revision-XC4ZJ7MY.js → item-revision-B3BIG66B.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{item-transaction-CVGK4RJP.js → item-transaction-4JDWOXNB.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{mutation-admission-N27D5H64.js → mutation-admission-577MXOGD.js} +2 -2
  65. package/dist/cli-bundle/focused-chunks/{stage-KPK2UHVO.js → stage-EKYWEU2Y.js} +2 -2
  66. package/dist/cli-bundle/main.js +32 -32
  67. package/dist/cli-bundle/sdk-authoring.js +1 -1
  68. package/dist/cli-bundle/sdk-contracts.js +1 -1
  69. package/dist/cli-bundle/sdk-core.js +1 -1
  70. package/dist/cli-bundle/sdk-governance.js +1 -1
  71. package/dist/cli-bundle/sdk-graph.js +1 -1
  72. package/dist/cli-bundle/sdk-merge.js +57 -57
  73. package/dist/cli-bundle/sdk-query.js +1 -1
  74. package/dist/cli-bundle/sdk-runtime.js +1 -1
  75. package/dist/cli-bundle/sdk-testing.js +1 -1
  76. package/dist/cli-bundle/sdk.js +11 -11
  77. package/dist/core/sentry/instrument.js +1 -1
  78. package/dist/core/shared/secret-rules.d.ts +18 -2
  79. package/dist/core/shared/secret-rules.js +4 -2
  80. package/dist/core/shared/url-credentials.d.ts +37 -0
  81. package/dist/core/shared/url-credentials.js +2 -0
  82. package/dist/core/telemetry/runtime.js +2 -2
  83. package/dist/sdk/command-line.d.ts +1 -1
  84. package/dist/sdk/command-line.js +1 -1
  85. package/dist/sdk/index.d.ts +1 -1
  86. package/dist/sdk/index.js +1 -1
  87. package/dist/sdk/lifecycle/item-revision.js +1 -1
  88. package/dist/sdk/public-surface.json +1 -1
  89. package/docs/CODEX_PLUGIN.md +2 -1
  90. package/docs/CONFIGURATION.md +16 -0
  91. package/docs/MUTATION_INTEGRITY.md +65 -0
  92. package/docs/README.md +2 -2
  93. package/docs/SDK.md +16 -0
  94. package/marketplace.json +1 -1
  95. package/package.json +2 -1
  96. package/packages/pm-beads/package.json +1 -1
  97. package/packages/pm-calendar/package.json +1 -1
  98. package/packages/pm-command-kit/package.json +1 -1
  99. package/packages/pm-digital-twin/package.json +1 -1
  100. package/packages/pm-governance-audit/package.json +1 -1
  101. package/packages/pm-guide-shell/package.json +1 -1
  102. package/packages/pm-kanban/package.json +1 -1
  103. package/packages/pm-lifecycle-hooks/package.json +1 -1
  104. package/packages/pm-linked-test-adapters/package.json +1 -1
  105. package/packages/pm-search-advanced/package.json +1 -1
  106. package/packages/pm-templates/package.json +1 -1
  107. package/packages/pm-todos/package.json +1 -1
  108. package/packages/pm-vcs/package.json +1 -1
  109. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  110. package/plugins/pm-claude/package.json +1 -1
  111. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  112. package/plugins/pm-codex/package.json +1 -1
  113. package/plugins/pm-codex/plugin.json +1 -1
  114. package/runtime-dependencies.json +1 -1
  115. package/dist/cli-bundle/chunks/chunk-D727C4RO.js +0 -122
  116. package/dist/cli-bundle/chunks/chunk-UFPLZ6LZ.js +0 -2
  117. package/dist/cli-bundle/chunks/item-transaction-4N5P34GO.js +0 -2
  118. package/dist/cli-bundle/focused-chunks/chunk-56MIAFEN.js +0 -24
  119. package/dist/cli-bundle/focused-chunks/chunk-U7HWWEJ2.js +0 -2
  120. package/docs/CHATGPT_CODEX_PLUGIN_IMPLEMENTATION.md +0 -776
@@ -1,4 +1,4 @@
1
- import{$a as _e,E as ze,F as Ht,Ma as Xe,Pa as Ge,Qa as Ye,R as J,Ra as Z,S as Wt,T as Q,Za as Ve,hb as Yt,qb as Vt,ua as zt,xa as Xt,yb as Kt,za as Gt,zb as ge}from"./chunk-ZBOCYFBE.js";import{Ac as We,Ba as je,Ca as Le,Da as k,H as Tt,Ia as At,Jc as x,Oa as Ft,Od as Lt,Pd as Be,Sa as Mt,Ta as Pt,Xe as Bt,a as fe,ac as jt,ce as $t,de as Ut,na as Ot,oa as Dt,qc as q,ra as kt,sc as $e,tc as ye,uc as $,vc as Ue,wa as pe,wc as he,xc as He,ya as Nt}from"./chunk-2SQUWQP3.js";import{A as m,B as xt,C as K,E as L,I as A,m as Rt,t as j,y as Pe,z as f}from"./chunk-G6ERMFJ5.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();var U=new Set(Rt),we=Object.freeze({get size(){return U.size},has(e){return U.has(e)},entries(){return U.entries()},keys(){return U.keys()},values(){return U.values()},forEach(e,t){U.forEach(i=>e.call(t,i,i,we))},[Symbol.iterator](){return U.values()}});function qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Jt(e){return typeof e!="string"?null:Tt(e)}function qi(e){try{return structuredClone(e)}catch{return e}}function Ji(e){let t=e.trim(),i=t.indexOf("=");if(i<=0)throw new m(`--field entries must use name=value syntax, received: ${e}`,f.USAGE);let o=t.slice(0,i).trim(),n=t.slice(i+1);return{key:o,value:n}}function Qi(e,t,i){try{let o=JSON.parse(e);if(i==="array"&&Array.isArray(o)||i==="object"&&typeof o=="object"&&o!==null&&!Array.isArray(o))return o}catch{}throw new m(`--field ${t}=... must be valid JSON ${i}`,f.USAGE)}function Zi(e,t,i){if(t==="string")return i;if(t==="number"){let o=i.trim();if(o.length===0)throw new m(`--field ${e}=... must be a number`,f.USAGE);let n=Number(o);if(!Number.isFinite(n))throw new m(`--field ${e}=... must be a number`,f.USAGE);return n}if(t==="boolean"){let o=i.trim().toLowerCase();if(o==="true"||o==="1"||o==="yes")return!0;if(o==="false"||o==="0"||o==="no")return!1;throw new m(`--field ${e}=... must be one of true|false|1|0|yes|no`,f.USAGE)}return t==="string_array"?i.split(/[\n,|]/u).map(o=>o.trim()).filter(o=>o.length>0):Qi(i,e,t)}function Ke(e){let t=new Map;if(!e)return t;for(let i of e.item_fields)for(let o of i.fields){let n=qt(o.name),r=Jt(o.type);if(!n||!r)continue;let s=t.get(n);if(s&&s.type!==r)throw new m(`Extension item field "${n}" is declared with conflicting types: ${s.type}, ${r}`,f.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(n,{name:n,type:r})}return t}function Qt(e){if(we.has(e))throw new m(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...we].sort((t,i)=>t.localeCompare(i)).join(", ")}.`,f.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function be(e){return[...Ke(e).keys()].sort((t,i)=>t.localeCompare(i))}function ar(e,t,i,o){if(!e||e.length===0)return{};let n=Ke(t),r={};for(let s of e){let{key:a,value:d}=Ji(s),c=n.get(a);if(!c)throw eo(a,n,i,o);Qt(c.name),r[c.name]=Zi(c.name,c.type,d)}return r}function eo(e,t,i,o){if(we.has(e)){let s=i?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new m(`--field ${e} is a core item field, not an extension field`,f.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}let n=o?.(e);if(n!==void 0){let s=n.recovery?.suggested_flags?.[0];return new m(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,f.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...n})}let r=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new m(`--field ${e} is not declared by an active extension item-field registration`,f.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:r.length>0?[`Use one of the declared fields: ${r.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function to(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(i=>typeof i=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function io(e,t){return!t||t.length===0?!0:t.some(i=>Object.is(i,e))}function cr(e,t,i={}){if(t){Ke(t);for(let o of t.item_fields)for(let n of o.fields){let r=qt(n.name);if(!r)continue;Qt(r),!(r in e)&&!i.skipDefaultFields?.has(r)&&Object.prototype.hasOwnProperty.call(n,"default")&&(e[r]=qi(n.default));let s=e[r];if(s===void 0)continue;let a=Jt(n.type);if(a&&!to(s,a))throw new TypeError(`Item field "${r}" must be of type ${a}`);let d=Array.isArray(n.values)?n.values:void 0;if(!io(s,d))throw new TypeError(`Item field "${r}" must match one of the configured allowed values`)}}}import oo from"node:crypto";import Ee from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function ei(e){let t=[],i=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,s=n>=97&&n<=122;if(!r&&!s){i=t.length>0;continue}i&&(t.push("-"),i=!1),t.push(o)}return t.length===0?"pm-":`${t.join("")}-`}function ee(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function te(e,t){let i=ei(t),o=ee(e);return o.startsWith(i)?o:`${i}${o}`}function no(e){let t=Lt(e);if(t!==void 0)return t;let i="";for(let o=0;o<e;o+=1)i+=oo.randomInt(0,36).toString(36);return i}async function ro(e,t,i){let o=[...new Set(Object.values(i))].flatMap(n=>[Ee.join(e,n,`${t}.md`),Ee.join(e,n,`${t}.toon`)]);return o.push(Ee.join(e,"history",`${t}.jsonl`)),(await Promise.all(o.map(n=>K(n)))).some(Boolean)}var Zt=4,ti=12;function so(e){return typeof e!="number"||!Number.isFinite(e)?Zt:Math.min(ti,Math.max(Zt,Math.trunc(e)))}async function yr(e,t,i={}){let o=so(i.tokenLength),n=Math.min(o+6,ti),r=0;for(;o<=n;){for(let s=0;s<32;s+=1){let a=`${ei(t)}${no(o)}`;if(!await(i.probeExisting===!1?K(Ee.join(e,"history",`${a}.jsonl`)):ro(e,a,i.typeToFolder??j)))return a;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function ie(e,t=!1){let i=e[0];if(i?.op!=="history_compact_baseline")return 0;let o=i.context?.history_compaction,n=typeof o=="object"&&o!==null&&"version_offset"in o?o.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(t)return null;throw new m("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",f.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}import ii from"node:fs/promises";import oe from"node:path";import{isUtf8 as ao}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var co=1048576,lo=4194304;async function oi(e,t){let i=oe.dirname(e);for(;i!==oe.parse(e).root;){let n=await ii.stat(i).catch(r=>{if(L(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new m("Workflow policy storage ancestor must be a directory.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}i=oe.dirname(i)}let o=await ii.open(e,"r").catch(n=>{if(L(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(t,n)+1),s=0;for(;s<r.length;){let a=await o.read(r,s,r.length-s,s);if(a.bytesRead===0)break;s+=a.bytesRead}if(s===r.length||!ao(r.subarray(0,s)))throw new m("Workflow policy input exceeds its byte bound or is not valid UTF-8.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,s)}finally{await o.close()}}function uo(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let t;try{t=JSON.parse(e)}catch{throw new m("schema/policies.json must contain valid JSON.",f.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return Ft(t)}async function mo(e){return uo(await oi(oe.join(e,"schema","policies.json"),co))}async function fo(e,t){let i=await oi(k(e,t),lo);if(i===null)return[];let o;try{if(o=i.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!_e(o).ok)throw new Error("invalid chain")}catch{throw new m("Approval evidence requires a valid item history chain.",f.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${t} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let s=r;return typeof s.policy_fingerprint!="string"||typeof s.content_fingerprint!="string"?[]:[{policy_fingerprint:s.policy_fingerprint,content_fingerprint:s.content_fingerprint,author:n.author}]})}async function po(e,t,i){let o=i.before?.status!==i.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&Mt(s,i)),n=i.before?.id??i.after?.id,r=o&&typeof n=="string"?await fo(e,n):[];return Pt(t,{...i,approvals:r})}async function qe(e){let t=await mo(e.pmRoot),i=await po(e.pmRoot,t,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(i.allowed)return i;let o=i.decisions.filter(l=>!l.satisfied&&l.effect==="refuse"),n=[],r="";if(!e.dryRun)try{let l=await Yt({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:i.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});n.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:l.entry.record_hash}),r=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(l){let h=new m("Workflow policy refusal could not be recorded in workspace history.",f.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw h.cause=l,h}let s=o.slice(0,3).map(l=>({policy_id:l.policy_id,rule:l.rule,description:t.policies.find(h=>h.id===l.policy_id).description,missing_fields:l.missing_fields})),a=[...new Set(s.flatMap(l=>l.missing_fields))],d=s.map(l=>`${l.policy_id} (${l.rule})`).join(", "),c=o.length>3?` and ${o.length-3} more`:"",y=e.after?.metadata.id??e.before.metadata.id,u=a.map(l=>{if(e.before===null)return`Supply ${l} in the original ${e.operation} request, then retry; the item was not created.`;let h=Ot("update",l);return h===void 0?`Supply ${l} using its declared SDK or package mutation contract, then retry.`:x(["update",y,Dt("update",h),`<${l}>`,"--pm-path",oe.resolve(e.pmRoot)])});throw new m(`Workflow policy refused ${e.operation}: ${d}${c}.${a.length?` Missing: ${a.join(", ")}.`:""}${r}`,f.CONFLICT,{code:"workflow_policy_refused",side_effects:n,reason:s.map(l=>l.policy_id).join(","),policy_violations:s,policy_violation_count:o.length,required:a.length?`Supply missing fields: ${a.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:s.map(l=>l.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:a},nextSteps:[...u,...new Set(o.slice(0,3).filter(l=>l.missing_fields.length===0).map(l=>l.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as yo}from"node:async_hooks";import{channel as ho}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Je=new yo,Qe=ho("@unbrained/pm-cli/item-metadata-enumeration/v1");function ve(e){Qe.publish(e)}async function Mr(e){let t={enumeration_calls:0,metadata_rows:0},i=o=>{Je.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=o)};Qe.subscribe(i);try{return{result:await Je.run([...Je.getStore()??[],t],e),work:{...t}}}finally{Qe.unsubscribe(i)}}import{AsyncLocalStorage as ni}from"node:async_hooks";import{realpathSync as _o}from"node:fs";import et from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();var Ze=new ni;function Xr(e,t){return Ze.run([...Ze.getStore()??[],{...e,pmRoot:et.resolve(e.pmRoot)}],t)}var go=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),wo=globalThis,ne=wo[go]??=new ni;function X(e){let t=et.resolve(e);try{return _o.native(t)}catch{return t}}function Gr(){return{entries:new Map}}function Yr(e,t){return ne.run([...ne.getStore()??[],e],t)}function Vr(e,t,i){let o=X(t);if(e.pmRoot!==void 0&&e.pmRoot!==o)throw new m("An expected-revision scope is already bound to another tracker.",f.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=o;for(let{id:n,itemHash:r}of i){let s=e.entries.get(n);if(s!==void 0&&s.declared!==r)throw new m(`Item ${n} has two different expected revisions.`,f.USAGE,{code:"expected_revision_duplicate",item_id:n,required:"Declare at most one expected revision per item."});e.entries.set(n,s??{declared:r,expected:r,checked:!1,committed:!1})}}function Kr(e){let t=[...e.entries.entries()];return{checked:t.filter(([,i])=>i.checked).map(([i])=>i),unchecked:t.filter(([,i])=>!i.checked).map(([i])=>i)}}function tt(e,t){let i=ne.getStore()??[];if(i.length===0)return[];let o=X(e),n=new Set(t.filter(r=>typeof r=="string"));return[...new Set(i.flatMap(r=>r.pmRoot===o?[...n].flatMap(s=>r.entries.get(s)??[]):[]))]}function qr(e){let t=ne.getStore()??[];if(t.length===0)return[];let i=X(e),o=new Map;for(let n of t)if(n.pmRoot===i)for(let[r,s]of n.entries){if(s.expected!==s.declared)return;o.set(r,(o.get(r)??new Set).add(s.expected))}if(![...o.values()].some(n=>n.size>1))return[...o].map(([n,r])=>`${n}=${[...r][0]}`)}function Jr(e){let t=X(e);return(ne.getStore()??[]).some(i=>i.pmRoot===t&&i.entries.size>0)}function bo(e,t,i){let o=tt(e,[i,t.metadata.id]);o.length>0&&ai(o,i,Xe(t),!1,e)}function Qr(e,t,i){let o=tt(e,[t]);o.length>0&&ai(o,t,At(i),!0,e)}var Eo="revision_changed",vo="document_unreadable";function Io(e,t,i={}){let o=[...i.scopeArgs??[]],n=[...i.outputArgs??["--json"]],r=x([...o,"get",e,...n]),s=x([...o,"history",e,"--limit","5",...n]);return{required:t?`Recover ${e} without --expect-hash (${x([...o,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${r} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[x([...o,"get",e,"--fields","item_hash",...n]),s],nextSteps:[r,s]}}var Co=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),So=globalThis,it=So[Co]??=new WeakMap,To=8;function ri(e){for(let t of si(e)){let i=it.get(t);if(i!==void 0)return i}}function*si(e){let t=e;for(let i=0;i<To&&typeof t=="object"&&t!==null;i+=1){yield t;try{t=t.cause}catch{return}}}function ai(e,t,i,o,n){for(let r of e)if(r.checked=!0,!(!o&&r.expected===i))throw Do(n,new m(`Item ${t} is no longer at the expected revision ${r.expected.slice(0,12)}${o?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${r.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,f.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:r.expected,current_revision:i,reason:o?vo:Eo,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...Io(t,o)}))}function Zr(e,t){let i=ri(e);return i===void 0||i===X(t)}var Ro=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),xo=globalThis,ot=xo[Ro]??=new WeakSet;function Oo(e){for(let t of si(e))if(ot.has(t))return!0;return!1}function es(e){return ot.add(e),e}function ts(e,t){let i=ri(e);return i!==void 0&&it.set(t,i),Oo(e)&&ot.add(t),t}function Do(e,t){return it.set(t,X(e)),t}function nt(e,t,i=t.metadata.id){bo(e,t,i);for(let o of rt(e,[i,t.metadata.id]))o.validate(t)}function rt(e,t){let i=et.resolve(e);return(Ze.getStore()??[]).filter(o=>o.pmRoot===i&&t.includes(o.id))}function st(e,t,i=t.metadata.id,o=[],n){let r=tt(e,[i,t.metadata.id,...o]);if(r.length>0){let s=n??Xe(t);for(let a of r)a.expected=s,a.committed=!0}for(let s of rt(e,[i,t.metadata.id,...o]))s.committed?.(t)}function ci(e,t){return Object.assign({},...rt(e,t).map(i=>i.historyContext))}import H from"node:fs/promises";import li from"node:path";import{randomUUID as ko}from"node:crypto";import{createRequire as No}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ao="metadata-query-index.sqlite",re="5",at;function se(){return at!==void 0||(at=Gt(process.versions.node,No(import.meta.url))),at}function di(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function G(e){return li.join(e,"runtime",Ao)}function Fo(e){e.exec(`
1
+ import{$a as _e,E as ze,F as Ht,Ma as Xe,Pa as Ge,Qa as Ye,R as J,Ra as Z,S as Wt,T as Q,Za as Ve,hb as Yt,qb as Vt,ua as zt,xa as Xt,yb as Kt,za as Gt,zb as ge}from"./chunk-HIKZYZ26.js";import{Ac as We,Ba as je,Ca as Le,Da as k,H as Tt,Ia as At,Jc as x,Oa as Ft,Rd as Lt,Sa as Mt,Sd as Be,Ta as Pt,_e as Bt,a as fe,ac as jt,fe as $t,ge as Ut,na as Ot,oa as Dt,qc as q,ra as kt,sc as $e,tc as ye,uc as $,vc as Ue,wa as pe,wc as he,xc as He,ya as Nt}from"./chunk-MK7UQEE5.js";import{A as m,B as xt,C as K,E as L,I as A,m as Rt,t as j,y as Pe,z as f}from"./chunk-G6ERMFJ5.js";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4e02447f-3fb0-5f7c-9512-be2b348fd082")}catch{}})();var U=new Set(Rt),we=Object.freeze({get size(){return U.size},has(e){return U.has(e)},entries(){return U.entries()},keys(){return U.keys()},values(){return U.values()},forEach(e,t){U.forEach(i=>e.call(t,i,i,we))},[Symbol.iterator](){return U.values()}});function qt(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function Jt(e){return typeof e!="string"?null:Tt(e)}function qi(e){try{return structuredClone(e)}catch{return e}}function Ji(e){let t=e.trim(),i=t.indexOf("=");if(i<=0)throw new m(`--field entries must use name=value syntax, received: ${e}`,f.USAGE);let o=t.slice(0,i).trim(),n=t.slice(i+1);return{key:o,value:n}}function Qi(e,t,i){try{let o=JSON.parse(e);if(i==="array"&&Array.isArray(o)||i==="object"&&typeof o=="object"&&o!==null&&!Array.isArray(o))return o}catch{}throw new m(`--field ${t}=... must be valid JSON ${i}`,f.USAGE)}function Zi(e,t,i){if(t==="string")return i;if(t==="number"){let o=i.trim();if(o.length===0)throw new m(`--field ${e}=... must be a number`,f.USAGE);let n=Number(o);if(!Number.isFinite(n))throw new m(`--field ${e}=... must be a number`,f.USAGE);return n}if(t==="boolean"){let o=i.trim().toLowerCase();if(o==="true"||o==="1"||o==="yes")return!0;if(o==="false"||o==="0"||o==="no")return!1;throw new m(`--field ${e}=... must be one of true|false|1|0|yes|no`,f.USAGE)}return t==="string_array"?i.split(/[\n,|]/u).map(o=>o.trim()).filter(o=>o.length>0):Qi(i,e,t)}function Ke(e){let t=new Map;if(!e)return t;for(let i of e.item_fields)for(let o of i.fields){let n=qt(o.name),r=Jt(o.type);if(!n||!r)continue;let s=t.get(n);if(s&&s.type!==r)throw new m(`Extension item field "${n}" is declared with conflicting types: ${s.type}, ${r}`,f.USAGE,{code:"extension_item_field_type_conflict",nextSteps:["Make every active extension declaration for this field use the same type."]});t.set(n,{name:n,type:r})}return t}function Qt(e){if(we.has(e))throw new m(`Extension item field "${e}" collides with built-in item metadata "${e}"; rename the extension field with an extension-specific prefix. Reserved fields: ${[...we].sort((t,i)=>t.localeCompare(i)).join(", ")}.`,f.USAGE,{code:"extension_item_field_reserved",nextSteps:["Rename the extension item field, preferably with an extension-specific prefix."]})}function be(e){return[...Ke(e).keys()].sort((t,i)=>t.localeCompare(i))}function ar(e,t,i,o){if(!e||e.length===0)return{};let n=Ke(t),r={};for(let s of e){let{key:a,value:d}=Ji(s),c=n.get(a);if(!c)throw eo(a,n,i,o);Qt(c.name),r[c.name]=Zi(c.name,c.type,d)}return r}function eo(e,t,i,o){if(we.has(e)){let s=i?.(e)??{recovery:{provided_fields:[e]},nextSteps:["Core metadata has no generic --field mutation path. Use the owning lifecycle, evidence, or importer API; inspect pm update <id> --help for declared mutation flags."]};return new m(`--field ${e} is a core item field, not an extension field`,f.USAGE,{code:"core_item_field_requires_dedicated_flag",field:e,...s})}let n=o?.(e);if(n!==void 0){let s=n.recovery?.suggested_flags?.[0];return new m(s===void 0?`--field ${e} is a project-schema field, not an extension field`:`--field ${e} is a project-schema field; set it with its declared flag ${s}`,f.USAGE,{code:"project_schema_field_requires_declared_flag",field:e,changed:!1,...n})}let r=[...t.keys()].sort((s,a)=>s.localeCompare(a));return new m(`--field ${e} is not declared by an active extension item-field registration`,f.USAGE,{code:"extension_item_field_unknown",field:e,recovery:{provided_fields:[e]},nextSteps:r.length>0?[`Use one of the declared fields: ${r.join(", ")}`]:["Activate an extension that calls registerItemFields before setting extension fields."]})}function to(e,t){return t==="string"?typeof e=="string":t==="number"?typeof e=="number"&&Number.isFinite(e):t==="boolean"?typeof e=="boolean":t==="array"?Array.isArray(e):t==="string_array"?Array.isArray(e)&&e.every(i=>typeof i=="string"):typeof e=="object"&&e!==null&&!Array.isArray(e)}function io(e,t){return!t||t.length===0?!0:t.some(i=>Object.is(i,e))}function cr(e,t,i={}){if(t){Ke(t);for(let o of t.item_fields)for(let n of o.fields){let r=qt(n.name);if(!r)continue;Qt(r),!(r in e)&&!i.skipDefaultFields?.has(r)&&Object.prototype.hasOwnProperty.call(n,"default")&&(e[r]=qi(n.default));let s=e[r];if(s===void 0)continue;let a=Jt(n.type);if(a&&!to(s,a))throw new TypeError(`Item field "${r}" must be of type ${a}`);let d=Array.isArray(n.values)?n.values:void 0;if(!io(s,d))throw new TypeError(`Item field "${r}" must match one of the configured allowed values`)}}}import oo from"node:crypto";import Ee from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="664124e5-715d-5f86-ae69-89f203db76c3")}catch{}})();function ei(e){let t=[],i=!1;for(let o of(e??"").toLowerCase()){let n=o.charCodeAt(0),r=n>=48&&n<=57,s=n>=97&&n<=122;if(!r&&!s){i=t.length>0;continue}i&&(t.push("-"),i=!1),t.push(o)}return t.length===0?"pm-":`${t.join("")}-`}function ee(e){let t=e.trim().toLowerCase();return t.startsWith("#")&&(t=t.slice(1)),t}function te(e,t){let i=ei(t),o=ee(e);return o.startsWith(i)?o:`${i}${o}`}function no(e){let t=Lt(e);if(t!==void 0)return t;let i="";for(let o=0;o<e;o+=1)i+=oo.randomInt(0,36).toString(36);return i}async function ro(e,t,i){let o=[...new Set(Object.values(i))].flatMap(n=>[Ee.join(e,n,`${t}.md`),Ee.join(e,n,`${t}.toon`)]);return o.push(Ee.join(e,"history",`${t}.jsonl`)),(await Promise.all(o.map(n=>K(n)))).some(Boolean)}var Zt=4,ti=12;function so(e){return typeof e!="number"||!Number.isFinite(e)?Zt:Math.min(ti,Math.max(Zt,Math.trunc(e)))}async function yr(e,t,i={}){let o=so(i.tokenLength),n=Math.min(o+6,ti),r=0;for(;o<=n;){for(let s=0;s<32;s+=1){let a=`${ei(t)}${no(o)}`;if(!await(i.probeExisting===!1?K(Ee.join(e,"history",`${a}.jsonl`)):ro(e,a,i.typeToFolder??j)))return a;r+=1}o+=1}throw new Error(`Unable to generate unique id after ${r} attempts`)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="5db05e2f-4742-526b-b1c8-b97ff302b40e")}catch{}})();function ie(e,t=!1){let i=e[0];if(i?.op!=="history_compact_baseline")return 0;let o=i.context?.history_compaction,n=typeof o=="object"&&o!==null&&"version_offset"in o?o.version_offset:void 0;if(typeof n=="number"&&Number.isSafeInteger(n)&&n>=0&&Number.isSafeInteger(n+e.length))return n;if(t)return null;throw new m("This compacted stream has no trustworthy version offset; numeric history addresses are unavailable.",f.USAGE,{code:"history_version_mapping_unavailable",required:"Use a retained timestamp or recover the pre-compaction stream from version control.",nextSteps:["Run pm history <id> --full to inspect the retained timestamps and checkpoint evidence."]})}import ii from"node:fs/promises";import oe from"node:path";import{isUtf8 as ao}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="697f1dbe-8315-5901-ab11-e0c5211dbdbf")}catch{}})();var co=1048576,lo=4194304;async function oi(e,t){let i=oe.dirname(e);for(;i!==oe.parse(e).root;){let n=await ii.stat(i).catch(r=>{if(L(r))return null;throw r});if(n!==null){if(!n.isDirectory())throw new m("Workflow policy storage ancestor must be a directory.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Restore the policy or approval history directory before retrying."]});break}i=oe.dirname(i)}let o=await ii.open(e,"r").catch(n=>{if(L(n))return null;throw n});if(o===null)return null;try{let n=(await o.stat()).size,r=Buffer.alloc(Math.min(t,n)+1),s=0;for(;s<r.length;){let a=await o.read(r,s,r.length-s,s);if(a.bytesRead===0)break;s+=a.bytesRead}if(s===r.length||!ao(r.subarray(0,s)))throw new m("Workflow policy input exceeds its byte bound or is not valid UTF-8.",f.CONFLICT,{code:"workflow_policy_input_unreadable",nextSteps:["Inspect the policy and approval history; reduce the declaration or use verified history compaction before retrying."]});return r.toString("utf8",0,s)}finally{await o.close()}}function uo(e){if(e===null)return{version:1,enforcement:"advise",policies:[]};let t;try{t=JSON.parse(e)}catch{throw new m("schema/policies.json must contain valid JSON.",f.CONFLICT,{code:"workflow_policy_registry_invalid",nextSteps:["Restore valid policy JSON before retrying the mutation."]})}return Ft(t)}async function mo(e){return uo(await oi(oe.join(e,"schema","policies.json"),co))}async function fo(e,t){let i=await oi(k(e,t),lo);if(i===null)return[];let o;try{if(o=i.split(/\r?\n/).filter(n=>n.trim()).map(n=>JSON.parse(n)),!_e(o).ok)throw new Error("invalid chain")}catch{throw new m("Approval evidence requires a valid item history chain.",f.CONFLICT,{code:"workflow_policy_approval_history_invalid",nextSteps:[`Run pm history ${t} --verify before recording or using an approval.`]})}return o.flatMap(n=>{let r=n.context?.workflow_approval;if(n.op!=="policy_approve"||n.record_hash_version!==1||typeof n.record_hash!="string"||typeof r!="object"||r===null)return[];let s=r;return typeof s.policy_fingerprint!="string"||typeof s.content_fingerprint!="string"?[]:[{policy_fingerprint:s.policy_fingerprint,content_fingerprint:s.content_fingerprint,author:n.author}]})}async function po(e,t,i){let o=i.before?.status!==i.after?.status&&t.policies.some(s=>s.rule.kind==="approval"&&Mt(s,i)),n=i.before?.id??i.after?.id,r=o&&typeof n=="string"?await fo(e,n):[];return Pt(t,{...i,approvals:r})}async function qe(e){let t=await mo(e.pmRoot),i=await po(e.pmRoot,t,{operation:e.operation,author:e.author,before:e.before?{...e.before.metadata,body:e.before.body}:null,after:e.after?{...e.after.metadata,body:e.after.body}:null});if(i.allowed)return i;let o=i.decisions.filter(l=>!l.satisfied&&l.effect==="refuse"),n=[],r="";if(!e.dryRun)try{let l=await Yt({pmRoot:e.pmRoot,op:"policy_refused",author:e.author,context:{item_id:e.after?.metadata.id??e.before?.metadata.id,operation:e.operation,workflow_policies:i.decisions},message:"Workflow policy refused a proposed item mutation.",lockTtlSeconds:e.settings.locks.ttl_seconds,lockWaitMs:e.settings.locks.wait_ms});n.push({path:"history/_workspace.jsonl",op:"policy_refused",record_hash:l.entry.record_hash}),r=" Audit appended to tracker-relative history/_workspace.jsonl; retain it with the workspace changes. Each refused attempt records its own audit event."}catch(l){let h=new m("Workflow policy refusal could not be recorded in workspace history.",f.CONFLICT,{code:"workflow_policy_audit_failed",nextSteps:["Resolve workspace-history lock or storage failures, then retry the refused mutation; no item changes were written."]});throw h.cause=l,h}let s=o.slice(0,3).map(l=>({policy_id:l.policy_id,rule:l.rule,description:t.policies.find(h=>h.id===l.policy_id).description,missing_fields:l.missing_fields})),a=[...new Set(s.flatMap(l=>l.missing_fields))],d=s.map(l=>`${l.policy_id} (${l.rule})`).join(", "),c=o.length>3?` and ${o.length-3} more`:"",y=e.after?.metadata.id??e.before.metadata.id,u=a.map(l=>{if(e.before===null)return`Supply ${l} in the original ${e.operation} request, then retry; the item was not created.`;let h=Ot("update",l);return h===void 0?`Supply ${l} using its declared SDK or package mutation contract, then retry.`:x(["update",y,Dt("update",h),`<${l}>`,"--pm-path",oe.resolve(e.pmRoot)])});throw new m(`Workflow policy refused ${e.operation}: ${d}${c}.${a.length?` Missing: ${a.join(", ")}.`:""}${r}`,f.CONFLICT,{code:"workflow_policy_refused",side_effects:n,reason:s.map(l=>l.policy_id).join(","),policy_violations:s,policy_violation_count:o.length,required:a.length?`Supply missing fields: ${a.join(", ")}, then retry the refused mutation.`:"Satisfy the declared workflow policy before retrying.",why:s.map(l=>l.description).filter(Boolean).join(" ")||void 0,recovery:{missing_required_fields:a},nextSteps:[...u,...new Set(o.slice(0,3).filter(l=>l.missing_fields.length===0).map(l=>l.remediation)),...o.length>3?[`Inspect all policies with pm schema policies before retrying ${e.operation}.`]:[]]})}import{AsyncLocalStorage as yo}from"node:async_hooks";import{channel as ho}from"node:diagnostics_channel";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b2b2d49a-bb8c-54d7-89d2-1dbe76879129")}catch{}})();var Je=new yo,Qe=ho("@unbrained/pm-cli/item-metadata-enumeration/v1");function ve(e){Qe.publish(e)}async function Mr(e){let t={enumeration_calls:0,metadata_rows:0},i=o=>{Je.getStore()?.includes(t)&&(t.enumeration_calls+=1,t.metadata_rows+=o)};Qe.subscribe(i);try{return{result:await Je.run([...Je.getStore()??[],t],e),work:{...t}}}finally{Qe.unsubscribe(i)}}import{AsyncLocalStorage as ni}from"node:async_hooks";import{realpathSync as _o}from"node:fs";import et from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();var Ze=new ni;function Xr(e,t){return Ze.run([...Ze.getStore()??[],{...e,pmRoot:et.resolve(e.pmRoot)}],t)}var go=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),wo=globalThis,ne=wo[go]??=new ni;function X(e){let t=et.resolve(e);try{return _o.native(t)}catch{return t}}function Gr(){return{entries:new Map}}function Yr(e,t){return ne.run([...ne.getStore()??[],e],t)}function Vr(e,t,i){let o=X(t);if(e.pmRoot!==void 0&&e.pmRoot!==o)throw new m("An expected-revision scope is already bound to another tracker.",f.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});e.pmRoot=o;for(let{id:n,itemHash:r}of i){let s=e.entries.get(n);if(s!==void 0&&s.declared!==r)throw new m(`Item ${n} has two different expected revisions.`,f.USAGE,{code:"expected_revision_duplicate",item_id:n,required:"Declare at most one expected revision per item."});e.entries.set(n,s??{declared:r,expected:r,checked:!1,committed:!1})}}function Kr(e){let t=[...e.entries.entries()];return{checked:t.filter(([,i])=>i.checked).map(([i])=>i),unchecked:t.filter(([,i])=>!i.checked).map(([i])=>i)}}function tt(e,t){let i=ne.getStore()??[];if(i.length===0)return[];let o=X(e),n=new Set(t.filter(r=>typeof r=="string"));return[...new Set(i.flatMap(r=>r.pmRoot===o?[...n].flatMap(s=>r.entries.get(s)??[]):[]))]}function qr(e){let t=ne.getStore()??[];if(t.length===0)return[];let i=X(e),o=new Map;for(let n of t)if(n.pmRoot===i)for(let[r,s]of n.entries){if(s.expected!==s.declared)return;o.set(r,(o.get(r)??new Set).add(s.expected))}if(![...o.values()].some(n=>n.size>1))return[...o].map(([n,r])=>`${n}=${[...r][0]}`)}function Jr(e){let t=X(e);return(ne.getStore()??[]).some(i=>i.pmRoot===t&&i.entries.size>0)}function bo(e,t,i){let o=tt(e,[i,t.metadata.id]);o.length>0&&ai(o,i,Xe(t),!1,e)}function Qr(e,t,i){let o=tt(e,[t]);o.length>0&&ai(o,t,At(i),!0,e)}var Eo="revision_changed",vo="document_unreadable";function Io(e,t,i={}){let o=[...i.scopeArgs??[]],n=[...i.outputArgs??["--json"]],r=x([...o,"get",e,...n]),s=x([...o,"history",e,"--limit","5",...n]);return{required:t?`Recover ${e} without --expect-hash (${x([...o,"restore",e,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${e} (${r} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[x([...o,"get",e,"--fields","item_hash",...n]),s],nextSteps:[r,s]}}var Co=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),So=globalThis,it=So[Co]??=new WeakMap,To=8;function ri(e){for(let t of si(e)){let i=it.get(t);if(i!==void 0)return i}}function*si(e){let t=e;for(let i=0;i<To&&typeof t=="object"&&t!==null;i+=1){yield t;try{t=t.cause}catch{return}}}function ai(e,t,i,o,n){for(let r of e)if(r.checked=!0,!(!o&&r.expected===i))throw Do(n,new m(`Item ${t} is no longer at the expected revision ${r.expected.slice(0,12)}${o?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${r.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,f.CONFLICT,{code:"item_revision_conflict",item_id:t,expected_revision:r.expected,current_revision:i,reason:o?vo:Eo,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...Io(t,o)}))}function Zr(e,t){let i=ri(e);return i===void 0||i===X(t)}var Ro=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),xo=globalThis,ot=xo[Ro]??=new WeakSet;function Oo(e){for(let t of si(e))if(ot.has(t))return!0;return!1}function es(e){return ot.add(e),e}function ts(e,t){let i=ri(e);return i!==void 0&&it.set(t,i),Oo(e)&&ot.add(t),t}function Do(e,t){return it.set(t,X(e)),t}function nt(e,t,i=t.metadata.id){bo(e,t,i);for(let o of rt(e,[i,t.metadata.id]))o.validate(t)}function rt(e,t){let i=et.resolve(e);return(Ze.getStore()??[]).filter(o=>o.pmRoot===i&&t.includes(o.id))}function st(e,t,i=t.metadata.id,o=[],n){let r=tt(e,[i,t.metadata.id,...o]);if(r.length>0){let s=n??Xe(t);for(let a of r)a.expected=s,a.committed=!0}for(let s of rt(e,[i,t.metadata.id,...o]))s.committed?.(t)}function ci(e,t){return Object.assign({},...rt(e,t).map(i=>i.historyContext))}import H from"node:fs/promises";import li from"node:path";import{randomUUID as ko}from"node:crypto";import{createRequire as No}from"node:module";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="84a3dae8-69b6-589d-a8ec-11f77c1d103a")}catch{}})();var Ao="metadata-query-index.sqlite",re="5",at;function se(){return at!==void 0||(at=Gt(process.versions.node,No(import.meta.url))),at}function di(e,t){return Math.max(0,Math.floor(e===void 0?t:e))}function G(e){return li.join(e,"runtime",Ao)}function Fo(e){e.exec(`
2
2
  PRAGMA foreign_keys = ON;
3
3
  PRAGMA journal_mode = OFF;
4
4
  PRAGMA synchronous = OFF;
@@ -88,4 +88,4 @@ import{$a as _e,E as ze,F as Ht,Ma as Xe,Pa as Ge,Qa as Ye,R as J,Ra as Z,S as W
88
88
  WHERE item_search MATCH ?
89
89
  ORDER BY bm25(item_search), items.priority, items.updated_at DESC, items.id
90
90
  LIMIT ?`).all(e.query,Math.max(0,Math.floor(e.limit))).map(r=>JSON.parse(String(r.metadata_json)));return i.close(),{source_cursor:o.source_cursor,items:n}}catch{return i?.close(),null}}async function Te(e){await H.rm(G(e),{force:!0})}import E from"node:fs/promises";import w from"node:path";import{createHash as Po,randomUUID as gi}from"node:crypto";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="846c1c5d-8a5c-56ee-832a-bfc780283e70")}catch{}})();var O=8,wi=500,jo="metadata-derived-index",Lo="metadata-cache.json",$o="metadata-cache-bodies.json",Uo="metadata-cache-collections.json",Ho="metadata-cache-delta.json",Wo="metadata-cache-manifest.json",pi=4,Bo=["comments","notes","learnings","files","tests","test_runs","docs"];function bi(){return be(q())}function xe(e){let t={...e},i={};for(let o of Bo)o in t&&(i[o]=t[o],delete t[o]);return{light:t,heavy:i}}function Ei(e,t){return!t||Object.keys(t).length===0?e:{...e,...t}}function vi(e,t,i,o){let n=Po("sha256");n.update(`format:${e??"default"}`);let r=Object.entries(t).sort(([s],[a])=>s.localeCompare(a)).map(([s,a])=>`${s}=${a}`).join(",");return n.update(`|types:${r}`),i&&n.update(`|schema:${JSON.stringify(i)}`),o.length>0&&n.update(`|extension_fields:${o.join(",")}`),n.digest("hex").slice(0,16)}function Oe(e){return w.join(e,"runtime",Lo)}function De(e){return w.join(e,"runtime",$o)}function ke(e){return w.join(e,"runtime",Uo)}function dt(e){return w.join(e,"runtime",Ho)}function lt(e){return w.join(e,"runtime",Wo)}function Ne(e,t){let i=w.extname(e);return`${e.slice(0,-i.length)}.${t}${i}`}var zo=24,T=new Map,Ae=new WeakMap;function ut(e){return Ae.get(e)??e.source_cursor}function Xo(e,t){let i=ut(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Ae.set(e,i);for(let[o,n]of Object.entries(t.changes))n.entry?e.entries[o]=n.entry:delete e.entries[o];e.directory_signatures=t.directory_signatures,e.source_cursor=t.source_cursor}}function Go(e,t){if(!e)return;let i=ut(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Ae.set(e,i);for(let[o,n]of Object.entries(t.changes))n.body?e.bodies[o]=n.body:delete e.bodies[o];e.source_cursor=t.source_cursor}}function Yo(e,t){if(!e)return;let i=ut(e);if(!(t.base_source_cursor!==i||e.source_cursor===t.source_cursor)){Ae.set(e,i);for(let[o,n]of Object.entries(t.changes))n.collections?e.collections[o]=n.collections:delete e.collections[o];e.source_cursor=t.source_cursor}}function Vo(e,t,i,o){!e||!o||e.context_fingerprint!==o.context_fingerprint||(Xo(e,o),Go(t,o),Yo(i,o))}function ct(e,t){T.size>=zo&&!T.has(e)&&jt(T),T.set(e,t)}async function F(e,t){let i;try{i=await E.stat(e)}catch{return T.delete(e),null}let o=T.get(e);if(o&&ae(o.signature,i.mtimeMs,i.ctimeMs,i.size))return T.delete(e),T.set(e,o),o.envelope;let n;try{n=t(await E.readFile(e,"utf8"))}catch{n=null}return ct(e,{signature:{mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size},envelope:n}),n}async function Ko(e,t,i){let o=a=>{let d=JSON.parse(a);return d.version!==O||typeof d.source_cursor!="string"||typeof d.entries!="object"||d.entries===null?null:d},n=Oe(e),r=await F(n,o);if(!t||r===null||r.context_fingerprint===t)return r;let s=await F(Ne(n,t),o);return s===null&&le(i,`metadata_cache_context_changed:${r.context_fingerprint}->${t}`),s}async function qo(e,t){let i=r=>{let s=JSON.parse(r);return s.version!==O||typeof s.source_cursor!="string"||typeof s.bodies!="object"||s.bodies===null?null:s},o=De(e),n=await F(o,i);return t&&n?.context_fingerprint!==t?await F(Ne(o,t),i):n}async function Jo(e,t){let i=r=>{let s=JSON.parse(r);return s.version!==O||typeof s.source_cursor!="string"||typeof s.collections!="object"||s.collections===null?null:s},o=ke(e),n=await F(o,i);return t&&n?.context_fingerprint!==t?await F(Ne(o,t),i):n}async function mt(e){let t=dt(e),i=await F(t,o=>{let n=JSON.parse(o);return n.version!==O||typeof n.base_source_cursor!="string"||typeof n.source_cursor!="string"||typeof n.changes!="object"||n.changes===null?null:n});if(i)return{envelope:i,invalid:!1};try{return await E.stat(t),{envelope:null,invalid:!0}}catch{return{envelope:null,invalid:!1}}}async function ft(e){let t=lt(e),i=await F(t,o=>{let n=JSON.parse(o);return n.version!==O||typeof n.context_fingerprint!="string"||typeof n.source_cursor!="string"||!Number.isInteger(n.entry_count)||n.entry_count<0||typeof n.directory_signatures!="object"||n.directory_signatures===null?null:n});if(i)return i;try{await E.stat(t),await Y(e)}catch{}return null}async function ce(e,t){await E.mkdir(w.dirname(e),{recursive:!0}),await A(e,JSON.stringify(t));try{let o=await E.stat(e);ct(e,{signature:{mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size},envelope:t})}catch{T.delete(e)}let i=w.dirname(w.dirname(e));if(e===Oe(i)||e===De(i)||e===ke(i)){let o=Ne(e,t.context_fingerprint);await A(o,JSON.stringify(t));try{let d=await E.stat(o);ct(o,{signature:{mtime_ms:d.mtimeMs,ctime_ms:d.ctimeMs,size:d.size},envelope:t})}catch{T.delete(o)}let n=w.dirname(e),r=w.extname(e),s=w.basename(e,r),a=(await E.readdir(n,{withFileTypes:!0}).catch(()=>[])).filter(d=>d.isFile()&&d.name!==w.basename(e)&&d.name.startsWith(`${s}.`)&&d.name.endsWith(r)).map(d=>w.join(n,d.name));if(a.length>pi){let d=(await Promise.all(a.map(async c=>{try{return{path:c,mtime:(await E.stat(c)).mtimeMs}}catch{return null}}))).filter(c=>c!==null);for(let c of d.sort((y,u)=>y.mtime-u.mtime).slice(0,Math.max(0,d.length-pi)))await E.rm(c.path,{force:!0}),T.delete(c.path)}}}function Qo(e,t,i){return i?t===i&&e!==i:t==="toon"&&e!=="toon"}function Ii(e,t,i){return e===void 0||Qo(e,t,i)}function le(e,t){e&&!e.includes(t)&&e.push(t)}function ae(e,t,i,o){return e.mtime_ms===t&&e.ctime_ms===i&&e.size===o}async function Zo(e,t,i){let o=w.join(e,t);try{let n=await E.readdir(o);return{folder:t,dirPath:o,files:n}}catch(n){return typeof n=="object"&&n!==null&&"code"in n&&!L(n)&&le(i,`item_list_directory_read_failed:${t}`),{folder:t,dirPath:o,files:[]}}}async function en(e,t){try{let i=await E.stat(w.join(e,t));return[t,{exists:!0,mtime_ms:i.mtimeMs,ctime_ms:i.ctimeMs,size:i.size}]}catch{return[t,{exists:!1,mtime_ms:0,ctime_ms:0,size:0}]}}async function Re(e,t){return Object.fromEntries(await Promise.all(t.map(async i=>await en(e,i))))}function de(e,t){return!e||Object.keys(e).length!==Object.keys(t).length?!1:Object.entries(t).every(([i,o])=>{let n=e[i];return n!==void 0&&n.exists===o.exists&&ae(n,o.mtime_ms,o.ctime_ms,o.size)})}function tn(e){return pe.some(t=>e.toLowerCase().endsWith(t))}function on(e,t,i,o,n,r){o||(e.metadata=!0),t&&!n&&(e.body=!0),i&&!r&&(e.collections=!0)}async function nn(e,t,i){if(i)for(let o of await he({path:e,scope:"project"}))le(t,o)}function yi(e,t,i,o){if(e)return t&&i?i.collections:o}async function rn(e,t,i){let o=await E.stat(e),n=o.mtimeMs,r=o.ctimeMs,{size:s}=o,a=Le(e);await nn(e,i.warnings,i.dispatchReadHooks);let d=i.previousEntries[t],c=!i.forceSourceRead&&d!==void 0&&ae(d,n,r,s),y=i.previousBodies[t],u=!i.forceSourceRead&&y!==void 0&&ae(y,n,r,s),l=i.previousCollections[t],h=!i.forceSourceRead&&l!==void 0&&ae(l,n,r,s);if(!(!c||i.includeBody&&!u||i.includeCollections&&!h))return{mtimeMs:n,ctimeMs:r,size:s,itemFormat:a,lightMetadata:d.metadata,heavyMetadata:yi(i.includeCollections,h,l,void 0),bodyLength:d.body_length,body:i.includeBody?y.body:void 0};let p=await E.readFile(e,"utf8"),g=J(p,{format:a,schema:i.schema,extensionFieldNames:i.extensionFieldNames,onWarning:b=>le(i.warnings,b)}),_=xe(g.metadata);return on(i.state.misses,i.includeBody,i.includeCollections,c,u,h),{mtimeMs:n,ctimeMs:r,size:s,itemFormat:a,lightMetadata:c?d.metadata:_.light,heavyMetadata:yi(i.includeCollections,h,l,_.heavy),bodyLength:c?d.body_length:g.body.length,body:i.includeBody?g.body:void 0}}function sn(e,t,i,o){i.state.newEntries[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,metadata:o.lightMetadata,body_length:o.bodyLength},i.includeBody&&o.body!==void 0&&(i.state.newBodies[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,body:o.body}),i.includeCollections&&o.heavyMetadata!==void 0&&(i.state.newCollections[t]={mtime_ms:o.mtimeMs,ctime_ms:o.ctimeMs,size:o.size,collections:o.heavyMetadata});let n=i.includeCollections?Ei(o.lightMetadata,o.heavyMetadata):o.lightMetadata,r=i.state.documentsById.get(n.id),s={metadata:n,body:o.body,item_format:o.itemFormat,item_path:e};Ii(r?.itemFormat,o.itemFormat,i.preferredFormat)&&i.state.documentsById.set(n.id,{candidate:s,itemFormat:o.itemFormat})}async function an(e,t,i,o){try{let n=await rn(t,i,o);sn(t,i,o,n)}catch{le(o.warnings,`item_list_item_read_failed:${e}/${w.basename(t)}`)}}function cn(e,t){return e&&e.context_fingerprint===t?e.entries:{}}function dn(e,t){return e&&e.context_fingerprint===t?e.bodies:{}}function ln(e,t){return e&&e.context_fingerprint===t?e.collections:{}}function un(){return{newEntries:{},newBodies:{},newCollections:{},documentsById:new Map,misses:{metadata:!1,body:!1,collections:!1}}}async function mn(e,t){let i=[];for(let{folder:o,dirPath:n,files:r}of e)for(let s of r){if(!tn(s))continue;let a=w.join(n,s),d=w.relative(t.pmRoot,a);i.push(an(o,a,d,t)),i.length===32&&(await Promise.all(i),i.length=0)}await Promise.all(i)}async function fn(e){if(!(!(e.state.misses.metadata||Object.keys(e.previousEntries).length!==Object.keys(e.state.newEntries).length||!de(e.existingCache?.directory_signatures,e.directorySignatures))&&e.existingCache!==null&&e.existingCache.context_fingerprint===e.contextFingerprint))try{await ce(Oe(e.pmRoot),{version:O,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,directory_signatures:e.directorySignatures,entries:e.state.newEntries}),await ce(lt(e.pmRoot),{version:O,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,entry_count:Object.keys(e.state.newEntries).length,directory_signatures:e.directorySignatures});let t=[...e.state.documentsById.values()].map(({candidate:i})=>({relativePath:w.relative(e.pmRoot,i.item_path),metadata:xe(i.metadata).light,linkedFiles:i.metadata.files??[]}));t.length>=e.minimumIndexedItems?await mi({pmRoot:e.pmRoot,contextFingerprint:e.contextFingerprint,sourceCursor:e.sourceCursor,rows:t}):await Te(e.pmRoot)}catch{}}async function pn(e){!(e.state.misses.body||Object.keys(e.previousBodies).length!==Object.keys(e.state.newBodies).length)&&e.existingBodyCache!==null&&e.existingBodyCache.context_fingerprint===e.contextFingerprint||await ce(De(e.pmRoot),{version:O,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,bodies:e.state.newBodies}).catch(()=>{})}async function yn(e){!(e.state.misses.collections||Object.keys(e.previousCollections).length!==Object.keys(e.state.newCollections).length)&&e.existingCollectionsCache!==null&&e.existingCollectionsCache.context_fingerprint===e.contextFingerprint||await ce(ke(e.pmRoot),{version:O,context_fingerprint:e.contextFingerprint,source_cursor:e.sourceCursor,collections:e.state.newCollections}).catch(()=>{})}async function pt(e,t,i={}){let o=await ft(e);return i.required!==!0&&(o===null||o.entry_count<wi)?async()=>{}:$t(e,jo,30,t,!1,!1,3e3)}async function Cs(e,t){let i=await ft(e);if(i===null)return null;let o=await mt(e);if(o.invalid)return await Y(e),null;let n=o.envelope?.context_fingerprint===i.context_fingerprint&&o.envelope.base_source_cursor===i.source_cursor?o.envelope.source_cursor:i.source_cursor,r=o.envelope?.context_fingerprint===i.context_fingerprint&&o.envelope.base_source_cursor===i.source_cursor?o.envelope.directory_signatures:i.directory_signatures;return t&&!de(r,await Re(e,t))?null:{source_cursor:n,entry_count:i.entry_count}}function hi(e,t){let i=w.relative(e,t);return i===""||i===".."||i.startsWith(`..${w.sep}`)||w.isAbsolute(i)?null:i}async function Y(e){await Promise.all([Oe(e),De(e),ke(e),dt(e),lt(e)].map(async t=>{await E.rm(t,{force:!0}),T.delete(t)})),await Te(e)}async function hn(e){if(e.mutation.document===null)return{entry:null,body:null,collections:null};let t=await E.stat(e.mutation.itemPath),i=xe(e.mutation.document.metadata),o={mtime_ms:t.mtimeMs,ctime_ms:t.ctimeMs,size:t.size};return{entry:{...o,metadata:i.light,body_length:e.mutation.document.body.length},body:{...o,body:e.mutation.document.body},collections:{...o,collections:i.heavy}}}function _n(e,t,i){return e?.context_fingerprint===t&&e.base_source_cursor===i?structuredClone(e.changes):{}}async function yt(e){let t=hi(e.pmRoot,e.itemPath),i=e.previousItemPath?hi(e.pmRoot,e.previousItemPath):void 0;if(t===null||i===null)return await Y(e.pmRoot),["metadata_derived_index_path_invalidated"];try{let o=vi(e.preferredFormat,e.typeToFolder,e.schema,bi()),n=await ft(e.pmRoot);if(n===null||n.context_fingerprint!==o)return[];let r=n.source_cursor,s=await mt(e.pmRoot);if(s.invalid)return await Y(e.pmRoot),["metadata_derived_index_refresh_failed"];let a=_n(s.envelope,o,r),d=s.envelope?.context_fingerprint===o&&s.envelope.base_source_cursor===r?s.envelope.source_cursor:r;i!==void 0&&(a[i]={entry:null,body:null,collections:null}),a[t]=await hn({mutation:e});let c=gi();return await ce(dt(e.pmRoot),{version:O,context_fingerprint:o,base_source_cursor:r,source_cursor:c,directory_signatures:await Re(e.pmRoot,[...new Set(Object.values(e.typeToFolder))]),changes:a}),await fi({pmRoot:e.pmRoot,contextFingerprint:o,expectedSourceCursor:d,sourceCursor:c,row:e.document===null?null:{relativePath:t,metadata:xe(e.document.metadata).light,linkedFiles:e.document.metadata.files},deletedRelativePaths:[...i===void 0?[]:[i],...e.document===null?[t]:[]]})||await Te(e.pmRoot),[]}catch{return await Y(e.pmRoot).catch(()=>{}),["metadata_derived_index_refresh_failed"]}}function gn(e){return[...e.documentsById.values()].sort((t,i)=>t.candidate.metadata.id.localeCompare(i.candidate.metadata.id)).map(t=>t.candidate)}function _i(e,t,i){return e?.context_fingerprint===t&&e.source_cursor===i}function wn(e,t,i,o,n){return e.every(r=>(!t||o[r]!==void 0)&&(!i||n[r]!==void 0))}function bn(e){let t=new Map;for(let[i,o]of Object.entries(e.previousEntries)){let n=Le(i);if(!n)continue;let r=e.includeCollections?Ei(o.metadata,e.previousCollections[i]?.collections):o.metadata,s=t.get(r.id);Ii(s?.itemFormat,n,e.preferredFormat)&&t.set(r.id,{itemFormat:n,candidate:{metadata:r,body:e.includeBody?e.previousBodies[i]?.body:void 0,item_format:n,item_path:w.join(e.pmRoot,i)}})}return[...t.values()].sort((i,o)=>i.candidate.metadata.id.localeCompare(o.candidate.metadata.id)).map(i=>i.candidate)}function En(e){return e.forceSourceScan||He()||e.existingCache?.context_fingerprint!==e.contextFingerprint||e.entryKeys.length<e.minimumIndexedItems||!de(e.existingCache?.directory_signatures,e.directorySignatures)?!1:[!e.includeBody||_i(e.existingBodyCache,e.contextFingerprint,e.existingCache.source_cursor),!e.includeCollections||_i(e.existingCollectionsCache,e.contextFingerprint,e.existingCache.source_cursor)].every(Boolean)&&wn(e.entryKeys,e.includeBody,e.includeCollections,e.previousBodies,e.previousCollections)}async function Fe(e,t,i,o,n,r={}){let s=r.includeBody!==!1,a=r.includeCollections!==!1,d=bi(),c=vi(t,i,n,d),y=await mt(e);y.invalid&&await Y(e);let u=await Ko(e,c,r.cacheDiagnostics),l=s?await qo(e,c):null,h=a?await Jo(e,c):null;Vo(u,l,h,y.envelope);let p=cn(u,c),g=dn(l,c),_=ln(h,c),b=[...new Set(Object.values(i))],R=await Re(e,b),P=Object.keys(p),D=Math.max(1,Math.floor(r.derivedIndexMinimumItems??wi));if(En({forceSourceScan:r.forceSourceScan===!0,contextFingerprint:c,existingCache:u,existingBodyCache:l,existingCollectionsCache:h,directorySignatures:R,entryKeys:P,minimumIndexedItems:D,includeBody:s,includeCollections:a,previousBodies:g,previousCollections:_}))return bn({pmRoot:e,preferredFormat:t,includeBody:s,includeCollections:a,previousEntries:p,previousBodies:g,previousCollections:_});let W=await Promise.all(b.map(me=>Zo(e,me,o))),C=He(),I=un(),B={pmRoot:e,preferredFormat:t,warnings:o,schema:n,extensionFieldNames:d,includeBody:s,includeCollections:a,forceSourceRead:r.forceSourceScan===!0,dispatchReadHooks:C,previousEntries:p,previousBodies:g,previousCollections:_,state:I};await mn(W,B);let z=await Re(e,b),N=de(R,z)?z:{},S=I.misses.metadata||Object.keys(p).length!==Object.keys(I.newEntries).length||!de(u?.directory_signatures,N)||u===null?gi():u.source_cursor;return await fn({pmRoot:e,contextFingerprint:c,sourceCursor:S,existingCache:u,previousEntries:p,directorySignatures:N,state:I,minimumIndexedItems:D}),s&&await pn({pmRoot:e,contextFingerprint:c,sourceCursor:S,existingBodyCache:l,previousBodies:g,state:I}),a&&await yn({pmRoot:e,contextFingerprint:c,sourceCursor:S,existingCollectionsCache:h,previousCollections:_,state:I}),gn(I)}async function Ci(e,t,i,o,n){return(await Fe(e,t,i,o,n,{includeBody:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}async function Si(e,t,i,o,n){return(await Fe(e,t,i,o,n,{includeBody:!1,includeCollections:!1})).map(r=>({metadata:r.metadata,body:r.body??""}))}import M from"node:fs/promises";import{statSync as Sn}from"node:fs";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="02424d1c-c29f-5a13-b711-d50267170b9f")}catch{}})();function vn(e,t){let i=-1;return e.forEach((o,n)=>{let r=Date.parse(o.ts);if(!Number.isFinite(r))throw new m(`History for this item contains invalid timestamp at entry ${n+1}.`,f.GENERIC_FAILURE);r<=t&&(i=n)}),i}function In(e,t){let i=e[0]?.ts??null,o=e.at(-1)?.ts??null,n={code:"history_target_out_of_range",required:"Choose a target within the available item history.",why:"Point-in-time reads and restores can only reconstruct recorded versions.",examples:[],nextSteps:["Run pm history <id> to inspect available versions and timestamps."],valid_range:{first_version:null,last_version:null,first_timestamp:i,last_timestamp:o}};return o!==null&&(n.examples=[o],t!==null&&(n.examples.unshift(String(t+1),String(t+e.length)),n.valid_range.first_version=t+1,n.valid_range.last_version=t+e.length)),{guidance:n,lastTimestamp:o}}function Cn(e,t){let i={};if(t instanceof Error&&t.message.trim().length>0&&(i.reason=t.message.trim()),typeof t!="object"||t===null)return i;let o=t;if(typeof o.index=="number"&&Number.isInteger(o.index)&&o.index>=0&&(i.patchIndex=o.index),typeof o.operation=="object"&&o.operation!==null){let n=o.operation;Object.assign(i,Object.fromEntries(["op","path","from"].flatMap(r=>{let s=n[r];return typeof s=="string"?[[r,s]]:[]})))}if(i.patchIndex!==void 0){let n=e[i.patchIndex];n&&(i.op??=n.op,i.path??=n.path,i.from??=n.from)}return i}function Ti(e,t,i={}){let o=e.trim(),n=i.errorSubject??"history",r=n==="restore"?"Restore":"History",{guidance:s,lastTimestamp:a}=In(t,ie(t,!0));if(!o)throw new m(`Missing ${n} target. Use a timestamp or version number.`,f.USAGE,s);if(/^\d+$/.test(o)){let y=ie(t),u=Number(o);if(u>=1&&u<=y)throw new m(`History version ${u} was pruned by compaction.`,f.USAGE,{...s,code:"history_version_pruned"});if(!Number.isSafeInteger(u)||u<1||u>y+t.length)throw new m(`${r} version must be between ${y+1} and ${y+t.length} for this item.`,f.USAGE,s);return{kind:"version",raw:o,historyIndex:u-y-1}}let d=Date.parse(o);if(!Number.isFinite(d))throw new m(`Invalid ${n} target "${e}". Use a positive version number or ISO timestamp.`,f.USAGE,s);let c=vn(t,d);if(c<0||i.allowFutureTimestamp!==!0&&d>Date.parse(a))throw new m(n==="restore"?`No history entries exist at or before timestamp ${o}.`:`No history entry exists at timestamp ${o}.`,f.USAGE,s);return{kind:"timestamp",raw:o,historyIndex:c}}function ht(e,t,i,o){let n=Ve(e,t);if(n.ok)return n.document;let r=Cn(t,n.error),s=[`history_op=${o}`,r.patchIndex===void 0?null:`patch_index=${r.patchIndex}`,r.op?`op=${r.op}`:null,r.path?`path=${r.path}`:null,r.from?`from=${r.from}`:null].filter(a=>a!==null);throw new m(`Failed to apply history patch at entry ${i} (${s.join(", ")}). ${r.reason??String(n.error)}`,f.GENERIC_FAILURE)}function Ri(e,t){let i=e[0];if(i&&i.op!=="create"&&i.op!=="history_compact_baseline"){let s=Ve(Z,i.patch);if(!s.ok||typeof s.document.metadata.id!="string")throw new m("History starts without a reconstructable item baseline.",f.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the missing baseline."]})}let o=e.slice(0,t+1),n=_e([...o]),r=structuredClone(Z);for(let s=0;s<=t;s+=1){let a=e[s];if(!a)throw new m(`History target entry ${s+1} does not exist.`,f.USAGE);r=ht(r,a.patch,s+1,a.op)}if(!n.ok)throw new m(`History cannot be replayed: ${n.errors.join(", ")}.`,f.GENERIC_FAILURE,{code:"history_replay_invalid",verification_errors:n.errors,required:"Inspect the history integrity findings before attempting recovery.",nextSteps:["Run pm history <id> --verify --full."]});return r}function Ds(e,t){if(Object.keys(e.metadata).length>0){if(typeof e.metadata.id!="string"||!Array.isArray(e.metadata.tags))throw new m("History has no complete item baseline for this target.",f.GENERIC_FAILURE,{code:"history_baseline_unavailable",required:"Recover the original create entry or a complete checkpoint from version control.",nextSteps:["Run pm history <id> --full to inspect the first recorded state."]});return e}throw new m(`History target ${t.raw} resolves to a deleted state; choose a version or timestamp where the item exists.`,f.USAGE)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="be69f1e8-4543-5cf5-abb0-9d38ca1d0cc6")}catch{}})();function Tn(e,t){let i=-1,o=structuredClone(Z);for(let[a,d]of e.entries()){if(o=ht(o,d.patch,a+1,d.op),o.metadata.id!==void 0&&o.metadata.id!==t)throw new m(`History belongs to item ${String(o.metadata.id)}, expected ${t}.`,f.GENERIC_FAILURE,{code:"history_replay_invalid",required:"Recover the correct history stream for this item before attempting restoration."});o.metadata.id===t&&Array.isArray(o.metadata.tags)&&(i=a)}let n=ie(e,!0),r=i<0||n===null?null:n+i+1,s=r===null?void 0:String(r);if(i>=0&&s===void 0){let a=e[i].ts;Ti(a,e).historyIndex===i&&(s=a)}return{version:r,target:s}}async function xi(e,t,i){let o=new Set([te(t,i),ee(t)]);for(let n of o){let r=k(e,n);if(!Sn(r,{throwIfNoEntry:!1})?.isFile())continue;let s=await Xt(r,n),a=-1;if(s.forEach((h,p)=>{h.op==="delete"&&(a=p)}),a<0)continue;let d=Ri(s,s.length-1);if(Object.keys(d.metadata).length!==0)continue;let{version:c,target:y}=Tn(s,n),u=y===void 0?["history",n,"--verify"]:["get",n,"--at",y],l=x(u);return new m(`Item ${n} was deleted at ${s[a].ts}; its history is retained.`,f.NOT_FOUND,{code:"item_deleted",required:"Read a retained materialized version, then restore it if the item should exist again.",item_id:n,tombstone:{deleted:!0,deleted_at:s[a].ts,recoverable:y!==void 0,last_materialized_version:c},nextSteps:[l,...y===void 0?["Recover the pre-compaction history from version control."]:[x(["restore",n,y])]],recovery:{suggested_retry:l,suggested_retry_args:u}})}}import{AsyncLocalStorage as Rn}from"node:async_hooks";import Oi from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="c343ed33-0135-5d3a-94a4-67314b295168")}catch{}})();var Di=new Rn;function Xs(e,t){return Di.run({...e,pmRoot:Oi.resolve(e.pmRoot)},t)}function ki(e,t){let i=Di.getStore();return i?.pmRoot===Oi.resolve(e)&&i.itemId===t?{bulk_checkpoint:i.checkpointId}:void 0}import gt from"node:path";import xn from"node:fs/promises";import On from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="fd3a41f0-4e82-59ab-bb8c-ed796c96a0d7")}catch{}})();function Dn(e){return[...new Set(e.filter(t=>t.trim().length>0))].sort((t,i)=>t.localeCompare(i))}function kn(e,t){return new m(`Missing history stream for ${e}. ${t} requires history streams when settings.history.missing_stream is strict_error.`,f.NOT_FOUND)}async function Nn(e,t){return await xt(On.dirname(e)),await(await xn.open(e,"a")).close(),$({path:e,scope:"project",op:`${t}:history:auto_create`})}async function _t(e){return An({pmRoot:e.pmRoot,settings:e.settings,itemIds:[e.itemId],commandLabel:e.commandLabel})}async function An(e){let t=Dn(e.itemIds),i=[],o=[];for(let n of t){let r=k(e.pmRoot,n);if(!await K(r)){if(e.settings.history.missing_stream==="strict_error")throw kn(n,e.commandLabel);o.push(...await Nn(r,e.commandLabel)),o.push(`history_stream_auto_created:${n}`),i.push(n)}}return{auto_created_ids:i,warnings:o}}import{isUtf8 as Fn}from"node:buffer";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2bc3df8a-c200-52a0-8227-0deda053a955")}catch{}})();async function Mn(e){try{return await M.access(e),!0}catch{return!1}}function Pn(e,t){e&&(e.includes(t)||e.push(t))}function wt(e){return e??be(q())}function jn(e){return e==="toon"?["toon","json_markdown"]:e==="json_markdown"?["json_markdown","toon"]:["toon","json_markdown"]}async function bt(e,t,i="pm-",o,n=j){let r=t.trim(),s=r.startsWith("#")?r.slice(1):r;if(s.length===0)return null;let a=te(t,i),d=ee(t),c=[...new Set([s,a,d])].filter(l=>l.length>0),y=Object.entries(n),u=jn(o);for(let l of c){let h=new Map;for(let[p]of y)for(let g of u){let _=je(e,p,l,g,n);await Mn(_)&&h.set(_,h.get(_)??{id:l,type:p,itemPath:_,item_format:g})}if(h.size>1){let p=[...h.keys()].map(g=>gt.relative(e,g).split(gt.sep).join("/")).sort();throw new m(`Item ${l} has ambiguous identity across ${p.join(", ")}. Preserve both documents and inspect pm ops validate --check-storage-integrity before resolving the collision.`,f.CONFLICT,{code:"item_identity_ambiguous",item_id:l,paths:p})}for(let p of h.values())return p}return null}async function Ai(e,t={}){let i=await Ln(e,t);if(i.error!==null)throw i.error;return{raw:i.raw,document:i.document}}async function Ln(e,t={}){let i=await M.readFile(e.itemPath);if(!Fn(i))throw new m("Item contains invalid UTF-8; preserve a binary backup before recovering it.",f.CONFLICT,{code:"item_document_encoding_invalid",item_id:e.id,item_path:e.itemPath,byte_length:i.length,empty:!1});let o=i.toString("utf8");await he({path:e.itemPath,scope:"project"});let n;try{n=J(o,{format:e.item_format,requireSupportedFormat:!0,schema:t.schema,extensionFieldNames:wt(t.extensionFieldNames),onWarning:r=>Pn(t.warnings,r)})}catch(r){if(r instanceof m&&r.code==="item_format_version_unsupported")throw new m(`Item ${e.id}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath});if(r instanceof m&&r.code==="item_document_invalid")return{raw:o,document:null,error:new m(`Cannot read ${e.id} at ${e.itemPath}${i.length===0?" (zero-length file)":""}: ${r.message}`,r.exitCode,{...r.context,item_id:e.id,item_path:e.itemPath,byte_length:i.length,empty:i.length===0,nextSteps:[`Run pm history ${e.id} --full, then pm restore ${e.id} <version> to recover a recorded state.`]})};throw r}return{raw:o,document:n,error:null}}async function $n(e,t,i=j,o,n){await ge(e);let r=await Ci(e,t,i,o,n);return ve(r.length),r.map(s=>s.metadata)}async function Da(e,t,i=j,o,n){await ge(e);let r=await Si(e,t,i,o,n);return ve(r.length),r.map(s=>s.metadata)}async function ka(e,t,i=j,o,n,r={}){await ge(e);let s=await Fe(e,t,i,o,n,{includeBody:!0,forceSourceScan:r.forceSourceScan});return ve(s.length),s.map(a=>({...a.metadata,body:a.body}))}function Fi(e){return{async get(t){let i=await bt(e.pmRoot,t,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!i)return null;let{document:o}=await Ai(i,{schema:e.settings.schema});return{item:o.metadata,body:o.body}},list:()=>$n(e.pmRoot,e.settings.item_format,e.typeToFolder,void 0,e.settings.schema)}}async function Un(e,t){let i=new Set(Object.values(t)),o=[];return await Promise.all([...i].map(async n=>{try{let r=await M.readdir(gt.join(e,n));for(let s of r)for(let a of pe)if(s.toLowerCase().endsWith(a)){o.push(s.slice(0,-a.length));break}}catch{}})),o}async function Hn(e,t,i,o){let n=te(t,i),r=await Un(e,o);if(r.length===0)return[];let s=Math.max(3,Math.floor(n.length/2));return r.map(a=>({id:a,distance:fe(a,n,s)})).filter(a=>a.distance!==null).sort((a,d)=>a.distance-d.distance).slice(0,3).map(a=>a.id)}async function Wn(e,t,i,o){let n=await xi(e,t,i);if(n)return n;let r=await Hn(e,t,i,o),s=["Confirm the active --path/PM_PATH scope, then retry with a valid id."];return r.length>0&&s.unshift(`Did you mean one of: ${r.join(", ")}?`),new m(`Item ${t} not found`,f.NOT_FOUND,{code:"item_not_found",id:t,nextSteps:s})}function Bn(e,t){return e==="claim"||t===!0&&(e==="comment_add"||e==="comment_edit"||e==="comment_delete"||e==="note_add"||e==="learning_add"||e==="release"||e==="update"||e==="update_ownership_bypass"||e==="update_audit")}async function Mi(e){let t=e.typeToFolder??kt(e.settings,q()).type_to_folder,i=await bt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,t);if(!i)throw await Wn(e.pmRoot,e.id,e.settings.id_prefix,t);let o=await Ut(e.pmRoot,i.id,e.settings.locks.ttl_seconds,e.author,!!e.force,e.settings.governance.force_required_for_stale_lock,e.settings.locks.wait_ms,{waitPolicy:"progress"}),n=o.release;try{let r=[],{raw:s,document:a}=await Ai(i,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames,warnings:r}),d=a.metadata.assignee?.trim(),c=a.metadata.claim_principal?.trim()||d,y=zt(e.author),u=Vt(e.settings);if(d&&c!==y&&!e.force&&!Bn(e.op,e.bypassAssigneeConflict)){if(u.ownership_enforcement==="strict")throw new m(`Item ${i.id} is assigned to ${d}. Use --force to override.`,f.CONFLICT);u.ownership_enforcement==="warn"&&r.push(`ownership_warning:assignee_conflict:${i.id}:${d}`)}return{typeToFolder:t,located:i,originalRaw:s,document:a,warnings:r,releaseLock:n,lease:o}}catch(r){throw await n(),r}}async function Pi(e,t,i,o){return e.fence(async()=>{let n;try{n=await M.readFile(t.itemPath,"utf8")}catch(r){if(!L(r))throw r;n=null}if(n!==i)throw new m(`Item ${t.id} changed after this mutation read it; refusing to overwrite the newer revision. Nothing was written.`,f.CONFLICT,{code:"stale_revision",item_id:t.id,reason:n===null?"item_removed":"item_revision_changed",required:"Re-read the item and apply the mutation again; the newer stored revision was kept."});return o()})}function zn(e,t,i){if(!e.handled||typeof e.result!="object"||e.result===null)return{effectiveTargetItemPath:t,effectiveSerializedAfter:i,skipItemWrite:!1};let o=e.result;return{effectiveTargetItemPath:typeof o.target_item_path=="string"&&o.target_item_path.trim().length>0?o.target_item_path:t,effectiveSerializedAfter:typeof o.contents=="string"?o.contents:i,skipItemWrite:o.skip_write===!0}}async function ji(e){try{let t=await bt(e.pmRoot,e.id,e.settings.id_prefix,e.settings.item_format,e.typeToFolder);if(!t)return{document:Pe};let i=J(await M.readFile(t.itemPath,"utf8"),{format:t.item_format,requireSupportedFormat:!0,schema:e.settings.schema,extensionFieldNames:wt(e.extensionFieldNames)});return i.metadata.id===e.embeddedId?{document:i}:{document:e.fallback,revision:Ni}}catch{return{document:e.fallback,revision:Ni}}}var Ni="unreadable-after-storage-override";async function Xn(e){let t=await We("item_store_delete",e),i=t.handled&&typeof t.result=="object"&&t.result!==null?t.result:{};return{effectiveItemPath:typeof i.item_path=="string"&&i.item_path.trim().length>0?i.item_path:e.item_path,skipDelete:i.skip_delete===!0,warnings:t.warnings}}async function Gn(e){if(!e.skipItemWrite){if(e.effectiveTargetItemPath!==e.originalItemPath){await A(e.originalItemPath,e.originalRaw),await M.rm(e.effectiveTargetItemPath,{force:!0});return}await A(e.originalItemPath,e.originalRaw)}}async function Et(e){Bt(e.op);let t=await Mi({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:e.op,author:e.author,force:e.force,bypassAssigneeConflict:e.bypassAssigneeConflict,extensionFieldNames:e.extensionFieldNames,typeToFolder:e.typeToFolder}),{typeToFolder:i,located:o,originalRaw:n,document:r,warnings:s,releaseLock:a,lease:d}=t;try{nt(e.pmRoot,r,o.id);let c=Q(r,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),y=Q(structuredClone(r),{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),u=await e.mutate(y);if(e.skipNoop===!0&&u.changedFields.length===0)return{item:c.metadata,body:c.body,changedFields:[],warnings:[...s,...u.warnings??[]]};let l={...e.resolveHistoryContext?.(),...ki(e.pmRoot,o.id),...ci(e.pmRoot,[o.id,r.metadata.id])},h=Math.max(ze(c.metadata),ze(y.metadata));Kt(Nt(e.pmRoot),h),h>Ht(y.metadata)&&(y.metadata.pm_format_version=h,u.changedFields.push("pm_format_version")),y.metadata.updated_at=Be();let p=Q(y,{schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),g=await qe({pmRoot:e.pmRoot,settings:e.settings,operation:e.op,author:e.author,before:c,after:p});await Ue({pm_root:e.pmRoot,operation:e.op,before:c,after:p,changed_fields:u.changedFields,sdk:Fi({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:i})});let _=await _t({pmRoot:e.pmRoot,settings:e.settings,itemId:o.id,commandLabel:e.op}),b="toon",R=Wt(p,{format:b,schema:e.settings.schema,extensionFieldNames:e.extensionFieldNames}),P=je(e.pmRoot,p.metadata.type,o.id,b,i),D=k(e.pmRoot,o.id),W=await Pi(d,o,n,async()=>{let N=await We("item_store_write",{op:e.op,pm_root:e.pmRoot,item_id:o.id,source_item_path:o.itemPath,target_item_path:P,history_path:D,item_format:b,before:c,after:p,contents:R}),{effectiveTargetItemPath:S,effectiveSerializedAfter:me,skipItemWrite:V}=zn(N,P,R),Gi=await pt(e.pmRoot,e.author),St=[];try{V||await A(S,me),!V&&S!==o.itemPath&&await M.rm(o.itemPath);let Vi=Ge({nowIso:p.metadata.updated_at,author:e.author,op:e.op,before:c,after:p,message:e.message,context:g.decisions.length===0?Object.keys(l).length===0?void 0:l:{...l,workflow_policies:g.decisions}});try{await Ye(D,Vi)}catch(Ki){throw await Gn({skipItemWrite:V,effectiveTargetItemPath:S,originalItemPath:o.itemPath,originalRaw:n}),Ki}V||(St=await yt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:i,schema:e.settings.schema,itemPath:S,previousItemPath:o.itemPath,document:p}))}finally{await Gi()}let Yi=V||S!==P||me!==R;return{derivedIndexWarnings:St,effectiveTargetItemPath:S,overrideWarnings:N.warnings,stored:Yi?await ji({pmRoot:e.pmRoot,settings:e.settings,id:o.id,typeToFolder:i,extensionFieldNames:e.extensionFieldNames,fallback:p,embeddedId:p.metadata.id}):{document:p}}}),{derivedIndexWarnings:C,effectiveTargetItemPath:I,stored:B}=W;st(e.pmRoot,B.document,o.id,[p.metadata.id],B.revision);let z=[...await $({path:I,scope:"project",op:e.op,item_id:p.metadata.id,item_type:p.metadata.type,before:c,after:p,changed_fields:u.changedFields}),...await $({path:D,scope:"project",op:`${e.op}:history`,item_id:p.metadata.id,item_type:p.metadata.type,before:c,after:p,changed_fields:u.changedFields})];return $e({id:p.metadata.id,op:e.op,item_type:p.metadata.type,previous_status:c.metadata.status,status:p.metadata.status,previous:ye(c.metadata,u.changedFields),current:ye(p.metadata,u.changedFields),changed_fields:u.changedFields}),{item:p.metadata,body:p.body,changedFields:u.changedFields,warnings:[...s,...u.warnings??[],...g.warnings,..._.warnings,...W.overrideWarnings,...C,...z]}}finally{await a()}}async function Na(e){let{historyContext:t,...i}=e;return Et({...i,resolveHistoryContext:()=>t})}async function Aa(e){return Et(e)}async function Fa(e){return Et(e)}async function Ma(e){let t=await Mi({pmRoot:e.pmRoot,settings:e.settings,id:e.id,op:"delete",author:e.author,force:e.force}),{located:i,originalRaw:o,document:n,warnings:r,releaseLock:s,lease:a}=t;try{nt(e.pmRoot,n,i.id);let d=wt(void 0),c=Q(n,{schema:e.settings.schema,extensionFieldNames:d}),y=await qe({pmRoot:e.pmRoot,settings:e.settings,operation:"delete",author:e.author,before:c,after:null,dryRun:e.dryRun});await Ue({pm_root:e.pmRoot,operation:"delete",before:c,after:null,changed_fields:["deleted"],sdk:Fi({pmRoot:e.pmRoot,settings:e.settings,typeToFolder:t.typeToFolder})});let u=await _t({pmRoot:e.pmRoot,settings:e.settings,itemId:i.id,commandLabel:"delete"}),l=Be(),h=Pe,p=Ge({nowIso:l,author:e.author,op:"delete",before:c,after:h,message:e.message,context:y.decisions.length===0?void 0:{workflow_policies:y.decisions}}),g=k(e.pmRoot,i.id),_=()=>Xn({op:"delete",pm_root:e.pmRoot,item_id:i.id,item_path:i.itemPath,history_path:g,before:c});if(e.dryRun===!0){let C=await _();return{item:c.metadata,changedFields:["deleted"],targetPath:C.effectiveItemPath,warnings:[...r,...y.warnings,...u.warnings,...C.warnings]}}let b=await Pi(a,i,o,async()=>{let{effectiveItemPath:C,skipDelete:I,warnings:B}=await _(),z=await pt(e.pmRoot,e.author),N=[];try{I||await M.rm(C);try{await Ye(g,p)}catch(S){throw I||await A(C,o),S}I||(N=await yt({pmRoot:e.pmRoot,preferredFormat:e.settings.item_format,typeToFolder:t.typeToFolder,schema:e.settings.schema,itemPath:C,document:null}))}finally{await z()}return{derivedIndexWarnings:N,effectiveItemPath:C,overrideWarnings:B,stored:I||C!==i.itemPath?await ji({pmRoot:e.pmRoot,settings:e.settings,id:i.id,typeToFolder:t.typeToFolder,fallback:h,embeddedId:n.metadata.id}):{document:h}}}),{derivedIndexWarnings:R,effectiveItemPath:P,stored:D}=b;st(e.pmRoot,D.document,i.id,[n.metadata.id],D.revision);let W=[...await $({path:P,scope:"project",op:"delete",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]}),...await $({path:g,scope:"project",op:"delete:history",item_id:c.metadata.id,item_type:c.metadata.type,before:c,after:h,changed_fields:["deleted"]})];return $e({id:c.metadata.id,op:"delete",item_type:c.metadata.type,previous_status:c.metadata.status,previous:ye(c.metadata,Object.keys(c.metadata)),changed_fields:["deleted"]}),{item:c.metadata,changedFields:["deleted"],warnings:[...r,...y.warnings,...u.warnings,...b.overrideWarnings,...R,...W]}}finally{await s()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="a483f454-e261-5232-bae0-da3cdb8c0518")}catch{}})();var ue=Object.freeze({max_bytes:4096,max_depth:8}),Li=160;var $i=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u,Yn=new Set(["__proto__"]),v=class extends Error{reason;path;constructor(t,i){super(t),this.reason=t,this.path=i}};function Ui(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Vn(e,t){return/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Kn(e){if(Buffer.byteLength(e,"utf8")<=Li)return e;let t="",i=Buffer.byteLength("\u2026","utf8");for(let o of e){if(i+=Buffer.byteLength(o,"utf8"),i>Li)break;t+=o}return`${t}\u2026`}function Me(e,t,i){if(e.bytes+=t,!(e.bytes<=ue.max_bytes))throw new v("byte_limit",i)}function Hi(e,t,i){if(e.bytes+t>ue.max_bytes)throw new v("byte_limit",i)}function vt(e,t,i){let o=Object.getOwnPropertyDescriptor(e,t);if(o===void 0||!("value"in o))throw new v("unsupported_value",i);return o.value}function qn(e,t,i){if(typeof e=="number"&&!Number.isFinite(e))throw new v("non_finite_number",t);if(typeof e=="string"&&(Hi(i,e.length+2,t),$i.test(e)))throw new v("malformed_unicode",t);if(e!==null&&!["boolean","number","string"].includes(typeof e))throw new v("unsupported_value",t);return Me(i,Buffer.byteLength(JSON.stringify(e),"utf8"),t),e}function Wi(e,t,i,o){if(typeof e!="object"||e===null)return qn(e,t,o);if(i>=ue.max_depth)throw new v("depth_limit",t);if(Array.isArray(e)){let n=vt(e,"length",t);if(typeof n!="number"||!Number.isSafeInteger(n)||n<0)throw new v("unsupported_value",t);Me(o,n>0?n+1:2,t);let r=[];for(let s=0;s<n;s+=1){let a=`${t}[${s}]`;r.push(Wi(vt(e,String(s),a),a,i+1,o))}return r}if(!Ui(e))throw new v("unsupported_value",t);return Bi(e,t,i+1,o)}function Bi(e,t,i,o){let n=Object.keys(e);Me(o,n.length>0?n.length+1:2,t);let r={};for(let s of n){Hi(o,s.length+3,t);let a=Vn(t,s);if(Yn.has(s))throw new v("reserved_key",a);if($i.test(s))throw new v("malformed_unicode",a);Me(o,Buffer.byteLength(JSON.stringify(s),"utf8")+1,a),r[s]=Wi(vt(e,s,a),a,i,o)}return r}function Jn(e){try{if(e instanceof v)return e}catch{}return new v("unsupported_value","details")}function It(e){let t=ue.max_bytes,i={bytes:0};try{if(!Ui(e))throw new v("not_plain_object","details");return{ok:!0,details:Bi(e,"details",0,i),byte_length:i.bytes}}catch(o){let n=Jn(o);return{ok:!1,omission:n.reason==="byte_limit"?{reason:"byte_limit",byte_limit:t}:{reason:n.reason,path:Kn(n.path),byte_limit:t}}}}function Qn(e){return It(e).ok}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e82bc812-181f-57ab-a29a-61703e8bec1b")}catch{}})();function Ct(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function Ga(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;if(!Ct(t.requested_tokens)||t.basis!=="canonical_retry")return!1;switch(t.minimum_status){case"exact":return Ct(t.minimum_feasible_tokens)&&t.feasible_tokens===t.minimum_feasible_tokens&&t.reason===void 0;case"feasible_only":return t.minimum_feasible_tokens===null&&Ct(t.feasible_tokens)&&t.reason===void 0;case"unavailable":return t.minimum_feasible_tokens===null&&t.feasible_tokens===null&&["query_cost_limit","search_limit","output_constraints"].includes(t.reason);default:return!1}}var Zn="PmCliError";function Ya(e){if(!ir(e)||e.code!=="item_already_exists"||e.exitCode!==f.CONFLICT)return!1;let t=e.context;return typeof t=="object"&&t!==null&&t.code==="item_already_exists"&&typeof t.id=="string"&&t.id.trim().length>0&&typeof t.path=="string"&&t.path.trim().length>0}function er(e){if(!Number.isFinite(e))throw new TypeError("createPmCliExpectedError options.exitCode must be a finite number");let t=Math.trunc(e);if(t<=f.SUCCESS)throw new TypeError("createPmCliExpectedError options.exitCode must be a positive exit code");return t}function tr(e){if(e==null)return{};if(!Object.hasOwn(e,"details"))return e;let t=Object.getOwnPropertyDescriptor(e,"details");if(!("value"in t))throw zi("unsupported_value","details");if(t.value===void 0)return e;let i=It(t.value);if(i.ok)return{...e,details:i.details};if(i.omission.reason==="byte_limit"){let{details:o,...n}=e;return{...n,details_omitted:i.omission}}throw zi(i.omission.reason,i.omission.path)}function zi(e,t){let i=new TypeError(`createPmCliExpectedError options.context.details must be plain JSON (${e})`);return Object.defineProperty(i,"path",{value:t,enumerable:!1}),i}function Va(e,t={}){if(typeof e!="string"||e.trim().length===0)throw new TypeError("createPmCliExpectedError message must be a non-empty string");let i=new m(e,er(t.exitCode??f.USAGE),tr(t.context));return"cause"in t&&Object.defineProperty(i,"cause",{value:t.cause,enumerable:!1,configurable:!0,writable:!0}),i}function ir(e){try{if(!(e instanceof Error)||e.name!==Zn)return!1;let t=e;return typeof t.exitCode=="number"&&Number.isFinite(t.exitCode)&&typeof t.context=="object"&&t.context!==null&&!Array.isArray(t.context)}catch{return!1}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="e23f9ca6-9fa6-566b-9bfb-7cbe6d449a59")}catch{}})();function or(e,t){let i=e.trim().toLowerCase();if(i.length===0)return;let o=Math.floor(i.length/3);return t.map(n=>({candidate:n,distance:fe(i,n.toLowerCase(),o)??Number.POSITIVE_INFINITY})).filter(({distance:n})=>Number.isFinite(n)).sort((n,r)=>n.distance!==r.distance?n.distance-r.distance:n.candidate.localeCompare(r.candidate))[0]?.candidate}function Xi(e){return["pm",...e].map(t=>/^[A-Za-z0-9_./:@=-]+$/u.test(t)?t:JSON.stringify(t)).join(" ")}function Za(e){let t=e.command_path.trim().replaceAll(/\s+/gu," "),i=e.token.trim(),o=i.length===0?"<empty>":i,n=[...new Set(e.allowed.map(l=>l.trim()))].filter(Boolean).sort((l,h)=>l.localeCompare(h));if(t.length===0||o.length===0||n.length===0)throw new TypeError("Unknown-subcommand contracts require a path, token, and allowed set");let r=t.split(" "),s=e.trailing_args??[],a=e.display_name??`pm ${t}`,d=e.token_kind??"subcommand",c=e.retry_command?void 0:or(o,n),y=Xi([...r,o,...s]),u=e.retry_command??(c?Xi([...r,c,...s]):void 0);return new m(`Unknown ${a} ${d} "${o}". Allowed: ${n.join(", ")}${e.message_suffix??""}`,e.exit_code??f.USAGE,{code:"unknown_subcommand",reason:"unknown_positional_token",value:o,examples:[...u?[u]:[],...e.examples??[],`pm ${t} --help`],nextSteps:u?[`Retry with the suggested command: ${u}`]:["Choose one value from recovery.allowed_values."],recovery:{attempted_command:y,allowed_values:n,suggested_retry:u,fallback_candidates:e.fallback_candidates}})}export{we as a,be as b,ar as c,cr as d,Za as e,_t as f,An as g,ei as h,ee as i,te as j,yr as k,ie as l,Ti as m,ht as n,Ri as o,Ds as p,co as q,uo as r,mo as s,fo as t,po as u,qe as v,Mr as w,Xr as x,Gr as y,Yr as z,Vr as A,Kr as B,qr as C,Jr as D,Qr as E,Eo as F,vo as G,Io as H,Zr as I,Oo as J,es as K,ts as L,nt as M,st as N,Xs as O,ds as P,ls as Q,us as R,wi as S,Bo as T,pt as U,Cs as V,yt as W,Fe as X,bt as Y,Ai as Z,Ln as _,$n as $,Da as aa,ka as ba,Fi as ca,Wn as da,Na as ea,Aa as fa,Fa as ga,Ma as ha,Qn as ia,Ga as ja,Zn as ka,Ya as la,Va as ma,ir as na};
91
- //# sourceMappingURL=chunk-WJHDUON5.js.map
91
+ //# sourceMappingURL=chunk-NY65XTX7.js.map
@@ -1,8 +1,8 @@
1
- import{r as q,s as V}from"./chunk-QHGGO7SY.js";import{d as m,j as M,l as k}from"./chunk-RFMKS7VD.js";import{Ga as O,Gd as N,Jd as D,Md as j,S as x,X as g,ce as z}from"./chunk-2SQUWQP3.js";import{A as C,E as _,I as L,z as S}from"./chunk-G6ERMFJ5.js";import{constants as p}from"node:fs";import{lstat as A,mkdir as I,open as P}from"node:fs/promises";import h from"node:path";(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5434ff6f-95af-5983-88cb-fd360d95cb9e")}catch{}})();function E(i,e){if(typeof i!="string"||i.trim().length===0)throw new TypeError(`Relationship event ${e} must be non-empty`);return i.trim()}function $(i,e){let t=e.require(i.kind),n=t.direction==="undirected"?[i.source,i.target].sort().join("\0"):`${i.source}\0${i.target}`;return`${t.kind}\0${n}`}function Q(i){return Object.freeze({...i,...i.payload===void 0?{}:{payload:Object.freeze(structuredClone(i.payload))}})}function U(i,e,t,n){let r=t.require(i.kind),o=n.outgoingOne.get(`${r.kind}\0${i.source}`);if(o!==void 0&&o!==e)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=n.incomingOne.get(`${r.kind}\0${i.target}`);if(s!==void 0&&s!==e)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let c=$(i,t),a=n.identities.get(c);if(a!==void 0&&a!==e)throw new TypeError(`Relationship edge already active: ${c}`)}function Y(i){let e=new Map;for(let t of i)t.action==="remove"?e.delete(t.relationshipId):e.set(t.relationshipId,t.edge);return e}function X(i,e,t){if(i.expectedVersion!==void 0&&i.expectedVersion!==e)throw new TypeError(`Relationship event version conflict: expected ${i.expectedVersion}, current ${e}`);let n=E(i.eventId,"eventId");if(t.has(n))throw new TypeError(`Relationship event already exists: ${n}`);if(i.action!=="add"&&i.action!=="remove"&&i.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${i.action}`);if(!Number.isFinite(Date.parse(i.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:n,relationshipId:E(i.relationshipId,"relationshipId"),author:E(i.author,"author"),timestamp:new Date(i.timestamp).toISOString()}}function Z(i,e,t,n,r,o){let s=t.has(e);if(i.action==="add"&&s)throw new TypeError(`Relationship is already active: ${e}`);if(i.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${e}`);if(i.action==="remove")return;if(!i.edge)throw new TypeError(`Relationship ${i.action} event requires an edge`);let c=typeof i.edge.source=="string"?i.edge.source.trim():"",a=typeof i.edge.target=="string"?i.edge.target.trim():"";if(!n.has(c)||!n.has(a))throw new TypeError(`Relationship endpoint not found: ${c} -> ${a}`);let d=new g([c,a],[i.edge],r).edges()[0];return U(d,e,r,o),Q(d)}var T=class{#t;#i;#n=[];#o=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(e,t={}){this.#t=new Set([...e].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean)),this.#i=t.registry??x()}get version(){return this.#n.length}events(){return Object.freeze([...this.#n])}*stream(e={}){let t=e.fromVersion??1,n=e.toVersion??this.version,r=e.batchSize??100;if(!Number.isInteger(t)||t<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(n)||n<0||n>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${n}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(t>n+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let o=t-1;o<n;o+=r)yield Object.freeze(this.#n.slice(o,Math.min(o+r,n)))}project(e,t,n={}){if(typeof t!="function")throw new TypeError("Relationship event projection requires a reducer");let r=e,o=0,s;for(let c of this.stream({...n,batchSize:256}))for(let a of c)r=t(r,a),o+=1,s=a;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(n.fromVersion??1)-1),processed:o,...s===void 0?{}:{asOf:s.timestamp}})}#s(e,t){let n=this.#i.require(t.kind);this.#r.identities.set($(t,this.#i),e),n.outgoing==="one"&&this.#r.outgoingOne.set(`${n.kind}\0${t.source}`,e),n.incoming==="one"&&this.#r.incomingOne.set(`${n.kind}\0${t.target}`,e)}#a(e){let t=this.#i.require(e.kind);this.#r.identities.delete($(e,this.#i)),t.outgoing==="one"&&this.#r.outgoingOne.delete(`${t.kind}\0${e.source}`),t.incoming==="one"&&this.#r.incomingOne.delete(`${t.kind}\0${e.target}`)}append(e){let t=X(e,this.version,this.#o),n=this.#e.get(t.relationshipId),r=Z(e,t.relationshipId,this.#e,this.#t,this.#i,this.#r),o=Object.freeze({eventId:t.eventId,relationshipId:t.relationshipId,action:e.action,...r===void 0?{}:{edge:r},author:t.author,timestamp:t.timestamp,...e.reason?.trim()?{reason:e.reason.trim()}:{},sequence:this.version+1});return this.#n.push(o),this.#o.add(t.eventId),n&&this.#a(n),e.action==="remove"?this.#e.delete(t.relationshipId):(this.#e.set(t.relationshipId,r),this.#s(t.relationshipId,r)),o}snapshot(e={}){if(e.atVersion!==void 0&&e.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let t;if(e.atTimestamp!==void 0){let o=Date.parse(e.atTimestamp);if(!Number.isFinite(o))throw new TypeError("Relationship snapshot timestamp must be valid");t=this.#n.filter(s=>Date.parse(s.timestamp)<=o)}else{let o=e.atVersion??this.version;if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship snapshot version out of range: ${o}`);t=this.#n.slice(0,o)}let n=Y(t),r=new g(this.#t,n.values(),this.#i);return Object.freeze({version:t.at(-1)?.sequence??0,...t.at(-1)?{asOf:t.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(e){if(!Number.isInteger(e.limit)||e.limit<1)throw new TypeError("Relationship event page limit must be positive");let t=N("relationship-events",{order:"append-sequence"}),n=e.cursor===void 0?this.version:Number(D(e.cursor,t).snapshot);if(!Number.isSafeInteger(n)||n<0||n>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=j(this.#n.slice(0,n),{cursor:e.cursor,fingerprint:t,limit:e.limit,readId:o=>o.eventId,snapshot:String(n)});return{version:n,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},ee="relationship-event-store",W=p.O_NOFOLLOW;function w(i){return z(i,ee,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function f(i,e="relationships/events.jsonl"){let t=h.resolve(i),n=h.resolve(t,e),r=h.relative(t,n);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${h.sep}`)||h.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await I(t,{recursive:!0}),(await A(t)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let o=t;for(let s of r.split(h.sep)){o=h.join(o,s);try{if((await A(o)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(_(c))break;throw c}}return n}async function y(i,e,t){let n=new T(e,{registry:t}),r,o;try{o=await P(i,p.O_RDONLY|W),r=await o.readFile("utf8")}catch(c){if(_(c))return{log:n,raw:""};throw c}finally{await o?.close()}let s=r.split(`
1
+ import{r as q,s as V}from"./chunk-AXPRCCYM.js";import{d as m,j as M,l as k}from"./chunk-NSOXVVQX.js";import{Ga as O,Jd as N,Md as D,Pd as j,S as x,X as g,fe as z}from"./chunk-MK7UQEE5.js";import{A as C,E as _,I as L,z as S}from"./chunk-G6ERMFJ5.js";import{constants as p}from"node:fs";import{lstat as A,mkdir as I,open as P}from"node:fs/promises";import h from"node:path";(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5434ff6f-95af-5983-88cb-fd360d95cb9e")}catch{}})();function E(i,e){if(typeof i!="string"||i.trim().length===0)throw new TypeError(`Relationship event ${e} must be non-empty`);return i.trim()}function $(i,e){let t=e.require(i.kind),n=t.direction==="undirected"?[i.source,i.target].sort().join("\0"):`${i.source}\0${i.target}`;return`${t.kind}\0${n}`}function Q(i){return Object.freeze({...i,...i.payload===void 0?{}:{payload:Object.freeze(structuredClone(i.payload))}})}function U(i,e,t,n){let r=t.require(i.kind),o=n.outgoingOne.get(`${r.kind}\0${i.source}`);if(o!==void 0&&o!==e)throw new TypeError(`Relationship outgoing cardinality exceeded for ${r.kind}`);let s=n.incomingOne.get(`${r.kind}\0${i.target}`);if(s!==void 0&&s!==e)throw new TypeError(`Relationship incoming cardinality exceeded for ${r.kind}`);let c=$(i,t),a=n.identities.get(c);if(a!==void 0&&a!==e)throw new TypeError(`Relationship edge already active: ${c}`)}function Y(i){let e=new Map;for(let t of i)t.action==="remove"?e.delete(t.relationshipId):e.set(t.relationshipId,t.edge);return e}function X(i,e,t){if(i.expectedVersion!==void 0&&i.expectedVersion!==e)throw new TypeError(`Relationship event version conflict: expected ${i.expectedVersion}, current ${e}`);let n=E(i.eventId,"eventId");if(t.has(n))throw new TypeError(`Relationship event already exists: ${n}`);if(i.action!=="add"&&i.action!=="remove"&&i.action!=="supersede")throw new TypeError(`Unknown relationship event action: ${i.action}`);if(!Number.isFinite(Date.parse(i.timestamp)))throw new TypeError("Relationship event timestamp must be valid");return{eventId:n,relationshipId:E(i.relationshipId,"relationshipId"),author:E(i.author,"author"),timestamp:new Date(i.timestamp).toISOString()}}function Z(i,e,t,n,r,o){let s=t.has(e);if(i.action==="add"&&s)throw new TypeError(`Relationship is already active: ${e}`);if(i.action!=="add"&&!s)throw new TypeError(`Relationship is not active: ${e}`);if(i.action==="remove")return;if(!i.edge)throw new TypeError(`Relationship ${i.action} event requires an edge`);let c=typeof i.edge.source=="string"?i.edge.source.trim():"",a=typeof i.edge.target=="string"?i.edge.target.trim():"";if(!n.has(c)||!n.has(a))throw new TypeError(`Relationship endpoint not found: ${c} -> ${a}`);let d=new g([c,a],[i.edge],r).edges()[0];return U(d,e,r,o),Q(d)}var T=class{#t;#i;#n=[];#o=new Set;#e=new Map;#r={identities:new Map,outgoingOne:new Map,incomingOne:new Map};constructor(e,t={}){this.#t=new Set([...e].filter(n=>typeof n=="string").map(n=>n.trim()).filter(Boolean)),this.#i=t.registry??x()}get version(){return this.#n.length}events(){return Object.freeze([...this.#n])}*stream(e={}){let t=e.fromVersion??1,n=e.toVersion??this.version,r=e.batchSize??100;if(!Number.isInteger(t)||t<1)throw new TypeError("Relationship event stream fromVersion must be positive");if(!Number.isInteger(n)||n<0||n>this.version)throw new TypeError(`Relationship event stream toVersion out of range: ${n}`);if(!Number.isInteger(r)||r<1)throw new TypeError("Relationship event stream batchSize must be positive");if(t>n+1)throw new TypeError("Relationship event stream fromVersion exceeds the selected prefix");for(let o=t-1;o<n;o+=r)yield Object.freeze(this.#n.slice(o,Math.min(o+r,n)))}project(e,t,n={}){if(typeof t!="function")throw new TypeError("Relationship event projection requires a reducer");let r=e,o=0,s;for(let c of this.stream({...n,batchSize:256}))for(let a of c)r=t(r,a),o+=1,s=a;return Object.freeze({state:r,version:s?.sequence??Math.max(0,(n.fromVersion??1)-1),processed:o,...s===void 0?{}:{asOf:s.timestamp}})}#s(e,t){let n=this.#i.require(t.kind);this.#r.identities.set($(t,this.#i),e),n.outgoing==="one"&&this.#r.outgoingOne.set(`${n.kind}\0${t.source}`,e),n.incoming==="one"&&this.#r.incomingOne.set(`${n.kind}\0${t.target}`,e)}#a(e){let t=this.#i.require(e.kind);this.#r.identities.delete($(e,this.#i)),t.outgoing==="one"&&this.#r.outgoingOne.delete(`${t.kind}\0${e.source}`),t.incoming==="one"&&this.#r.incomingOne.delete(`${t.kind}\0${e.target}`)}append(e){let t=X(e,this.version,this.#o),n=this.#e.get(t.relationshipId),r=Z(e,t.relationshipId,this.#e,this.#t,this.#i,this.#r),o=Object.freeze({eventId:t.eventId,relationshipId:t.relationshipId,action:e.action,...r===void 0?{}:{edge:r},author:t.author,timestamp:t.timestamp,...e.reason?.trim()?{reason:e.reason.trim()}:{},sequence:this.version+1});return this.#n.push(o),this.#o.add(t.eventId),n&&this.#a(n),e.action==="remove"?this.#e.delete(t.relationshipId):(this.#e.set(t.relationshipId,r),this.#s(t.relationshipId,r)),o}snapshot(e={}){if(e.atVersion!==void 0&&e.atTimestamp!==void 0)throw new TypeError("Relationship snapshot accepts one target");let t;if(e.atTimestamp!==void 0){let o=Date.parse(e.atTimestamp);if(!Number.isFinite(o))throw new TypeError("Relationship snapshot timestamp must be valid");t=this.#n.filter(s=>Date.parse(s.timestamp)<=o)}else{let o=e.atVersion??this.version;if(!Number.isInteger(o)||o<0||o>this.version)throw new TypeError(`Relationship snapshot version out of range: ${o}`);t=this.#n.slice(0,o)}let n=Y(t),r=new g(this.#t,n.values(),this.#i);return Object.freeze({version:t.at(-1)?.sequence??0,...t.at(-1)?{asOf:t.at(-1).timestamp}:{},edges:r.edges(),graph:r})}page(e){if(!Number.isInteger(e.limit)||e.limit<1)throw new TypeError("Relationship event page limit must be positive");let t=N("relationship-events",{order:"append-sequence"}),n=e.cursor===void 0?this.version:Number(D(e.cursor,t).snapshot);if(!Number.isSafeInteger(n)||n<0||n>this.version)throw new TypeError("Relationship event cursor snapshot version is invalid");let r=j(this.#n.slice(0,n),{cursor:e.cursor,fingerprint:t,limit:e.limit,readId:o=>o.eventId,snapshot:String(n)});return{version:n,events:r.rows,hasMore:r.has_more,...r.next_cursor?{nextCursor:r.next_cursor}:{}}}},ee="relationship-event-store",W=p.O_NOFOLLOW;function w(i){return z(i,ee,30,`relationship-store:${process.pid}`,!1,!1,3e3)}async function f(i,e="relationships/events.jsonl"){let t=h.resolve(i),n=h.resolve(t,e),r=h.relative(t,n);if(r.length===0)throw new TypeError("Relationship event path must name a file within the tracker root");if(r===".."||r.startsWith(`..${h.sep}`)||h.isAbsolute(r))throw new TypeError("Relationship event path must stay within the tracker root");if(await I(t,{recursive:!0}),(await A(t)).isSymbolicLink())throw new TypeError("Relationship event tracker root must not be a symbolic link");let o=t;for(let s of r.split(h.sep)){o=h.join(o,s);try{if((await A(o)).isSymbolicLink())throw new TypeError("Relationship event path must not contain symbolic links")}catch(c){if(_(c))break;throw c}}return n}async function y(i,e,t){let n=new T(e,{registry:t}),r,o;try{o=await P(i,p.O_RDONLY|W),r=await o.readFile("utf8")}catch(c){if(_(c))return{log:n,raw:""};throw c}finally{await o?.close()}let s=r.split(`
2
2
  `);for(let c=0;c<s.length;c+=1){let a=s[c].trim();if(!a)continue;let d;try{d=JSON.parse(a)}catch{throw new TypeError(`Invalid relationship event JSONL at line ${c+1}`)}if(d.sequence!==n.version+1)throw new TypeError(`Invalid relationship event sequence at line ${c+1}`);n.append({eventId:d.eventId,relationshipId:d.relationshipId,action:d.action,...d.edge===void 0?{}:{edge:d.edge},author:d.author,timestamp:d.timestamp,...d.reason===void 0?{}:{reason:d.reason},expectedVersion:n.version})}return{log:n,raw:r}}function te(i,e,t,n){let r=Date.parse(e.timestamp),o;return e.action!=="remove"&&e.edge!==void 0&&(o=new g(t,[e.edge],n).edges()[0]),i.eventId===e.eventId.trim()&&i.relationshipId===e.relationshipId.trim()&&i.action===e.action&&i.author===e.author.trim()&&Number.isFinite(r)&&i.timestamp===new Date(r).toISOString()&&i.reason===(e.reason?.trim()||void 0)&&O(i.edge)===O(o)}var F=class i{#t;#i;#n;#o;#e;constructor(e,t,n,r){this.#t=e.pmRoot,this.#i=t,this.#n=e.registry,this.#o=n,this.#e=r}static async open(e){let t=Object.freeze([...e.nodes]),n=await f(e.pmRoot,e.relativePath),r=await w(e.pmRoot);try{await f(e.pmRoot,n);let{log:o}=await y(n,t,e.registry);return new i(e,t,n,o)}finally{await r()}}get path(){return this.#o}async currentVersion(){return this.#e=await this.#r(),this.#e.version}async append(e){let t=await w(this.#t);try{let n=await f(this.#t,this.#o),{log:r}=await y(n,this.#i,this.#n),o=r.append(e);await I(h.dirname(n),{recursive:!0}),await f(this.#t,n);let s=await P(n,p.O_APPEND|p.O_CREAT|p.O_WRONLY|W);try{await s.appendFile(`${JSON.stringify(o)}
3
3
  `,"utf8")}finally{await s.close()}return this.#e=r,o}finally{await t()}}async appendBatch(e,t={}){let n=await w(this.#t);try{let r=await f(this.#t,this.#o),{log:o,raw:s}=await y(r,this.#i,this.#n),c=o.version,a=new Map(o.events().map(l=>[l.eventId,l])),d=[],R=[];for(let l of e){let u=l.eventId.trim(),v=a.get(u);if(v!==void 0){if(t.existingEventPolicy==="skip_identical"&&te(v,l,this.#i,this.#n)){R.push(v.eventId);continue}if(t.existingEventPolicy==="skip_identical")throw new TypeError(`Relationship event id collision with different content: ${u}`)}let b=o.append(l);a.set(b.eventId,b),d.push(b)}if(d.length>0){let l=s.length===0||s.endsWith(`
4
4
  `)?s:`${s}
5
5
  `;await I(h.dirname(r),{recursive:!0}),await f(this.#t,r),await L(r,`${l}${d.map(u=>JSON.stringify(u)).join(`
6
6
  `)}
7
7
  `)}return this.#e=o,Object.freeze({version_before:c,version_after:o.version,appended:Object.freeze(d),skipped_event_ids:Object.freeze(R)})}finally{await n()}}async snapshot(e={}){return this.#e=await this.#r(),this.#e.snapshot(e)}async page(e){return this.#e=await this.#r(),this.#e.page(e)}async*stream(e={}){this.#e=await this.#r(),yield*this.#e.stream(e)}async project(e,t,n={}){return this.#e=await this.#r(),this.#e.project(e,t,n)}async#r(){let e=await w(this.#t);try{let t=await f(this.#t,this.#o);return(await y(t,this.#i,this.#n)).log}finally{await e()}}};(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();function K(i){return[...i].sort().join("\0")}function ie(i,e,t){let n=i.successors.get(e);n?n.push(t):i.successors.set(e,[t]);let r=i.predecessors.get(t);r?r.push(e):i.predecessors.set(t,[e])}function G(i,e,t,n,r){let o=e.resolve(r);if(o?.ordering!==!0)return;let s=M(n),c=s===void 0?void 0:i.canonicalIds.get(s.toLowerCase());if(c===void 0)return;let a=(o.precedence??"source_before_target")==="source_before_target";ie(i,a?t:c,a?c:t)}function ne(i,e){let t={successors:new Map,predecessors:new Map,canonicalIds:new Map},n=i.filter(r=>typeof r?.id=="string"&&r.id.trim().length>0);for(let r of n){let o=r.id.trim();t.canonicalIds.set(o.toLowerCase(),o)}for(let r of n){let o=r.id.trim();G(t,e,o,r.blocked_by,"blocked_by");for(let s of r.dependencies??[])typeof s!="object"||s===null||G(t,e,o,s.id,typeof s.kind=="string"?s.kind:"related")}for(let r of[t.successors,t.predecessors])for(let o of r.values())o.sort();return t}function re(i,e){let t=new Set([e]),n=[e];for(;n.length>0;){let r=n.pop();for(let o of[i.successors,i.predecessors])for(let s of o.get(r)??[])t.has(s)||(t.add(s),n.push(s))}return t}function oe(i,e){let t=new Map;for(let n of e){let r=(i.successors.get(n)??[]).filter(o=>e.has(o));r.length>0&&t.set(n,r)}return t}function H(i,e,t){let n=ne(i,e),r=n.canonicalIds.get(t.trim().toLowerCase());if(r===void 0)return{cycles:[],successors:new Map,canonical:t};let o=oe(n,re(n,r));return{cycles:q(o).filter(s=>s.includes(r)),successors:o,canonical:r}}function se(i,e,t){let n=new Set(e),r=n.has(t)?t:e[0];if(i.get(r)?.includes(r))return[r,r];for(let o of i.get(r)??[]){if(!n.has(o))continue;let s=ae(i,n,r,o);if(s)return s}return[...e,e[0]]}function ae(i,e,t,n){let r=[[n]],o=new Set([t,n]);for(;r.length>0;){let s=r.shift(),c=s.at(-1);for(let a of i.get(c)??[]){if(a===t)return[t,...s,t];!e.has(a)||o.has(a)||(o.add(a),r.push([...s,a]))}}}function ve(i,e,t){let n=m(),r=H(i,n,t),o=H(e,n,t),s=new Set(r.cycles.map(K)),c=new Set(k(i,void 0,n).map(a=>`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`));return[...k(e,void 0,n).filter(a=>a.holder_id.toLowerCase()===t.trim().toLowerCase()&&!c.has(`${a.holder_id.toLowerCase()}\0${a.target_id.toLowerCase()}\0${a.dependency_kind}`)).map(a=>`ordering_storage_contradiction_created:${V(a)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...o.cycles.filter(a=>!s.has(K(a))).map(a=>`ordering_cycle_created:${se(o.successors,a,o.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}(function(){try{var i=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},e=new i.Error().stack;e&&(i._sentryDebugIds=i._sentryDebugIds||{},i._sentryDebugIds[e]="5f2ca18e-450d-5b6e-9e07-7bbf080764f9")}catch{}})();function Ee(i,e){let t=e.resolve(i);return t?.hierarchy===!0||t?.outgoing==="one"||t?.incoming==="one"}function J(i,e,t,n,r){let o=JSON.stringify([e,t,n]),s=i.get(o);s===void 0&&(s={kind:e,direction:t,node_id:n,endpoints:new Set},i.set(o,s)),s.endpoints.add(r)}function B(i,e){let t=new Map;for(let n of i)for(let r of n.dependencies??[]){let o=e.resolve(r.kind);o===void 0||o.hierarchy||(o.outgoing==="one"&&J(t,o.kind,"outgoing",n.id,r.id),o.incoming==="one"&&J(t,o.kind,"incoming",r.id,n.id))}return t}function Ie(i,e,t=m()){let n=B(i,t),r=B(e,t);for(let o of[...r.keys()].sort()){let s=r.get(o);if(s.endpoints.size<=1)continue;let c=n.get(o);if(![...s.endpoints].every(a=>c?.endpoints.has(a)))throw new C(`Relationship ${s.kind} permits only one ${s.direction} endpoint for ${s.node_id}.`,S.USAGE,{code:"dependency_cardinality_created",field:"dependencies",value:s.kind,relationship_cardinality:{kind:s.kind,direction:s.direction,node_id:s.node_id,endpoint_ids:[...s.endpoints].sort()},required:"The final dependency set must satisfy the active relationship kind's one-edge cardinality.",nextSteps:["Drop extra --dep seeds, or remove conflicting rows with update --dep-remove before adding another edge.","Choose another kind only when its declared semantics match the intended relationship."]})}}export{T as a,F as b,ve as c,Ee as d,Ie as e};
8
- //# sourceMappingURL=chunk-67M7E2Z3.js.map
8
+ //# sourceMappingURL=chunk-P6KYUJD4.js.map