@unbrained/pm-cli 2026.11.12 → 2026.11.13

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 (115) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/CHANGELOG.md +11 -0
  3. package/dist/cli-bundle/bundle-manifest.json +1 -1
  4. package/dist/cli-bundle/chunks/{chunk-3DWEBVIK.js → chunk-36E4L2R4.js} +2 -2
  5. package/dist/cli-bundle/chunks/{chunk-FJNHTBJ2.js → chunk-4WD4CHVH.js} +2 -2
  6. package/dist/cli-bundle/chunks/{chunk-OBTU2BHJ.js → chunk-5LG5YZYF.js} +2 -2
  7. package/dist/cli-bundle/chunks/{chunk-UY7Z3ZHQ.js → chunk-6UXBWMEM.js} +2 -2
  8. package/dist/cli-bundle/chunks/{chunk-OFIXSWJS.js → chunk-CO7RWLCM.js} +2 -2
  9. package/dist/cli-bundle/chunks/chunk-COTC2QOR.js +6 -0
  10. package/dist/cli-bundle/chunks/{chunk-6ESY4Y2B.js → chunk-FAYX6C7H.js} +2 -2
  11. package/dist/cli-bundle/chunks/{chunk-PS2YAPXC.js → chunk-GIAJX2QJ.js} +2 -2
  12. package/dist/cli-bundle/chunks/{chunk-GLPUIQDB.js → chunk-GWVP23RZ.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-GDS4DC5A.js → chunk-GXGMMIZN.js} +4 -4
  14. package/dist/cli-bundle/chunks/{chunk-PZI6CR24.js → chunk-HQINCDF6.js} +47 -47
  15. package/dist/cli-bundle/chunks/{chunk-U7MZIX3D.js → chunk-IYDIPXBO.js} +2 -2
  16. package/dist/cli-bundle/chunks/{chunk-KJL42AN5.js → chunk-L4F4ZHGR.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-T4UC3ZKL.js → chunk-LKVFPQNY.js} +2 -2
  18. package/dist/cli-bundle/chunks/{chunk-MR3CRLA7.js → chunk-O6PBQMD7.js} +2 -2
  19. package/dist/cli-bundle/chunks/{chunk-5NY6EQSX.js → chunk-O6T24Z3M.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-L3SA3354.js → chunk-OQCVU2SG.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-2DUUL53Z.js → chunk-PUU5DXSV.js} +2 -2
  22. package/dist/cli-bundle/chunks/chunk-QSSENTXG.js +20 -0
  23. package/dist/cli-bundle/chunks/{chunk-UTNPDAID.js → chunk-TCYIGAQG.js} +31 -31
  24. package/dist/cli-bundle/chunks/chunk-UFZQPKQS.js +124 -0
  25. package/dist/cli-bundle/chunks/{chunk-EALO2FPM.js → chunk-URWNUZQZ.js} +2 -2
  26. package/dist/cli-bundle/chunks/{chunk-2K6GJUW7.js → chunk-UYARS5XF.js} +2 -2
  27. package/dist/cli-bundle/chunks/{item-revision-SYJT6TVZ.js → item-revision-G5OVYGZ5.js} +2 -2
  28. package/dist/cli-bundle/chunks/item-transaction-I2X2P4TW.js +2 -0
  29. package/dist/cli-bundle/chunks/{mutation-admission-T57TAVWI.js → mutation-admission-SET4KY73.js} +2 -2
  30. package/dist/cli-bundle/chunks/{register-list-query-5XZXTPNG.js → register-list-query-JNJY2D3N.js} +2 -2
  31. package/dist/cli-bundle/chunks/{register-mutation-V6WJFL77.js → register-mutation-WTHZHPOP.js} +2 -2
  32. package/dist/cli-bundle/chunks/{register-operations-5RAWXY2F.js → register-operations-EZP3EG6A.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-setup-HCKCSQWQ.js → register-setup-THFZP23A.js} +2 -2
  34. package/dist/cli-bundle/chunks/{stage-VIDXGF3T.js → stage-JXJILTYE.js} +2 -2
  35. package/dist/cli-bundle/focused-chunks/chunk-2ZPGEGTB.js +2 -0
  36. package/dist/cli-bundle/focused-chunks/{chunk-NSOXVVQX.js → chunk-3MB47JLT.js} +2 -2
  37. package/dist/cli-bundle/focused-chunks/{chunk-5OCUNAQN.js → chunk-4LFE3FQL.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/chunk-5KTOMFLR.js +44 -0
  39. package/dist/cli-bundle/focused-chunks/{chunk-MK7UQEE5.js → chunk-5NTLNE54.js} +18 -18
  40. package/dist/cli-bundle/focused-chunks/{chunk-P6KYUJD4.js → chunk-ADBFVDTG.js} +2 -2
  41. package/dist/cli-bundle/focused-chunks/{chunk-AXPRCCYM.js → chunk-CSKDIMQP.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-IPIFI4NT.js → chunk-FNIX62V6.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/{chunk-VUNX6NBR.js → chunk-IYV3IPRF.js} +51 -51
  44. package/dist/cli-bundle/focused-chunks/{chunk-KN7RBRRH.js → chunk-J3LQQP3N.js} +22 -22
  45. package/dist/cli-bundle/focused-chunks/{chunk-BHYGUVAU.js → chunk-JR75B6HU.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-NP5C2TQM.js → chunk-Q3OA5OAK.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-TZO6L523.js → chunk-QGQJBQCH.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-GB2N4OM7.js → chunk-RIMNSVFA.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-GBW2EAAG.js → chunk-TVJ2PHAK.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-LAIN47EJ.js → chunk-VGFKTSGY.js} +2 -2
  51. package/dist/cli-bundle/focused-chunks/{chunk-RXY6BFRW.js → chunk-VGJDKDKA.js} +2 -2
  52. package/dist/cli-bundle/focused-chunks/chunk-VGUQ4V47.js +82 -0
  53. package/dist/cli-bundle/focused-chunks/chunk-VTOTZ5UC.js +91 -0
  54. package/dist/cli-bundle/focused-chunks/{chunk-SPAEZKVA.js → chunk-WFVZ7GGR.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/{chunk-3FN4ON2Z.js → chunk-ZJF6ZA7B.js} +2 -2
  56. package/dist/cli-bundle/focused-chunks/{chunk-GAXO2UQX.js → chunk-ZOGEQFGH.js} +2 -2
  57. package/dist/cli-bundle/focused-chunks/{item-revision-PWJNBW3F.js → item-revision-IF7E7BVY.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{item-transaction-T6HXC3NS.js → item-transaction-5TFWIOXI.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/{mutation-admission-CLPOLSXZ.js → mutation-admission-KELM46JF.js} +2 -2
  60. package/dist/cli-bundle/focused-chunks/{stage-EKYWEU2Y.js → stage-UAKMQTCI.js} +2 -2
  61. package/dist/cli-bundle/main.js +2 -2
  62. package/dist/cli-bundle/sdk-authoring.js +1 -1
  63. package/dist/cli-bundle/sdk-contracts.js +1 -1
  64. package/dist/cli-bundle/sdk-core.js +1 -1
  65. package/dist/cli-bundle/sdk-governance.js +1 -1
  66. package/dist/cli-bundle/sdk-graph.js +1 -1
  67. package/dist/cli-bundle/sdk-merge.js +57 -57
  68. package/dist/cli-bundle/sdk-query.js +1 -1
  69. package/dist/cli-bundle/sdk-runtime.js +1 -1
  70. package/dist/cli-bundle/sdk-testing.js +1 -1
  71. package/dist/cli-bundle/sdk.js +1 -1
  72. package/dist/core/history/history-rewrite.js +1 -1
  73. package/dist/core/schema/runtime-field-values.js +1 -1
  74. package/dist/core/shared/author.js +2 -2
  75. package/dist/core/shared/secret-rules.d.ts +8 -2
  76. package/dist/core/shared/secret-rules.js +3 -3
  77. package/dist/core/shared/url-credentials.d.ts +33 -5
  78. package/dist/core/shared/url-credentials.js +1 -1
  79. package/dist/core/store/item-store.js +1 -1
  80. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  81. package/dist/sdk/lifecycle/claim.js +1 -1
  82. package/dist/sdk/lifecycle/create.js +1 -1
  83. package/dist/sdk/lifecycle/restore.js +1 -1
  84. package/dist/sdk/lifecycle/update.js +2 -2
  85. package/dist/sdk/ownership-source.js +1 -1
  86. package/docs/MUTATION_INTEGRITY.md +56 -6
  87. package/marketplace.json +1 -1
  88. package/package.json +1 -1
  89. package/packages/pm-beads/package.json +1 -1
  90. package/packages/pm-calendar/package.json +1 -1
  91. package/packages/pm-command-kit/package.json +1 -1
  92. package/packages/pm-digital-twin/package.json +1 -1
  93. package/packages/pm-governance-audit/package.json +1 -1
  94. package/packages/pm-guide-shell/package.json +1 -1
  95. package/packages/pm-kanban/package.json +1 -1
  96. package/packages/pm-lifecycle-hooks/package.json +1 -1
  97. package/packages/pm-linked-test-adapters/package.json +1 -1
  98. package/packages/pm-search-advanced/package.json +1 -1
  99. package/packages/pm-templates/package.json +1 -1
  100. package/packages/pm-todos/package.json +1 -1
  101. package/packages/pm-vcs/package.json +1 -1
  102. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  103. package/plugins/pm-claude/package.json +1 -1
  104. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  105. package/plugins/pm-codex/package.json +1 -1
  106. package/plugins/pm-codex/plugin.json +1 -1
  107. package/runtime-dependencies.json +1 -1
  108. package/dist/cli-bundle/chunks/chunk-5NGGI7JC.js +0 -6
  109. package/dist/cli-bundle/chunks/chunk-A7L5IEYV.js +0 -20
  110. package/dist/cli-bundle/chunks/chunk-FOT5K5OM.js +0 -124
  111. package/dist/cli-bundle/chunks/item-transaction-YXZ27UC6.js +0 -2
  112. package/dist/cli-bundle/focused-chunks/chunk-AIYJHVKV.js +0 -44
  113. package/dist/cli-bundle/focused-chunks/chunk-BB2GMKRB.js +0 -2
  114. package/dist/cli-bundle/focused-chunks/chunk-HIKZYZ26.js +0 -82
  115. package/dist/cli-bundle/focused-chunks/chunk-NY65XTX7.js +0 -91
@@ -1,54 +1,54 @@
1
- import{A as h,C as g,E as gt,F as be,G as Z,H as Ae,I as Kd,J as _s,K as bt,L as Yd,a as je,b as ps,c as Hd,e as Kr,f as Yr,g as Xr,h as qd,i as Jr,j as on,k as Vd,m as Ve,n as Bd,o as Wd,p as Qr,q as Zr,u as Vn,v as Gd,y as S,z as Bn}from"./chunk-O4ZLEN4T.js";import bh 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]="77f9d61e-e78b-5b6a-a769-1ad6e5b91777")}catch{}})();function wh(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function vh(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=eo(o))}return n}function eo(e){let t=wh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>eo(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return eo(r)}return vh(e)}function R(e){return JSON.stringify(eo(e))}function Xd(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function Eh(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function kh(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function Sh(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!Xd(o,n,r,B))return!1;return!0}function Oh(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!Xd([o,i],n,r,([s,a],[c,d])=>B(s,c)&&B(a,d)))return!1;return!0}function Ah(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>B(n,t[r]))}function Ih(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!B(e[i],t[i]))return!1}return!0}var Th=[Eh,kh,Sh,Oh,Ah];function B(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of Th){let r=n(e,t);if(r!==void 0)return r}return Ih(e,t)}function to(e){return bh.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}import{createHash as Qd}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]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();var Ch=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],Jd=256,ys=64;function le(e){throw new g(`Invalid workflow policy: ${e}`,h.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function $e(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return le(`${n} must be an object`);let r=e;return Object.keys(r).some(o=>!t.includes(o))?le(`${n} contains an unknown key`):r}function wt(e,t,n=128){return typeof e!="string"||!e.trim()||e.length>n?le(`${t} must be nonempty text of at most ${n} characters`):e.trim()}function Wn(e,t){if(!Array.isArray(e)||e.length===0||e.length>ys)return le(`${t} requires 1-${ys} terms`);let n=e.map(r=>wt(r,t));return t==="fields"&&n.some(r=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(r)||r.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?le("fields must be safe metadata paths of at most eight segments"):[...new Set(n)]}function Rh(e){let t=$e(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?($e(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>ys?le("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(n=>!Array.isArray(n)||n.length!==2?le("transition pairs need two statuses"):[wt(n[0],"from"),wt(n[1],"to")])}):t.kind==="authors"?($e(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Wn(t.authors,"authors")}):t.kind==="require_fields"?($e(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Wn(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?($e(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Wn(t.fields,"fields"),authors:Wn(t.authors,"authors")}):le("unknown rule kind")}function xh(e){let t={},n=$e(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let r of["types","tags","statuses","operations","parents"])n[r]!==void 0&&(t[r]=Wn(n[r],r));if(n.dependency!==void 0){let r=$e(n.dependency,["kind","id"],"dependency");t.dependency={kind:wt(r.kind,"dependency kind"),...r.id===void 0?{}:{id:wt(r.id,"dependency id")}}}return t}function Nh(e){let t=$e(e,["id","description","subject","effect","rule"],"policy"),n=wt(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(n)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?le("effect must be advise, warn, or refuse"):{id:n,rule:Rh(t.rule),...t.subject===void 0?{}:{subject:xh(t.subject)},...t.description===void 0?{}:{description:wt(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:le("id must be a stable token")}function Dh(e){let t=$e(e,["version","enforcement","policies"],"document");if(t.version!==1)return le("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return le("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>Jd)return le(`policies must contain at most ${Jd} declarations`);let n=t.policies.map(Nh);return new Set(n.map(r=>r.id)).size!==n.length?le("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:n}}function no(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function Ph(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function Zd(e){return Qd("sha256").update(R(e)).digest("hex")}function Mh(e,t){let n=e.rule.kind==="approval"?e.rule.fields:[];return Qd("sha256").update(R({id:t.id,fields:n.map(r=>[r,no(t,r)])})).digest("hex")}function jh(e,t){return Array.isArray(t)&&t.some(n=>typeof n=="object"&&n!==null&&"kind"in n&&n.kind===e.kind&&(e.id===void 0||"id"in n&&n.id===e.id))}function $h(e,t,n){return!(e.types&&!e.types.some(r=>r.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(n)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(r=>t.tags.includes(r)))||e.dependency&&!jh(e.dependency,t.dependencies))}function Lh(e,t){if(t.completeness_only&&(e.rule.kind!=="require_fields"||e.subject?.operations!==void 0)||e.rule.kind==="approval"&&t.before===null)return!1;let n=e.subject??{},r=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&$h(n,{...o,status:r},t.operation))}function Fh(e,t,n,r){let o=["type","tags","parent","dependencies"].some(i=>!B(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||n||r||o)?e.filter(i=>!Ph(no(t.after,i))):[]}function Uh(e,t,n,r){let o=t.after??t.before,i=Mh(e,o);return t.approvals?.some(s=>s.policy_fingerprint===r&&s.content_fingerprint===i&&s.author!==t.author&&n.includes(s.author))??!1}function zh(e,t,n){let r=e.rule,o=t.before?.status!==t.after?.status,i="fields"in r&&r.fields.some(s=>!B(no(t.before,s),no(t.after,s)));switch(r.kind){case"require_fields":{let s=Fh(r.fields,t,o,i);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!o||r.allowed.some(([s,a])=>s===String(t.before?.status??"$create")&&a===String(t.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||Uh(e,t,r.authors,n),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function el(e,t,n){let r=e.policies.filter(o=>Lh(o,t)).map(o=>{let i=o.effect??"advise",s=n(o);return{policy_id:o.id,policy_fingerprint:s,rule:o.rule.kind,effect:i==="refuse"&&e.enforcement!=="refuse"?"warn":i,...zh(o,t,s)}});return{allowed:!r.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:r,warnings:r.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function zR(e,t){return el(e,t,Zd)}function HR(e){let t=Dh(e),n=new Map(t.policies.map(r=>[r,Zd(r)]));return r=>el(t,r,o=>n.get(o))}(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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var Hh=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-tqel"})),qh=[...["next","focus"].map(e=>({alias:e,canonical:`context ${e}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-6apl"})),...["normalize","reindex"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(e=>({...e,canonical_argv:e.canonical.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap"})),Vh=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-ik19"})),Bh=[...qh,...Vh,...["init","config","schema","profile"].map(e=>({alias:e,canonical:`workspace ${e}`,canonical_argv:["workspace",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(e=>[e,`item ${e}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(e=>[`completion-${e}`,`completion ${e}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(e=>[e,`calendar ${e}`,"pm-o3fh"])].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:n}))],hs=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...Hh,...Bh,...["discover","lookup"].map(e=>({alias:`files ${e}`,canonical:`item files ${e}`,canonical_argv:["item","files",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-yql1"}))];function VR(e){let t;for(let n of hs)n.canonical_argv.length<=(t?.canonical_argv.length??0)||n.canonical_argv.every((r,o)=>r===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=n);return t}function Wh(e){let t=e.trim().replace(/\s+/gu," ");return hs.find(n=>n.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function Gn(e){return Wh(e)}var ro=[...hs,...[["ctx","context"],["packages","package"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:[t,n],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:["comments","notes","learnings"].includes(t)?`item ${t}`:t,canonical_argv:["comments","notes","learnings"].includes(t)?["item",t]:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],BR=Object.fromEntries(ro.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function WR(e){let t=e.trim().toLowerCase();return ro.find(n=>n.alias===t)}function GR(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(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]="3348c61d-a03e-5023-a5dc-fd6149f478c1")}catch{}})();var Gh=[...je],Kh=[...on],Yh=[...Kr],QR=[...Yr],ZR=[...Xr],Xh=[...Jr],oo=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-attest","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],ex=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],tx=["install","reconcile","report","driver"],Jh=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],Qh=["upgrade"],Zh=["reopen"],tl={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},sn=Object.freeze(oo.flatMap(e=>e in tl?[]:e==="extension"||e==="package"?[...Jh.map(t=>`${e}-${t}`),...e==="package"?Qh.map(t=>`package-${t}`):[],e]:e==="item"?Zh.map(t=>`item-${t}`):[e])),eg=Object.freeze(ro.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&sn.includes(e.alias)).map(e=>e.alias)),nx=Object.freeze(sn.filter(e=>!eg.includes(e)));function rx(e=oo,t=sn,n=tl){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function ox(e){return sn.includes(e)}function ix(e){return Gh.includes(e)}function sx(e){return Kh.includes(e)}function ax(e){return Yh.includes(e)}function cx(e){return Xh.includes(e)}var dx=new Set(["update","item-reopen","close","claim","release","start-task","pause-task","close-task","restore","append","update-many","close-many","delete","comments","notes","learnings","files","docs","test","test-all","plan","history-redact","history-repair","history-compact","validate"]);(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]="b181d38e-7120-5d34-98d9-fd9b4619b9d9")}catch{}})();var tg=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],nl=tg,an=["draft","open","in_progress","blocked","closed","canceled"],io=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],cn=["string","number","boolean","string_array","array","object"],so=["create","update","update_many","list","search","calendar","context"],ao=["allow","warn","reject"],ux=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],fx=["project","global"],mx=["low","medium","high","critical"],co=["low","medium","high","critical"],lo=["low","medium","high"];var rl=["minimal","default","strict","custom"],px=["none","warn","strict"],_x=["progressive","strict"],yx=["off","warn","strict"],hx=["off","warn","strict"],ol=["off","warn","strict"];var uo=["daily","weekly","monthly","yearly"],Kn=["mon","tue","wed","thu","fri","sat","sun"];function gs(e){return Kn.indexOf(e)}var gx=["draft","research","review","approved","executing","paused","completed","superseded"],il=["pending","in_progress","completed","blocked","skipped","superseded"],bx=["codex","claude-code","cursor","generic"],wx=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],sl=["brief","standard","deep","full"],vx=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(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]="0ca7f52c-fb31-5cd9-b689-a918f4e61816")}catch{}})();import sg 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]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function Be(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ng(e){let t=e.key.trim();if(t.length===0)return null;let n=Be(e.aliases),r=e.description?.trim();return{key:t,values:Be(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var rg=e=>e,cl=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function og(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function ig(e,t){let n=new Map;for(let r of e??[]){let o=og(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function al(e,t){return t?Be(e):void 0}function bs(e){let t=e?.trim();return t&&t.length>0?t:void 0}function ws(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function fo(e,t={}){let n=t.resolvePolicyCommand??rg,r=e.name.trim();if(r.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Be(e.aliases),d=(e.options??[]).map(u=>ng(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=ig(e.command_option_policies,n);return{name:r,description:bs(e.description),default_status:bs(e.default_status),...e.execution_role===void 0?{}:{execution_role:ws(e.execution_role)},folder:bs(e.folder),aliases:c.length>0?c:void 0,required_create_fields:al(e.required_create_fields,o),required_create_repeatables:al(e.required_create_repeatables,i),options:s?d:void 0,command_option_policies:a?l:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f40ddc8e-1dd5-5f26-b2ba-fbbac30a1781")}catch{}})();var ag=Object.freeze({decision:"human",milestone:"gate"}),cg=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],dg=["dep","comment","note","learning","file","test","doc"],ll=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],lg=["title","description","type","status","priority","tags","body",...ll,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],ug=["title","description","body","status","closeReason","priority","type","tags",...ll,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],ul={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},fg={...ul},mg={...ul},fl=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],ml=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function pl(e){return Object.fromEntries(e)}var pg=pl([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...fl,["author","--author"],["message","--message"],["dep","--dep"],...ml]),_g=pl([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...fl,...ml,["author","--author"],["message","--message"],["force","--force"]]);function yg(e){return e.trim().replace(/^--+/,"").toLowerCase()}function hg(e){return e==="create"?lg:ug}function gg(e){return e==="create"?fg:mg}function _l(e,t){let n=yg(t);return n.length===0?void 0:gg(e)[n]||hg(e).find(r=>r.toLowerCase()===n)}function Rx(e,t){return(e==="create"?pg:_g)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function Es(e){let t=wg(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function bg(e){let t=e.trim(),n=t.replaceAll("\\","/").replace(/^\/+/,""),r=sg.posix.normalize(n);if(t.includes("\0")||/^[A-Za-z]:/.test(r)||r==="."||r===".."||r.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return r}function wg(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function vg(e){return fo(e,{resolvePolicyCommand:cl})}function Yn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Eg(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:Yn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Yn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function kg(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function Sg(e){if(Array.isArray(e.options))return e.options.map(t=>Eg(t)).filter(t=>t!==null)}function Og(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>kg(t)).filter(t=>t!==null)}function Ag(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:n,description:o,default_status:i,execution_role:ws(t.execution_role),folder:r,aliases:Yn(t,"aliases"),required_create_fields:Yn(t,"required_create_fields"),required_create_repeatables:Yn(t,"required_create_repeatables"),options:Sg(t),command_option_policies:Og(t)}}function Ig(e,t){return e.required_create_fields?Be(e.required_create_fields):t?.required_create_fields??[]}function Tg(e,t){return e.required_create_repeatables?Be(e.required_create_repeatables):t?.required_create_repeatables??[]}function Cg(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Rg(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function xg(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=bg(e.folder??t?.folder??Es(n)),s={name:n,execution_role:e.execution_role,folder:i,aliases:Be([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Ig(e,t),required_create_repeatables:Tg(e,t),options:Cg(e,t),command_option_policies:Rg(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function dl(e,t){for(let n of e){let r=vg(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,xg({...r,execution_role:r.execution_role??i?.execution_role},i))}}function Ng(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=Ag(o);i&&t.push(i)}}return t}function xx(e,t=null){let n=new Map;for(let c of nl)n.set(c.toLowerCase(),{name:c,execution_role:ag[c.toLowerCase()]??"agent",folder:Vn[c],aliases:[],required_create_fields:[...cg],required_create_repeatables:[...dg],options:[],command_option_policies:[]});dl(e.item_types?.definitions??[],n),dl(Ng(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let d of c.aliases)i[d.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Dg(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Pg(e,t){let n=Dg(e,t);if(n)return t.by_type[n]}function Mg(e,t,n,r){for(let o of r){let i=_l(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function vs(e,t,n){if(n){e.add(t);return}e.delete(t)}function jg(e,t,n,r){let o=_l(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&vs(e.required,o,r.required),r.visible!==void 0&&vs(e.hidden,o,!r.visible),r.enabled!==void 0&&vs(e.disabled,o,!r.enabled)}function $g(e,t,n){for(let r of t.command_option_policies)r.command===n&&jg(e,t,n,r)}function Lg(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function Nx(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Mg(a,e,t,n),$g(a,e,t),Lg(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function Fg(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function Ug(e,t,n){let r=e.values;if(r.length===0)return t;let o=new Map(r.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return o}function Dx(e,t,n){let r=Pg(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Fg(r),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),u=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${l}" must not be empty`);continue}let f=i.get(l.toLowerCase());if(!f){let _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=Ug(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.name}"`);let a=Object.keys(s).sort((c,d)=>c.localeCompare(d));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as zg,readdirSync as Hg,realpathSync as yl,statSync as hl}from"node:fs";import qg from"node:os";import C 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]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();var Vg={json_markdown:".md",toon:".toon"},Bg={".md":"json_markdown",".toon":"toon"},Wg=new Set([".git","coverage","dist","node_modules"]),Hx=[".md",".toon"];function Xn(e){try{return hl(e),!0}catch{return!1}}function Gg(e){let t=C.resolve(e),n=[];for(;C.dirname(t)!==t;)try{return C.join(yl(t),...n)}catch(r){if(!be(r))throw r;n.unshift(C.basename(t)),t=C.dirname(t)}return C.join(yl(t),...n)}function Kg(e){try{return hl(e),!0}catch(t){if(be(t))return!1;throw t}}function gl(e){try{let t=JSON.parse(zg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function Yg(e){let t=Gg(e);for(;;){let n=C.join(t,Qr),r=C.join(n,Zr);if(Xn(r))return n;let o=C.join(t,Zr);if(Xn(o)&&gl(o))return t;if(Kg(C.join(t,".git")))return n;let i=C.dirname(t);if(i===t)return;t=i}}function ks(e){return Yg(e)??C.resolve(e,Qr)}function qx(e,t){let n=t?C.resolve(t):void 0;try{return Hg(C.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!Wg.has(r.name)).map(r=>C.join(C.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Xn(Ie(r))).filter(r=>gl(Ie(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function bl(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=C.resolve(e,r);if(!Xn(Ie(o))){let i=C.join(o,Qr);if(Xn(Ie(i)))return i}return o}return ks(e)}function wl(e){let t=C.resolve(e),n=C.dirname(t);return C.basename(t)==="pm"&&C.basename(n)===".agents"?C.dirname(n):t}function vl(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:C.join(qg.homedir(),".pm-cli");return C.resolve(e,n)}function Ie(e){return C.join(e,Zr)}function Xg(e,t,n=Vn){let r=n[t]??Es(t);return C.join(e,r)}function Vx(e,t,n,r="toon",o=Vn){return C.join(Xg(e,t,o),`${n}${Vg[r]}`)}function Bx(e){let t=e.replaceAll("\\","/"),n=C.posix.extname(t).toLowerCase();return Bg[n]??null}function Wx(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return C.join(e,"history",`${t}.jsonl`)}function Ss(e,t){return C.join(e,"locks",`${t}.lock`)}function Os(e){return C.join(e,"runtime")}function mo(e){return C.join(Os(e),"test-runs")}function Jg(e){return C.join(mo(e),"runs")}function Gx(e,t){return C.join(Jg(e),`${t}.json`)}function Qg(e){return C.join(mo(e),"stdout")}function Zg(e){return C.join(mo(e),"stderr")}function Kx(e,t){return C.join(Qg(e),`${t}.log`)}function Yx(e,t){return C.join(Zg(e),`${t}.log`)}function eb(e){return C.join(mo(e),"results")}function Xx(e,t){return C.join(eb(e),`${t}.json`)}(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]="86412887-5659-5892-beaa-bdd15a02ff4c")}catch{}})();var po=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},El=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?po(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,dn=(e,t=process.platform)=>{let n=e.map(r=>El(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import{AsyncLocalStorage as tb}from"node:async_hooks";(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]="57597166-3d5e-501a-bde0-676a77898250")}catch{}})();var As="[redacted]";function kl(e){let t=e.lastIndexOf("@"),n=e.indexOf(":");if(t<0||n<0||n>t)return;let r=n+1;for(;r<t&&r<n+3&&(e[r]==="/"||e[r]==="\\");)r+=1;return r===t?void 0:[r,t]}function Sl(e){let t=kl(e);return t?`${e.slice(0,t[0])}${As}${e.slice(t[1])}`:e}var _o=6,nb=65536,Ol={carried:!1,fragments:new Set,fragmentLength:_o,shortSpellings:[]},Is=new tb;function Al(e){let t=e.toLowerCase();if(t.length===e.length)return t;let n="";for(let r of e){let o=r.toLowerCase();n+=o.length===r.length?o:r}return n}function rb(e){return[e,e.replaceAll(/(["\\$`])/gu,"\\$1"),po(`${e}@`).slice(1,-2),JSON.stringify(e).slice(1,-1)]}function ob(e){let t=e.indexOf(":");return t>=0&&t<e.length-1?e.slice(t+1):e}function ib(e){let t=new Set,n=!1;for(let d of e){let l=kl(d);if(l){n=!0;for(let u of rb(ob(d.slice(l[0],l[1]))))t.add(Al(u))}}let r=[...t],o=r.reduce((d,l)=>d+Math.max(0,l.length-_o+1)+1,0),i=Math.max(1,Math.ceil(o/nb)),s=Math.max(_o,i),a=new Set,c=new Set;for(let d of r){if(d.length<s){(d.length>=_o||/\s/u.test(d))&&c.add(d);continue}for(let l=0;l+s<=d.length;l+=i)a.add(d.slice(l,l+s));a.add(d.slice(-s))}return{carried:n,fragments:a,fragmentLength:s,shortSpellings:[...c]}}function sb(e,t){let n=Al(e),r=new Uint8Array(e.length),o=!1,i=t.fragmentLength;for(let a=0;a+i<=n.length;a+=1)t.fragments.has(n.slice(a,a+i))&&(r.fill(1,a,a+i),o=!0);for(let a of t.shortSpellings)for(let c=n.indexOf(a);c>=0;c=n.indexOf(a,c+1))r.fill(1,c,c+a.length),o=!0;if(!o)return e;let s="";for(let a=0;a<e.length;a+=1)r[a]?(a===0||!r[a-1])&&(s+=As):s+=e[a];return s}function ab(e,t){return Is.run(ib(e),t)}function cb(){return(Is.getStore()??Ol).carried}function db(e){let t=Is.getStore()??Ol,n=t.carried?sb(e,t):e;return n.includes("@")?n.replaceAll(/\S+/gu,Sl):n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9bb3b2ed-c289-5b96-99ce-9df6e202c464")}catch{}})();var Il=new Set(["--pm-path","--path","--author","--expect-hash","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),lb=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function ub(e){let t=e.indexOf("=");return t>0&&Il.has(e.slice(0,t))}function fb(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function yo(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")return;if(Il.has(n)){t+=fb(n,e[t+1])?1:0;continue}if(!(ub(n)||lb.has(n)||n==="--profile"||n==="--id-only"||n==="--explain")&&!n.startsWith("-"))return t}}function nN(e){let t=yo(e);return t===void 0?void 0:e[t].trim().toLowerCase()}import mb from"node:path";import Tl from"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]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();function Jn(e,t){let n=Tl.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!Tl.isAbsolute(n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f08c44a-dfdf-5c23-8f68-0e3ed73582b0")}catch{}})();var Ts=new WeakMap;function fN(e){Ts.set(e,e.path)}function pb(e){if(!process.env.PM_PATH?.trim())return;let t=bl(e);return Jn(wl(t),e)&&t===ks(e)?void 0:mb.relative(e,t)||"."}function mN(e,t=process.cwd()){let n=Ts.has(e)?Ts.get(e):e.path,r=n?.trim()?n:pb(t),o=r?["--pm-path",r]:[];return e.noExtensions&&o.push("--no-extensions"),o}var _b=new Set(["--literal","--regex","--replacement"]);function yb(e){let t=yo(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let n=e.slice(t+1),r=yo(n);return r!==void 0&&n[r]==="redact"}function pN(e){if(!yb(e))return[...e];let t=[],n=!1;for(let r of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!_b.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!0}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4155698-c244-5623-b627-92dd25297125")}catch{}})();var hb=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields",extension_command_availability:"read_output"},{flag:"--output-limit",value_name:"count",extension_command_availability:"read_output"},{flag:"--output-budget",value_name:"tokens",extension_command_availability:"read_output"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state",extension_command_availability:"read_output"},{flag:"--output-cursor",value_name:"cursor",extension_command_availability:"read_output"},{flag:"--output-row-contract",extension_command_availability:"read_output"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"],discovery_value_name:"path"},{flag:"--no-extensions",extension_command_availability:"never"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),ho=new Set(hb.flatMap(e=>[e.flag,...e.aliases??[]]));(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]="81054684-60df-57c9-af9d-0996874c1024")}catch{}})();var Cl=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function Cs(e){if(typeof e!="string")return null;let t=Cl.exec(e.trim());if(!t)return null;let n=t[2];return{name:t[1],valueName:n?n.slice(1,-1):null,optional:n?.startsWith("[")??!1}}function gN(e){let t=Cs(e);return t?t.name:typeof e=="string"&&e.trim()||null}function gb(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return ho.has(n)||ho.has(`--${n.slice(2).replaceAll("_","-")}`)?"host_owned_flag_collision":Cl.test(t)?null:"malformed_long_flag"}function Rl(e,t){let n=[e,t].find(i=>typeof i=="string"&&ho.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=gb(r);return o===null?null:{token:r,failure:o}}function xl(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function bb(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function wN(e){return bb(e)??void 0}function vN(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function EN(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function Dl(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function go(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}function kN(e){let t=go(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function SN(e,t,n){let r=go(e);return r===null||r<t||r>n?null:r}function ON(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function We(e){return typeof e!="object"||e===null?null:e}function Nl(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Pl(e){let t=Nl(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=Nl(t.default);return typeof n?.activate=="function"?n:null}function AN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e}:{}}(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]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function bo(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import wb from"node:crypto";import{AsyncLocalStorage as vb}from"node:async_hooks";(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]="ced47074-06d3-53b9-af75-63586cbd4f6a")}catch{}})();var Rs=new vb,Ml=1024;function Eb(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function kb(e){let t={...Eb(e),clockReads:0,tokenReads:0};return n=>Rs.run(t,n)}async function xN(e,t){return kb(e)(t)}function jl(){let e=Rs.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}function NN(e){let t=Rs.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Ml)throw new Error(`Reproducible token length must be an integer between 0 and ${Ml}`);let n="";for(;n.length<e;){let r=wb.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var Sb=/^([+-]?)(\d+)([hdwm])$/i,Ob=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Ab=/^(\d{4})(\d{2})(\d{2})$/,Ib=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Tb=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Cb=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Rb=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Te(){return jl()??new Date().toISOString()}function Le(e){return Number.isFinite(Date.parse(e))}function Qn(e){let t=Rb.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=Ds(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function ln(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return Qn(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var xb=1e4,wo=new Map;function $l(e){let t=wo.get(e);if(t!==void 0)return t;let n=Date.parse(e);return wo.size>=xb&&bo(wo),wo.set(e,n),n}function re(e,t){let n=$l(e),r=$l(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function LN(e,t){return!(t.deadlineBefore&&(!e.deadline||re(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||re(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&re(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&re(e.updated_at,t.updatedBefore)>0||t.createdAfter&&re(e.created_at,t.createdAfter)<0||t.createdBefore&&re(e.created_at,t.createdBefore)>0)}function xs(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function Ns(e){if(!e)return"";if(e.toUpperCase()==="Z")return"Z";let t=/^([+-]\d{2})(\d{2})$/.exec(e);return t?`${t[1]}:${t[2]}`:e}function Nb(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function Db(e){let t=[],n=d=>Nb(t,e,d),r=Ab.exec(e);if(r){let[,d,l,u]=r;n(`${d}-${l}-${u}`)}let o=Ib.exec(e);if(o){let[,d,l,u,f,m,_,y,b]=o,v=_?`:${_}`:"";n(`${d}-${l}-${u}T${f}:${m}${v}${xs(y)}${Ns(b)}`)}let i=Tb.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${xs(m)}${Ns(_)}`)}let s=Cb.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${xs(m)}${Ns(_)}`)}let a=10,c=e.slice(0,a);if(Mb(c)){let d=a;for(;d<e.length&&jb(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function Pb(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of Db(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Mb(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function jb(e){return e?e===" "||e===" "||e===`
2
- `||e==="\r"||e==="\f"||e==="\v":!1}function Ds(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var $b=["January","February","March","April","May","June","July","August","September","October","November","December"],Lb=/^(\d{4})-(\d{2})-(\d{2})/,Fb=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Ub(e,t,n){let r=Lb.exec(t)??Fb.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=Ds(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${$b[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function zb(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,Ds(i,s));return n.setUTCFullYear(i,s,a),n}function FN(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=Sb.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return zb(t,a).toISOString();let d=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*d).toISOString()}Ub(e,r,n);let i=Pb(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Ob.test(r)?"Compound relative expressions like +3d+1h are not supported; use a single relative token (for example +3d) or an ISO/date string.":'Use ISO/date string input, "now", or relative +6h/-6h/+1d/-1d/+2w/-2w/+6m/-6m.';throw new g(`Invalid ${s} value "${e}". ${a}`,h.USAGE,{field:s,value:e})}return new Date(i).toISOString()}(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]="5c3049c3-1d5a-5e7e-a070-35340737a6ab")}catch{}})();var Ll=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function vo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(Ll,t)?Ll[t]:null}function Hb(e,t,n){return!!(e.value_name?.trim()||t||n||e.required===!0||e.list===!0||e.repeatable===!0)}function qb(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function HN(e){let t=qb(e),n=vo(t),r=Cs(e.long),o=e.value_name?.trim()||null,i=!(n==="boolean"&&t!=="bool")&&Hb(e,r?.valueName,t),s=r?.valueName?r.optional:t==="bool";return{value_type:n,value_arity:i?s?"optional":"required":"none",value_name:i?o??r?.valueName??"value":null}}function Fl(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function Ul(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}function qN(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e)?null:{kind:t,received:e,expected:"a finite number"}:typeof e=="boolean"?null:{kind:t,received:e,expected:"true, false, 1, or 0"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function Eo(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let d=s[0];for(let l=1;l<=t.length;l+=1){let u=e[c-1]===t[l-1]?0:1,f=i[l-1]+u,m=s[l-1]+1,_=i[l]+1,y=Math.min(f,m,_);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(y=Math.min(y,o[l-2]+1)),s[l]=y,y<d&&(d=y)}if(d>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?a:null}(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]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var Ps=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!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]="418b3f7f-6350-5878-a362-3948de287baf")}catch{}})();function Oo(e){return e.trim().toLowerCase().replaceAll("-","_")}function Vb(e){if(e===void 0)return;let t=Oo(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function js(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)js(n,t);return Object.freeze(e)}for(let n of Object.values(e))js(n,t);return Object.freeze(e)}function Bb(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function Wb(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function Gb(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function Kb(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=Oo(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function Yb(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function Xb(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function Jb(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var $s=class{#e=new Map;#n=new Map;constructor(t=Ps){for(let n of t)this.register(n)}register(t){let n=Kb(t);if(Yb(t,n),Xb(t,n),Bb(t,n),Wb(t,n),Gb(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Vb(t.inverse),o=[...new Set((t.aliases??[]).map(Oo))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:Jb(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?js(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Oo(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Ls(){return new $s}var vt=Ls();function YN(e){return vt.require(e).kind}function XN(e){return vt.resolve(e)?.kind}function JN(e,t=vt){return t.resolve(e)?.ordering===!0}function Qb(e,t,n,r=vt){let o=Zn(e),i=Zn(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function ko(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function Zb(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=Qb(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function So(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function Zn(e){return typeof e=="string"?e.trim():""}function Ms(e,t){let n=Zn(e);return n&&t.has(n)?n:void 0}function ew(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var zl=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=vt){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=Zb(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(ko));for(let i of this.#r)So(this.#s,i.source,i),So(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(So(this.#s,i.target,i),So(this.#a,i.source,i))}static fromItems(t,n=vt){let r=new Set(t.map(i=>Zn(i.id)).filter(Boolean)),o=[];for(let i of t){let s=Zn(i.id);if(!s)continue;let a=Ms(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=Ms(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Ms(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||ko(a,c)<=0?a:c;o.at(-1)!==d&&o.push(d),a===d&&(i+=1),c===d&&(s+=1)}return Object.freeze(o)}nodes(){return this.#o}hasNode(t){return this.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||ko(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=[...new Set(o.map(c=>c.id))],a=s.slice(0,i);return{value:a,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:a.length<s.length,nextCursor:a.at(-1)}}}neighborEdges(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=o.slice(0,i);return{value:s,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:s.length<o.length,nextCursor:s.at(-1)?.id}}}closure(t,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,u=0,f=!1;e:for(let m=0;m<d.length;m+=1){n.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,r);if(u+=y.length,_.depth>=s){y.some(b=>!a.has(b.id))&&(f=!0);continue}for(let b of y)if(!a.has(b.id)){if(c.length>=i){f=!0;break e}a.add(b.id),c.push(b.id),d.push({id:b.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:u,truncated:f,nextCursor:c.at(-1)}}}shortestPath(t,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,u=0,f=!1;for(let m=0;m<a.length;m+=1){r.signal?.throwIfAborted();let _=a[m];l+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(b=>!d.has(b.id))&&(f=!0);continue}for(let b of y)if(!d.has(b.id)){if(c.set(b.id,_.id),b.id===n)return{value:ew(t,n,c),meta:{visitedNodes:l,inspectedEdges:u,truncated:!1}};d.add(b.id),a.push({id:b.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:u,truncated:f}}}subgraph(t,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,a=new Set;for(let c of o)for(let d of this.#s.get(c)??[])i.has(d.source)&&i.has(d.target)&&this.#c(d,s)&&a.add(d);return{value:{nodes:o,edges:[...a].sort(ko)},meta:r.meta}}};function QN(e,t,n=vt){return{source:e,target:t.id,kind:n.require(t.kind).kind,createdAt:t.created_at,author:t.author}}(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]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();var tw="__pm_suppress_host_output",Fs="@unbrained/pm-cli:suppress-host-output:v1";function Hl(e){return e===void 0?{__pm_suppress_host_output:Fs}:{__pm_suppress_host_output:Fs,result:e}}function Ao(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[tw]===Fs}import un from"node:fs";import Fe from"node:path";import{fileURLToPath as nw}from"node:url";(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]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();var rw="@unbrained/pm-cli";function ow(e){try{return JSON.parse(un.readFileSync(e,"utf8")).name===rw}catch{return!1}}function iw(e){let t=un.existsSync(e)&&un.statSync(e).isDirectory()?Fe.resolve(e):Fe.dirname(Fe.resolve(e));for(;;){let n=Fe.join(t,"package.json");if(un.existsSync(n)&&ow(n))return t;let r=Fe.dirname(t);if(r===t)return;t=r}}function Io(e,t=[]){let n=nw(e);return iw(n)||Fe.resolve(Fe.dirname(n),...t)}function oD(e,t=[]){try{let n=Fe.join(Io(e,t),"package.json");if(!un.existsSync(n))return;let r=JSON.parse(un.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function iD(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?Fe.resolve(o.trim()):n?Io(n,r):process.cwd()}(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]="447bb510-051a-5dce-8b7d-e27f4ca781f4")}catch{}})();var To={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},Co=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Et=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","learnings","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];(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]="f8657910-1392-5fae-afda-614b96dc8320")}catch{}})();function U(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function sw(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function pe(e){return e?P(e):{}}function _e(e){return e?P(e):sw()}function P(e){return structuredClone(e)}(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]="615b4955-a30d-5d45-a86d-4bcf7bd9bd7a")}catch{}})();var aw=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),cw=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function dw(e,t){for(let n of cw){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>aw.has(n)?U(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function lw(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>U(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function uw(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>U(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function Ro(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let n={schema_version:1};if(!dw(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=lw(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=uw(i);if(s===null)return null;n.preflight_ownership=s}return n}function lD(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(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]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function er(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ge(e){return je.includes(e)}function ql(e){let t=e.trim().toLowerCase();return Ge(t)?t:null}function Vl(e){return e.filter(t=>!Ge(t))}function Us(e){let t=e.trim().toLowerCase();return t.length===0?null:Hd[t]??null}function Bl(e){let t=er([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Us(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:er(n),legacy_aliases:o}}function fw(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Us(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of je){let a=Eo(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function Wl(e,t,n){let r=je.join(","),o=fw(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function Gl(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function mw(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Us(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:ps,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function pw(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...je],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!Ge(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:ps,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(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]="01116a5e-62d1-591b-9fd0-84ac6e99f8d0")}catch{}})();function tr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function zs(){return{overrides:[],handlers:[]}}function Hs(){return{overrides:[]}}function qs(){return{overrides:[]}}function Vs(){return{overrides:[]}}function Bs(){return{overrides:[]}}function Ws(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(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]="67511565-01f8-58a6-ad06-45b5d0ce831b")}catch{}})();var _w=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function yw(e){return{unknownKeys:Object.keys(e).filter(t=>!_w.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function hw(e){let t=yw(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function Kl(e,t,n){return hw(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as Ke}from"node:os";(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]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();var Yl=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),gw=/^[a-z][a-z0-9_]{0,63}$/u,bw=new Map([[Ke.errno.EACCES,"EACCES"],[Ke.errno.EDQUOT,"EDQUOT"],[Ke.errno.EMFILE,"EMFILE"],[Ke.errno.ENFILE,"ENFILE"],[Ke.errno.ENOMEM,"ENOMEM"],[Ke.errno.ENOSPC,"ENOSPC"],[Ke.errno.EPERM,"EPERM"],[Ke.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),ww={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function vw(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&Yl.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:bw.get(Math.abs(t.errno))??null}function Ew(e,t,n={}){let r=vw(e);if(r===null)return null;if(!gw.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=Yl.get(r);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:n.codes?.[o.category]??ww[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function Xl(e,t,n={}){try{return await t()}catch(r){throw Ew(r,e,n)??r}}(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]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function kw(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ee(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1),o=e.charCodeAt(n.length);return r>=55296&&r<=56319&&o>=56320&&o<=57343?n.slice(0,-1):n}function vD(e){return kw(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function ED(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).size;return o/i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();var Sw=5e3;async function nr(e,t,n){let r=[];for(let o of e)try{await o.run(P(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Ow(e,t){return nr(e.beforeCommand,"beforeCommand",t)}function Aw(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new g(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new g(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Gs(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:P(t.before),after:t.after===null?null:P(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},Sw),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Aw(r,n,t.operation)}}async function Iw(e,t){return nr(e.afterCommand,"afterCommand",t)}async function Ks(e,t){return nr(e.onWrite,"onWrite",t)}async function Ys(e,t){return nr(e.onRead,"onRead",t)}async function Xs(e,t){return nr(e.onIndex,"onIndex",t)}function Tw(e){let t="";e instanceof Error&&typeof e.message=="string"?t=e.message:typeof e=="string"?t=e:typeof e=="object"&&e!==null&&typeof e.message=="string"&&(t=e.message);let n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${Ee(n,r-1)}\u2026`:n}function xo(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?Ee(n,300):void 0}function Cw(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"exit_code"))return;let t=e.exit_code;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return t}async function Js(e,t){let n=U(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,args:P(t.args),options:P(t.options),global:P(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,...t.sdk===void 0?{}:{sdk:t.sdk}});return{handled:!0,result:o,warnings:[],...Object.fromEntries([["exitCode",Cw(o)],["errorCode",xo(o,"code")],["remediation",xo(o,"remediation")]].filter(i=>i[1]!==void 0))}}catch(o){let i=typeof o=="object"&&o!==null&&"exitCode"in o?o.exitCode:void 0;if(typeof i=="number"&&Number.isFinite(i))throw o;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${r.layer}:${r.name}:${r.command}`],errorMessage:Tw(o),...Object.fromEntries([["errorCode",xo(o,"code")],["remediation",xo(o,"remediation")]].filter(s=>s[1]!==void 0))},"cause",{value:o,configurable:!0})}}async function Qs(e,t){let n=U(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};try{let o=await Promise.resolve(r.run({command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel}))??{},i=Array.isArray(o.args)?P(o.args):P(t.args),s=o.options?pe(o.options):pe(t.options),a=o.global?_e(o.global):_e(t.global);return{overridden:!0,context:{command:n,args:i,options:s,global:a,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[`extension_parser_override_failed:${r.layer}:${r.name}:${r.command}`]}}}async function Zs(e,t){let n={command:U(t.command),args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},r=P(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:P(n.args),options:pe(n.options),global:_e(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:P(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?P(i.args):n.args,options:i.options?pe(i.options):n.options,global:i.global?_e(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function Jl(e){return{handled:!1,result:e.payload,warnings:[]}}function Ql(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function Zl(e){return{service:e.service,command:e.command?U(e.command):void 0,args:e.args?P(e.args):void 0,options:e.options?pe(e.options):void 0,global:e.global?_e(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:P(e.payload)}}function Rw(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function eu(e,t){return Rw(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function tu(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&B(e,n.payload)}function nu(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function ea(e,t){let n=Ql(e,t.service);if(n.length===0)return Jl(t);let r=[];for(let o of n)try{let i=Zl(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(tu(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=nu(o,eu(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function ta(e,t){let n=Ql(e,t.service);if(n.length===0)return Jl(t);let r=[];for(let o of n)try{let i=Zl(t),s=await Promise.resolve(o.run(i));if(tu(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=nu(o,eu(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function na(e,t){let n=U(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=pe(t.options),i=_e(t.global),s=r.run({command:n,args:P(t.args),options:o,global:i,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:P(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function xw(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(P(n))}catch{return!1}}function ra(e,t){let n=typeof t.command=="string"?U(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&xw(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?P(t.args):[],i=pe(t.options),s=_e(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,args:o,options:i,global:s,pm_root:a,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:P(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import It from"node:fs/promises";import At from"node:path";import{pathToFileURL as mv}from"node:url";(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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function ru(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([n,r])=>[n,r.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[n,r]of Object.entries(t.registrations))e.registrations[n].length=r}}(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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function ee(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function V(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function ou(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function kt(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function rr(e,t){if(kt(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var oa=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(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]="60fd882d-7c92-5be5-bf46-7e3c128bfb58")}catch{}})();var Nw=new Set(oa);function Dw(e){if(e!==void 0&&!Nw.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${oa.join(", ")}`)}function iu(e){V("registerCommand definition.action",e.action),V("registerCommand definition.family",e.family),V("registerCommand definition.description",e.description),V("registerCommand definition.intent",e.intent),V("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");Dw(e.family)}(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]="095ea29d-eda3-5287-b54d-8a961658f7bc")}catch{}})();function su(e,t="",n=""){if(e===void 0)return;if(fn(t)||fn(n))throw new TypeError("Native pm commands and actions cannot declare read_output");let r=K("registerCommand definition.read_output",e);if(Object.keys(r).some(s=>s!=="row_keys")||!Array.isArray(r.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(r.row_keys),i=new Set(["__proto__","constructor","prototype","row_contract","read_output","read_session","omission_receipt","output_budget_truncation"]);if(o.some(s=>typeof s!="string"||!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*$/u.test(s)||s.split(".").some(a=>i.has(a))))throw new TypeError("registerCommand definition.read_output row_keys must be safe dot-delimited property paths");if(new Set(o).size!==o.length||o.some(s=>o.some(a=>a.startsWith(`${s}.`))))throw new TypeError("registerCommand definition.read_output row_keys must be unique and non-overlapping");return Object.freeze({row_keys:Object.freeze([...o])})}function fn(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return sn.includes(t)||Et.includes(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="07cb237c-3956-5997-85f8-972d2ee490d0")}catch{}})();function Pw(e){let t=K("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return V("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function au(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=Pw(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function ia(e,t,n){return{registration:t,action:n,command:e.command,args:P(e.args),options:P(e.options),global:P(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(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]="fc2e7eac-cd1c-5885-aa27-e98455008a4f")}catch{}})();function cu(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(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]="bb1b4879-079c-50d4-afa5-e8a36ead2e5c")}catch{}})();function we(e){return typeof e!="string"?"":e.trim().toLowerCase()}function M(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function Mw(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function mn(e){return new Set((e??[]).map(t=>Mw(t)).filter(t=>t.length>0))}function du(e){let t=we(e);return Kr.includes(t)?t:"off"}function lu(e){let t=we(e);return Yr.includes(t)?t:"off"}function or(e){let t=we(e);return Xr.includes(t)?t:"none"}function sa(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return qd.includes(t)?t:void 0}function uu(e){if(typeof e=="string"){let t=sa(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:sa(e.global)??"block",project:sa(e.project)??"block"}:{global:"block",project:"block"}}function jw(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function L(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function $w(e){let t=we(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?or(e.sandbox_profile):void 0,allowedCapabilities:M(e.allowed_capabilities),blockedCapabilities:M(e.blocked_capabilities),allowedSurfaces:mn(e.allowed_surfaces),blockedSurfaces:mn(e.blocked_surfaces),allowedCommands:M(e.allowed_commands),blockedCommands:M(e.blocked_commands),allowedActions:M(e.allowed_actions),blockedActions:M(e.blocked_actions),allowedServices:M(e.allowed_services),blockedServices:M(e.blocked_services)}}}function fu(e){let t=new Map;for(let n of e??[]){let r=$w(n);r&&t.set(r.name,r.normalized)}return t}function Lw(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of L([...e.allowedCapabilities,...e.blockedCapabilities]))Ge(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of L([...o.allowedCapabilities,...o.blockedCapabilities]))Ge(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(Jr);for(let o of L([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of L([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function mu(e){let t=e.extensions?.policy??{},n=M(t.allowed_capabilities),r=M(t.blocked_capabilities),o=mn(t.allowed_surfaces),i=mn(t.blocked_surfaces),s=fu(t.extension_overrides);return{mode:du(t.mode),trustMode:lu(t.trust_mode),pmMaxVersionExceededMode:uu(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:M(t.trusted_extensions),defaultSandboxProfile:or(t.default_sandbox_profile),allowedExtensions:M(t.allowed_extensions),blockedExtensions:M(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:M(t.allowed_commands),blockedCommands:M(t.blocked_commands),allowedActions:M(t.allowed_actions),blockedActions:M(t.blocked_actions),allowedServices:M(t.allowed_services),blockedServices:M(t.blocked_services),overridesByName:s,warnings:Lw({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function pu(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:L(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:L(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:L(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:L(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:L(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:L(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:L(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:L(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:L(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:L(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:jw(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:L(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:L(e.allowedExtensions),blocked_extensions:L(e.blockedExtensions),allowed_capabilities:L(e.allowedCapabilities),blocked_capabilities:L(e.blockedCapabilities),allowed_surfaces:L(e.allowedSurfaces),blocked_surfaces:L(e.blockedSurfaces),allowed_commands:L(e.allowedCommands),blocked_commands:L(e.blockedCommands),allowed_actions:L(e.allowedActions),blocked_actions:L(e.blockedActions),allowed_services:L(e.allowedServices),blocked_services:L(e.blockedServices),extension_overrides:t}}function _u(e){let t=fu(e.extension_overrides);return{mode:du(e.mode),trustMode:lu(e.trust_mode),pmMaxVersionExceededMode:uu(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:M(e.trusted_extensions),defaultSandboxProfile:or(e.default_sandbox_profile),allowedExtensions:M(e.allowed_extensions),blockedExtensions:M(e.blocked_extensions),allowedCapabilities:M(e.allowed_capabilities),blockedCapabilities:M(e.blocked_capabilities),allowedSurfaces:mn(e.allowed_surfaces),blockedSurfaces:mn(e.blocked_surfaces),allowedCommands:M(e.allowed_commands),blockedCommands:M(e.blocked_commands),allowedActions:M(e.allowed_actions),blockedActions:M(e.blocked_actions),allowedServices:M(e.allowed_services),blockedServices:M(e.blocked_services),overridesByName:t,warnings:[]}}function Ye(e,t){return e.overridesByName.get(we(t))??null}function pn(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function yu(e,t,n){let r=n.trim().toLowerCase(),o=Ye(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return pn(i,s,r,"capability_not_allowlisted","capability_blocked")}function Fw(e,t,n){let r=Ye(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return pn(o,i,n,"surface_not_allowlisted","surface_blocked")}function Uw(e,t,n){let r=U(n);if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return pn(i,s,r,"command_not_allowlisted","command_blocked")}function zw(e,t,n){let r=we(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return pn(i,s,r,"action_not_allowlisted","action_blocked")}function Hw(e,t,n){let r=we(n);if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return pn(i,s,r,"service_not_allowlisted","service_blocked")}function qw(e,t){let n=we(t.name);return Ye(e,t.name)?.disabled===!0?"extension_override_disabled":pn(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Vw(e,t){if(e.trustMode==="off")return null;let n=Ye(e,t.name),r=we(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function Bw(e,t){if(e.mode==="off")return null;let n=Ye(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(n==="none")return null;let r=t.permissions;if(!r)return"sandbox_permissions_missing";let o=i=>r[i]===!0;return n==="restricted"?o("process_spawn")?"sandbox_restricted_disallows_process_spawn":o("env_write")?"sandbox_restricted_disallows_env_write":null:o("process_spawn")?"sandbox_strict_disallows_process_spawn":o("network")?"sandbox_strict_disallows_network":o("fs_write")?"sandbox_strict_disallows_fs_write":o("env_write")?"sandbox_strict_disallows_env_write":null}function No(e,t,n,r,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${n.layer}:${n.name}:reason=${r}${s}`}function hu(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=qw(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Vw(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=Bw(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:No("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:No("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function gu(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=yu(e,t,n);return r?{allowed:e.mode==="warn",warning:No(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function Ww(e,t,n,r,o){let i=typeof r=="string"?yu(e,t,r):null,s=Fw(e,t,n),a=o.command?Uw(e,t,o.command):null,c=o.action?zw(e,t,o.action):null,d=o.service?Hw(e,t,o.service):null;return i??s??a??c??d}function Gw(e,t,n,r){let o={method:we(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=U(r.command)),r.action&&(o.action=we(r.action).replace(/\s+/g,"-")),r.service&&(o.service=we(r.service)),o}function bu(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=Ww(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=No(e.mode==="warn"?"violation":"blocked","registration",t,a,Gw(r,n,o,s));return{allowed:e.mode==="warn",warning:c}}(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]="cd1de600-27e4-522b-842e-1993c12e9f0e")}catch{}})();var vu=100;function wu(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function Kw(e){if(e==null)return;let t=We(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function aa(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Eu(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function St(e){if(e!=null)return typeof e!="boolean"?null:e}function Yw(e){let t=Eu(e.priority);return t===void 0?vu:t}function Xw(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=or(t);return n!==t.trim().toLowerCase()?null:n}function ca(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function Jw(e){if(e==null)return;let t=We(e);if(!t)return null;let n=ca(t.source),r=ca(t.signature),o=ca(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function Qw(e){if(e==null)return;let t=We(e);if(!t)return null;let n=St(t.fs_read),r=St(t.fs_write),o=St(t.network),i=St(t.env_read),s=St(t.env_write),a=St(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function Zw(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=Bl(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function ev(e){if(e==null)return;let t=We(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>U(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function tv(e){let t=Eu(e.manifest_version);if(t===null)return null;let n=wu(e,"pm_min_version");if(n===null)return null;let r=wu(e,"pm_max_version");if(r===null)return null;let o=Kw(e.engines);if(o===null)return null;let i=St(e.trusted);if(i===null)return null;let s=Xw(e);if(s===null)return null;let a=Jw(e.provenance);if(a===null)return null;let c=Qw(e.permissions);if(c===null)return null;let d=Zw(e.capabilities);if(d===null)return null;let l=ev(e.activation);if(l===null)return null;let u=Ro(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:u}}function da(e){if(typeof e!="object"||e===null)return null;let t=e,n=aa(t,"name");if(n===null)return null;let r=aa(t,"version");if(r===null)return null;let o=aa(t,"entry");if(o===null)return null;let i=Yw(t);if(i===null)return null;let s=tv(t);return s===null?null:{name:n,version:r,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}import nv from"node:fs/promises";import ir 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]="029e0066-2ef5-5204-92ad-4866321710f4")}catch{}})();async function ku(e,t){let n=ir.dirname(t.manifest_path),r=ir.relative(n,t.entry_path);if(r.startsWith("..")||ir.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=ir.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await Xl("extension_module_graph_snapshot",()=>nv.cp(n,o,{recursive:!0,force:!0})),ir.join(o,r)}(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]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function Su(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return U(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function Ou(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47d10c23-88f8-5ba1-bcc2-458f339121a8")}catch{}})();var Do=cn;function Au(e){let t=e.trim().toLowerCase();return Do.includes(t)?t:null}function Iu(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Do)if(Eo(t,r,n)!==null)return r;return null}(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]="355fe619-e6f3-51d9-b88c-0b57267c25be")}catch{}})();function Tu(e){return e==="toon"||e==="json"}function Cu(e){return on.includes(e)}function Ot(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var Ru=Symbol("extension_registration_trace");function Ue(e,t){let n=new TypeError(e);return Object.defineProperty(n,Ru,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function xu(e){return e instanceof Error?e[Ru]:void 0}function sr(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>sr(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=sr(t[r]);return n}return e}function ar(e){if(Array.isArray(e))return e.map(t=>ar(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=ar(t[r]);return n}return e}function _n(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return sr(t)}function cr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return ar(t)}function dr(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>_n(e,n))}function oe(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function lr(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function la(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function ua(e,t){return U(`${e} ${t}`)}function ur(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var rv=new Set(["low","medium","high"]),ov=new Set(["number","string_set"]),iv=new Set(["string","number","boolean"]);function Nu(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function sv(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=K(r,n);if(!ov.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(V(`${r}.description`,o.description),o.parameters===void 0)return;let i=K(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;Nu(`${c}.name`,s);let d=K(c,a);if(!iv.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);ee(`${c}.required`,d.required),V(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function Du(e){let t=K("registerAssuranceMeasurementProvider provider",e),n=Nu("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!rv.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=K("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);sv(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(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]="4abca948-e9ba-52b5-b63c-a20fc344980a")}catch{}})();var av=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function Po(e,t){return dr(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function cv(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function fa(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let n=cv(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function ma(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[r,o]of e.entries()){let i=K(`registerCommand definition.arguments[${r}]`,o),s=oe(`registerCommand definition.arguments[${r}].name`,i.name);if(ee(`registerCommand definition.arguments[${r}].required`,i.required),ee(`registerCommand definition.arguments[${r}].variadic`,i.variadic),V(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function Mo(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!av.has(c)).sort((c,d)=>c.localeCompare(d));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);V(`registerFlags flags[${t}].long`,i),V(`registerFlags flags[${t}].short`,s);let a=Rl(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${xl(a.token,a.failure)}`);if(V(`registerFlags flags[${t}].value_name`,r.value_name),V(`registerFlags flags[${t}].description`,r.description),ee(`registerFlags flags[${t}].required`,r.required),ee(`registerFlags flags[${t}].enabled`,r.enabled),ee(`registerFlags flags[${t}].visible`,r.visible),ee(`registerFlags flags[${t}].list`,r.list),ee(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(ou(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Pu(`registerFlags flags[${t}]`,r),dv(`registerFlags flags[${t}]`,r)}}function dv(e,t){if(t.value_validation===void 0)return;if(t.value_validation!=="coerce"&&t.value_validation!=="strict")throw new TypeError(`${e}.value_validation must be "coerce" or "strict" (received ${JSON.stringify(t.value_validation)}).`);if(t.value_validation!=="strict")return;let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),r=n===void 0?null:vo(n);if(r!=="number"&&r!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function Pu(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=vo(n);if(r===null)throw new TypeError(`${e} value_type "${n}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?Fl(t.default):[t.default];for(let[i,s]of o.entries())if(!Ul(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Mu(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerItemFields fields[${t}]`,n);oe(`registerItemFields fields[${t}].name`,r.name);let o=oe(`registerItemFields fields[${t}].type`,r.type);if(Au(o)===null){let i=Iu(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Do.join(", ")}).${s}`)}ee(`registerItemFields fields[${t}].optional`,r.optional)}}function lv(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.command`,s.command),oe(`${i}.option`,s.option),ee(`${i}.enabled`,s.enabled),ee(`${i}.required`,s.required),ee(`${i}.visible`,s.visible)}}function uv(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.key`,s.key),kt(`${i}.values`,s.values),ee(`${i}.required`,s.required),kt(`${i}.aliases`,s.aliases)}}function ju(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=K(r,n);oe(`${r}.name`,o.name),V(`${r}.folder`,o.folder),kt(`${r}.aliases`,o.aliases),kt(`${r}.required_create_fields`,o.required_create_fields),kt(`${r}.required_create_repeatables`,o.required_create_repeatables),lv(t,o.command_option_policies),uv(t,o.options)}}function $u(e){let t=K("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(ee("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var Lu=["types","statuses","fields","workflows","config","templates","packages"],fv={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Fu(e){let t=K("registerProfile profile",e);if(oe("registerProfile profile.name",t.name),oe("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let n of Lu){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);fv[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function Uu(e){e.summary===void 0&&(e.summary="");for(let t of Lu)e[t]===void 0&&(e[t]=[]);return e}(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]="45ff820c-32af-5bdb-a570-3059684129ce")}catch{}})();function zu(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5de5028-f981-599b-8d11-0fc7b07beda4")}catch{}})();function Hu(e){return typeof e=="string"?e:String(e)}function fr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(n=>Number(n)):null}function pa(e,t){let n=fr(e),r=fr(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function qu(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=Hu(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!fr(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=pa(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function Vu(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=Hu(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!fr(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=pa(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,current:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3abe36f7-3c97-58d2-a56d-b4e0ea958461")}catch{}})();var Bu=null,pv=Object.freeze(Vd()),Wu=0;function _v(e=Date.now()){return Wu+=1,`${Wu}-${e}`}function yv(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function hv(e,t){let[n,r]=await Promise.all([It.realpath(e),It.realpath(t)]);return Jn(n,r)}function gv(e,t=process.cwd()){return{global:At.join(vl(t),"extensions"),project:At.join(e,"extensions")}}async function bv(e){try{return(await It.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function wv(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function Gu(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function vv(e){let t=new Map;try{let n=JSON.parse(await It.readFile(At.join(e,".managed-extensions.json"),"utf8")),r=We(n)?.entries;if(!Array.isArray(r))return t;for(let o of r){if(typeof o!="object"||o===null)continue;let i=o,s=Gu(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>Gu(l)).filter(l=>l!==void 0),c=Ro(i.contributions),d={aliases:[...new Set(a)],...s?{package_name:s}:{},...c?{contributions:c}:{}};typeof i.directory=="string"&&i.directory.trim().length>0&&t.set(`directory:${i.directory.trim()}`,d),typeof i.name=="string"&&i.name.trim().length>0&&t.set(`name:${i.name.trim()}`,d)}}catch{return t}return t}function Ku(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function Ev(e,t){let n=[...Ku(e),...Ku(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function Yu(e,t,n,r,o){let i=[],s=[],a=[],c=await bv(t),d=await vv(t);for(let l of c){let u=await Ov(e,t,l,n,r,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function kv(){return{diagnostics:[],warnings:[],candidates:[]}}function Xu(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function Sv(e,t,n,r,o,i,s,a){let c=Kl(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(Gl(e,t.name,t.legacy_capability_aliases));for(let d of Vl(t.capabilities))c.push(Wl(e,t.name,d));return r?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function Ov(e,t,n,r,o,i,s){let a=At.join(t,n),c=At.join(a,"manifest.json");if(!await gt(c))return Xu(e,n,c,`extension_manifest_missing:${e}:${n}`);let d,l;try{let de=JSON.parse(await It.readFile(c,"utf8"));l=We(de),d=da(de)}catch{l=null,d=null}if(!d||!l)return Xu(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=At.resolve(a,d.entry),f=Jn(a,u),m=f?await gt(u):!1,_=f&&m?await hv(a,u):f,y=yv(d.name,r,o),b=await Tv(e,d),v=await Cv(e,d,s),T=Sv(e,d,l,_,m,b,v,y),G=_&&m&&b.allowed&&v.allowed,ce=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:G?"ok":"warn"},warnings:T,candidate:cu({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:ce,extensionReady:G,enabledForLoad:y})}}async function Av(e){let t=gv(e.pmRoot,e.cwd??process.cwd()),n=er(e.settings.extensions.enabled),r=er(e.settings.extensions.disabled),o=mu(e.settings),i=pu(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?kv():await Yu("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await Yu("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=Ev(c.candidates,d.candidates),f=[];for(let m of u){let _={layer:m.layer,name:m.manifest.name,trusted:m.manifest.trusted===!0,provenanceVerified:m.manifest.provenance?.verified===!0,sandboxProfile:m.manifest.sandbox_profile,permissions:m.manifest.permissions&&typeof m.manifest.permissions=="object"?{fs_read:m.manifest.permissions.fs_read,fs_write:m.manifest.permissions.fs_write,network:m.manifest.permissions.network,env_read:m.manifest.permissions.env_read,env_write:m.manifest.permissions.env_write,process_spawn:m.manifest.permissions.process_spawn}:void 0},y=hu(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let b of m.manifest.capabilities){let v=gu(o,_,b);v.warning&&l.push(v.warning)}f.push(wv(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function jo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function Iv(){try{let e=Io(import.meta.url,["../../.."]),t=await It.readFile(At.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function Zu(){return Bu??=Iv(),Bu}function ef(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function Tv(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=qu(t.pm_min_version,await Zu()),r=ef(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function Cv(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=Vu(t.pm_max_version,await Zu(),n),o=ef(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function Ju(e){try{let t=await It.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function Rv(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await ku(t.module_graph_snapshot_root,e));let r=new URL(mv(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[o,i]=await Promise.all([Ju(e.entry_path),Ju(e.manifest_path)]),s=t.reload_token??_v();return r.searchParams.set("pm_ext_reload",s),r.searchParams.set("pm_ext_entry",o),r.searchParams.set("pm_ext_manifest",i),r.href}async function t1(e){let t=await Av(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await Rv(s,e));n.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:jo(a)})}return{...t,warnings:o,loaded:n,failed:r}}var Qu=5e3,xv=2147483647;function Nv(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let n=e.deactivate;t.deactivate=n.bind(e)}return t}function tf(e){let t=Pl(e);return t?Nv(t):null}async function n1(e,t,n={}){let r=Dv(n?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(l=>`${l.layer}:${l.name}`)),i=[];for(let l of e.loaded){if(o.has(`${l.layer}:${l.name}`))continue;let u=tf(l.module);!u||typeof u.deactivate!="function"||i.push({extension:l,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:u})=>{try{return await Pv(u,r),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:jo(f)}}})),a=[],c=[],d=0;for(let l of s){if(l.ok){d+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),c.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:d,warnings:a,failed:c}}function Dv(e){return typeof e!="number"||e<0?Qu:e===0||e===1/0?0:Number.isFinite(e)?Math.min(xv,Math.max(1,Math.floor(e))):Qu}async function Pv(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function Mv(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Ge(r)&&t.add(r)}return t}function H(e,t,n){let r=Mv(e);if(r!==null&&!r.has(t))throw Ue(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${n} registration call.`})}function jv(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>je.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function $v(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var _a=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,u){this.#e=t,this.extension=jv(t),this.#n=$v(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=bu(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:sr(o),hint:i}}registerCommandOverride(t,n){let r=U(t);if(r.length===0)throw Ue("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Ue(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Ue("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Ue("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=U(t.name);if(n.length===0)throw Ue("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Ue(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{iu(t);let o=fa(n,t.action),i=su(t.read_output,n,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=rr("registerCommand definition.examples",t.examples),d=rr("registerCommand definition.failure_hints",t.failure_hints),l=ma(t.arguments);t.flags!==void 0&&(H(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&(Mo(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Po("registerCommand definition.flags",t.flags)})));let u={source_version:this.#e.version,read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:c,failure_hints:d,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};s&&(u.description=s),a&&(u.intent=a),this.#t.commands.push(u)}catch(o){let i=jo(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Ue(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(H(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(H(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=U(oe("registerParser command",t));lr("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(H(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Su(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){H(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!Cu(o))throw new TypeError(`registerService service must be one of: ${on.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(lr("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...zu(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(H(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!Tu(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return U(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(H(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=U(oe("registerFlags targetCommand",t));Mo(n);let o=Po("registerFlags flags",n);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:o})}registerItemFields(t){if(H(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Mu(t);let n=dr("registerItemFields fields",t);if(n.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:n})}registerItemTypes(t){if(H(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;ju(t);let n=dr("registerItemTypes types",t);if(n.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:n})}registerRelationshipKinds(t){if(H(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let n=Ls();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(H(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;$u(t);let n=cr("registerMigration definition",t);this.#t.migrations.push(ur({layer:this.#e.layer,name:this.#e.name,definition:_n("registerMigration definition",t)},n))}registerProfile(t){if(H(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=ar(t);Fu(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Uu(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(H(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&(Mo(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Po(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...r,description:r?.description??o,arguments:r?.arguments??i},a=au(t,s,r?.description!==void 0);V(`${t} options.action`,s.action),V(`${t} options.description`,s.description),V(`${t} options.intent`,s.intent);let c=fa(n,s.action),d=rr(`${t} options.examples`,s.examples),l=rr(`${t} options.failure_hints`,s.failure_hints),u=ma(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:d,failure_hints:l,arguments:u},m=s.description?.trim();m&&(f.description=m);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,n,r){if(H(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=la(oe("registerImporter name",t));lr("registerImporter importer",n);let i=ua(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n(ia(s,o,"import"))})}registerExporter(t,n,r){if(H(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=la(oe("registerExporter name",t));lr("registerExporter exporter",n);let i=ua(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(ia(a,o,"export"));return s?.receipt==="suppress"&&!Ao(c)?Hl(c):c}})}registerSearchProvider(t){if(H(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=cr("registerSearchProvider provider",t);this.#t.search_providers.push(ur({layer:this.#e.layer,name:this.#e.name,definition:_n("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(H(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=cr("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(ur({layer:this.#e.layer,name:this.#e.name,definition:_n("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(H(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(Du(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=cr("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(ur({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:_n("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){H(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(Ot("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){H(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(Ot("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){H(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(Ot("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){H(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(Ot("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){H(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(Ot("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){H(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(Ot("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function Lv(e,t,n,r,o,i,s,a,c,d,l){return new _a(e,t,n,r,o,i,s,a,c,d,l)}function Fv(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:n,item_fields:r,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function Uv(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let d=a.get(c.command)??[];d.push(c),a.set(c.command,d)}for(let c of[...a.keys()].sort((d,l)=>d.localeCompare(l))){let d=a.get(c);if(d.length<=1)continue;let l=d[d.length-1];for(let u of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${u.layer}:${u.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let d of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${d.layer}:${d.name}`)}return t}function zv(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Hv(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var qv=new Set(["output_format"]);function Vv(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||qv.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function r1(e){let t=_u(e.policy??pv),n=tr(),r=zs(),o=Hs(),i=qs(),s=Vs(),a=Bs(),c=Ws(),d=[],l=[];for(let m of e.loaded){let _=tf(m.module);if(!_)continue;let y=d.length,b=ru({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(Lv(m,n,r,o,i,s,a,c,l,d,t)),d.length>y&&(b(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(v){b(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let T=xu(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:jo(v),trace:T})}}let u=[...Uv(r),...Hv(o),...Ou(i),...Vv(s),...zv(a)],f=[...new Set([...l,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:Fv(c)}}(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]="b1a38f8c-8f65-59e2-bddf-ed0606a0f0b5")}catch{}})();function a1(e){return{...e,hooks:tr(),profileEnabled:!!e.globalOptions.profile,migrationBlockers:[]}}(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]="4da25248-2914-5bc5-aa42-87f677ef4ea8")}catch{}})();function d1(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let r=Promise.all([e,...t]).then(()=>n());return e=r.then(()=>{},()=>{}),r}}}function Bv(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.push(o))}}}(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]="d8844150-afb4-5f2e-a005-4cfb8482660c")}catch{}})();var Wv={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},nf=":";function rf(e,t){return`${e}${nf}${ya(t)}`}function Gv(e){return e.slice(e.indexOf(nf)+1)}function ya(e){return e.trim().toLowerCase()}function Kv(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=ql(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function of(e){let t=new Map,n=(l,u)=>{for(let f of l){let m=rf(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function Yv(e,t={}){let n=of(e),r=new Set;t.extensionName!==void 0&&r.add(ya(t.extensionName));for(let i of t.extensionNames??[])r.add(ya(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(Gv(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function Xv(e,t){let n=of(t),r=[];for(let o of e){let i=Kv(o.capabilities);if(i.length===0)continue;let s=n.get(rf(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as Jv}from"node:fs";import{AsyncLocalStorage as Qv}from"node:async_hooks";import ze 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]="7c2e7a35-cbf9-5bb6-abfd-f1ae75c6afc2")}catch{}})();var He=null,yn=null,mr=null,pr=null,hn=null,_r=null,yr=null,Xe=null,Lo,$o=[],af=new Qv;function j(){return af.getStore()}function h1(e){return af.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var Zv=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function sf(e){let t=ze.resolve(e);for(;;){if(Jv(ze.join(t,".git")))return t;let n=ze.dirname(t);if(n===t)return;t=n}}function Fo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=sf(t)??ze.resolve(t),r=sf(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=ze.relative(n,ze.resolve(e)),i=o.length>0&&!o.startsWith(`..${ze.sep}`)&&o!==".."&&!ze.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(ze.sep).join("/")}:{}}}function g1(e){let t=j();if(t){t.hooks=e;return}He=e}function b1(e){let t=j();if(t){t.commands=e;return}yn=e}function w1(e){let t=j();if(t){t.parsers=e;return}mr=e}function v1(e){let t=j();if(t){t.preflight=e;return}pr=e}function E1(e){let t=j();if(t){t.services=e;return}hn=e}function k1(e){let t=j();if(t){t.renderers=e;return}_r=e}function S1(e){let t=j();if(t){t.registrations=e;return}yr=e}function cf(){let e=j();return e?e.registrations:yr}function O1(){let e=j();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=null,e.affectedItems=[];return}He=null,yn=null,mr=null,pr=null,hn=null,_r=null,yr=null,Xe=null,Lo=null}function A1(e){let t=e?{...e,...Fo(e.pm_root)}:null,n=j();if(n){n.commandContext=t;return}Xe=t}function df(){let e=j(),t=e?e.commandContext:Xe;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function I1(e){let t=j()??{commandContext:Xe,hooks:He,commands:yn,parsers:mr,preflight:pr,services:hn,renderers:_r,registrations:yr};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(n=>Object.values(n??{}).some(r=>r.length>0))||[t.commands,t.parsers].some(n=>Object.values(n??{}).some(r=>r.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([n,r])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(n)&&r.length>0)}function Uo(e){let t=j();if(t){t.commandResult=e;return}Lo=e}function T1(){let e=j();return e?e.commandResult:Lo}function C1(e){if(!e)return;let t=j();t?t.affectedItems.push(e):$o.push(e)}function R1(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||Zv.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function x1(){let e=j(),t=e?.affectedItems??$o;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:$o=[],n}function N1(){let e=j();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=void 0,e.affectedItems=[];return}He=null,yn=null,mr=null,pr=null,hn=null,_r=null,yr=null,Xe=null,Lo=void 0,$o=[]}async function zo(e){let t=j(),n=t?t.hooks:He;return n?Ks(n,e):[]}async function D1(e){let t=j(),n=t?t.hooks:He;n&&await Gs(n,e)}async function gn(e){let t=j(),n=t?t.hooks:He;return n?Ys(n,e):[]}function P1(){let e=j();return((e?e.hooks:He)?.onRead?.length??0)>0}async function M1(e){let t=j(),n=t?t.hooks:He;return n?Xs(n,e):[]}function lf(e){let t=j(),n=t?t.commands:yn,r=t?t.commandContext:Xe;return!n||!r?{overridden:!1,result:e,warnings:[]}:na(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function j1(e){let t=j(),n=t?t.commands:yn;return n?Js(n,{...e,...Fo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function $1(e){let t=j(),n=t?t.parsers:mr;return n?Qs(n,{...e,...Fo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},warnings:[]}}async function L1(e){let t=j(),n=t?t.preflight:pr;return n?Zs(n,{...e,...Fo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},decision:{...e.decision},warnings:[]}}function uf(e,t){let n=j(),r=n?n.renderers:_r,o=n?n.commandContext:Xe;return r?ra(r,{format:e,command:o?.command,args:o?[...o.args]:[],options:o?.options?{...o.options}:{},global:o?.global?{...o.global}:void 0,pm_root:o?.pm_root,source_workspace_root:o?.source_workspace_root,repo_root:o?.repo_root,pm_root_rel:o?.pm_root_rel,result:t}):{overridden:!1,rendered:null,warnings:[]}}function ff(e,t){let n=j(),r=n?n.commandContext:Xe;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function bn(e,t){let n=j(),r=n?n.services:hn;return r?ta(r,ff(e,t)):{handled:!1,result:t,warnings:[]}}function ha(e,t){let n=j(),r=n?n.services:hn;return r?ea(r,ff(e,t)):{handled:!1,result:t,warnings:[]}}import{createHash as eE}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]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var B1=["sha256","sha512"],tE="sha256",mf="sha256";function Tt(e){if(e===void 0)return tE;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function Je(e,t){return eE(Tt(t)).update(e,"utf8").digest("hex")}(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]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function pf(e){let t=[],n=e[0]?.op==="history_compact_baseline",r=n?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(r!==void 0&&t.push({prior_genesis_index:r,repeated_create_index:i+1,sequence:o?"delete_then_create":n?"checkpoint_then_create":"multiple_creates"}),r??=i+1,o=!1);return t}import yf from"node:path";import{link as nE,mkdir as rE,mkdtemp as oE,rm as iE,writeFile as sE}from"node:fs/promises";import ga 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]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();async function _f(e,t){let n=ga.dirname(e);await rE(n,{recursive:!0});let r=await oE(ga.join(n,".pm-seed-")),o=ga.join(r,"value");try{await sE(o,t,"utf8");try{return await nE(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await iE(r,{recursive:!0,force:!0})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var aE=2e3,Ho=new Map;function Qe(e){if(typeof e!="string")return"";let t=Ho.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return Ho.size>=aE&&bo(Ho),Ho.set(e,n),n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ie=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),bf=Wd,wa=Bd,cE=["create","update"],dE=new Set(io),lE=new Set(cn),uE=new Set(so),fE=new Set(ao),mE=new Set(["string","number","boolean","array","object"]),pE=16;function wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var _E=[e=>e.type===void 0||typeof e.type=="string"&&mE.has(e.type),e=>!Object.hasOwn(e,"const")||Vo(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Vo(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||wf(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Vo(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=Array.isArray(e)?e.every(r=>Vo(r,t)):Object.values(e).every(r=>Vo(r,t));return t.delete(e),n}function qo(e,t=0,n=new Set){if(!wf(e)||t>pE||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,d=r.required,l=r.min_length,u=r.min_items,f=r.format,m=r.additional_properties;if(!_E.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,T])=>[v,qo(T,t+1,n)])),y=c===void 0?void 0:qo(c,t+1,n),b=s===void 0?void 0:s.map(v=>qo(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...b??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:l,min_items:u,format:f,properties:_,required:d===void 0?void 0:[...new Set(d)],additional_properties:m,items:y,one_of:b}).filter(([,v])=>v!==void 0))}function gr(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function ye(e){if(typeof e!="string"||e.length===0)return;let t=Qe(e);return t.length>0?t:void 0}function yE(e){return e.startsWith("--")?e.slice(2):e}function hf(e){return typeof e=="string"?yE(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function vf(e){return e.replaceAll("_","-")}function hE(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function ba(e,t){let n=ye(e.id);if(!n)return null;let r=[...new Set(gr(e.aliases).map(Qe).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=gr(e.roles).filter(a=>dE.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function gE(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function Ef(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Qe(t[0]),r=Qe(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function bE(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)Ef(n,r);return{typeKey:t.toLowerCase(),record:n}}function wE(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=bE(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)Ef(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function kf(e){let t=Qe(e.key??"");if(!t)return null;let n=Qe(e.metadata_key??e.front_matter_key??t),r=hf(e.cli_flag??vf(t));if(!r)return null;let o=gr(e.cli_aliases).map(u=>hf(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=lE.has(i)?i:"string",a=(()=>{let u=gr(e.commands).filter(f=>uE.has(f));return u.length>0?u:[...cE]})(),c=e.description?.trim(),d=gr(e.required_types),l=e.value_schema===void 0?void 0:qo(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:n,cli_flag:r,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:[e.repeatable===!0,s==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1,value_schema:l}}function vE(e){let t=new Map;for(let[r,o]of e.entries()){let i=ba(o,r);i&&t.set(i.id,i)}let n=gf([...t.values()]);return n.length>0?n:gf(wa.map((r,o)=>ba(r,o)).filter(r=>r!==null))}function gf(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function EE(e){let t=new Map;for(let n of e??[]){let r=kf(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function kE(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function SE(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==vf(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function OE(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return fE.has(t)?t:"allow"}function Ce(e){let t={...ie,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:wa,r=vE(n),o=EE(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(kE),fields:o.map(SE),workflow:{...bf,...gE(e?.workflow)},type_workflows:wE(e?.type_workflows),unknown_field_policy:OE(e?.unknown_field_policy)}}function AE(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function IE(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function TE(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function CE(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function RE(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function xE(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function ue(e,t,n){let r=t?.trim()||n;return yf.isAbsolute(r)?r:yf.join(e,r)}function iM(e,t){return ue(e,t.files.types,ie.types)}async function sM(e,t){let n=Ce(t),r=[{path:ue(e,n.files.types,ie.types),seed:{definitions:[]}},{path:ue(e,n.files.statuses,ie.statuses),seed:{statuses:wa}},{path:ue(e,n.files.fields,ie.fields),seed:{fields:[]}},{path:ue(e,n.files.workflows,ie.workflows),seed:{workflow:bf}}],o=[];for(let i of r)await gt(i.path)||await _f(i.path,`${JSON.stringify(i.seed,null,2)}
3
- `)&&o.push(i.path);return{created_paths:o}}async function Sf(e,t){let n=Ce(t),r=[],o=ue(e,n.files.types,ie.types),i=ue(e,n.files.statuses,ie.statuses),s=ue(e,n.files.fields,ie.fields),a=ue(e,n.files.workflows,ie.workflows),c,d,l,u,f,m=async(T,G)=>{let ce=await Ae(T);if(ce!==null)return AE(ce,G,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=IE(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=TE(y),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await m(s,"runtime_schema_fields_invalid_json");b!==void 0&&(l=CE(b),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=RE(v),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=xE(v)),{schema:Ce({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function hr(e,t,n,r=!1){let o=n.map(s=>ye(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(r&&o!==void 0)return o;let i=e.find(s=>s.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function NE(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function DE(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Of(e){let t=Ce(e),n=t.statuses.map((v,T)=>ba(v,T)).filter(v=>v!==null),{aliasToId:r,byId:o}=NE(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=DE(n),u=t.workflow,f=ye(u.open_status)??hr(n,"default_open",["open","in_progress",an[0]]),m=ye(u.in_progress_status)??hr(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??hr(n,"blocked",["blocked"]),y=ye(u.close_status)??hr(n,"default_close",["closed","done","complete"]),b=ye(u.canceled_status)??hr(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:l,terminal_done_statuses:d,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:m,blocked_status:_,close_status:y,canceled_status:b}}function va(e,t){let n=Qe(e);if(n)return t.alias_to_id.get(n)}function Af(e){let t=Ce(e),n=new Map,r=t.fields.map(c=>kf(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,d)=>c.key.localeCompare(d.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let d of c.cli_aliases)s.set(d,c);for(let d of c.commands){let l=a.get(d)??[];l.push(c),a.set(d,l)}}for(let[c,d]of a.entries())d.sort((l,u)=>l.key.localeCompare(u.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function If(e){return hE(e.key)}function aM(e,t){let n=va(e,t);return n?t.terminal_statuses.has(n):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6635e694-c788-5805-adb8-ed93cc931946")}catch{}})();var PE=16;function Bo(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function pM(e,t,n=new Set,r){if(xf(e,t,r))return;let o=Nf(e,t,n,r),i=Wo(e);return[Bo(e.cli_flag),...i].find(s=>!o.has(s)&&Rf(s,i,o))}function Rf(e,t,n){for(let r of t){if(r===e)break;if(n.has(r))return!1}return!0}function xf(e,t,n){return t.definitions.some(r=>r!==e&&r.metadata_key===e.metadata_key&&(n===void 0||r.commands.includes(n)))}function Nf(e,t,n,r){return new Set([...n,...t.definitions.filter(o=>o!==e&&(r===void 0||o.commands.includes(r))).flatMap(o=>Wo(o))])}function Df(e){return e.replace(/^-+/u,"").startsWith("no-")}function ME(e){return e.startsWith("-")?e:`--${e}`}function _M(e,t,n,r){if(xf(e,t,r))return;let o=Nf(e,t,n.options,r),i=Wo(e);return[e.cli_flag,...e.cli_aliases].find(s=>{let a=Pf(s);return Df(s)||n.flags.has(ME(s))||o.has(a)?!1:Rf(a,i,o)})}function Pf(e){return e.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((t,n)=>`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`)}function Wo(e){return[...new Set([If(e),Bo(e.key),Bo(e.cli_flag),...e.cli_aliases.map(t=>Bo(t)),...[e.cli_flag,...e.cli_aliases].filter(t=>!Df(t)).map(t=>Pf(t))])]}function Mf(e,t){for(let n of Wo(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function jf(e){return Array.isArray(e)?e.flatMap(t=>jf(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function Tf(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Cf(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new g(`${t} must be a number`,h.USAGE);return r}function jE(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new g(`${t} must be valid JSON ${n}`,h.USAGE)}function $E(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function LE(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!$E(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!Qn(e))return`${n} must be an RFC 3339 date-time`}}function FE(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Go(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function UE(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=Go(s,a,`${n}.${i}`,r+1);if(c)return c}}function Go(e,t,n,r=0){if(r>PE)return`${n} value schema exceeds maximum depth`;let o=LE(e,t,n);if(o)return o;let i=FE(e,t,n,r);if(i)return i;let s=UE(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Go(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function Ct(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Go(t,e.value_schema,n);if(r)throw new g(r,h.USAGE);return t}function zE(e,t,n,r){let o=r==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Ct(e,jE(o,n,e.type),n)}function br(e,t,n,r="option"){let o=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return zE(e,t,o,r);if(e.repeatable||e.type==="string_array"){let s=jf(t);return e.type==="number"?Ct(e,s.map(a=>Cf(a,o)),o):e.type==="boolean"?Ct(e,s.map(a=>Tf(a,o)),o):Ct(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Ct(e,Cf(i,o),o):e.type==="boolean"?Ct(e,Tf(i,o),o):Ct(e,typeof i=="string"?i:String(i),o)}function HE(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function yM(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=Mf(e,i);if(s===void 0){HE(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=br(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function hM(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=Mf(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=br(s,a)))}return r}(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]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var Ea=1,ka=2;function bM(e){return Math.max(Sa(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function Sa(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function $f(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function qE(e,t=2,n=t){return e<n?"outdated":e>t?"ahead":"current"}function wM(e,t=2,n=t){let r=[],o=[];for(let i of e){let s=qE(i.version,t,n);s==="outdated"?r.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:r.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(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]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var VE={"in-progress":"in_progress",cancelled:"canceled"};function Ko(e,t){if(t){let o=va(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=VE[n]??n;if(an.includes(r))return r}function BE(e,t){return Ko(e,t)??e}function SM(e,t){return t.terminal_statuses.has(BE(e,t))}import{encode as YE}from"@toon-format/toon";import{isDeepStrictEqual as Lf}from"node:util";import{decode as WE}from"@toon-format/toon";(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]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function Oa(e){return{value:WE(e),usedScalarBracketEscape:!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]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var GE=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function KE(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(GE);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Yo(e){return KE(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d371559f-ff71-590b-ac84-ad820852d18c")}catch{}})();var Ca=new Set(["schema","tracker","auto","none"]),qf=new Set(["source","isolated","snapshot"]),XE=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),JE=new Set(["passed","failed","stopped","canceled"]),QE=new Set(il);function kn(e){return e.replaceAll("\\","/")}function Vf(e){for(let t of e)if(t!==0)return t;return 0}function Jo(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Bf=["id","title","description","created_at","updated_at"],ZE=new Set(Ve);function Wf(e){if(e?.schema)return{statusRegistry:Of(e.schema),fieldRegistry:Af(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function e0(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Ze(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new g(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function Er(e,t){throw new g(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Gf(e,t){if(!t||typeof e!="object"||e===null)return;let n=Sa(e);if(!(n<=ka))throw new g(`Stored item uses format version ${n}; this runtime supports up to ${ka}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:n,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function Kf(e){let t=new Set(ZE);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function O(e,t){e||Ze(t)}function kr(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Ze(t),e}function Aa(e,t){let n=e[t];O(typeof n=="string",`${t} must be a string`),O(Le(n),`${t} must be a valid ISO timestamp`)}function Ff(e,t,n){let r=e[t];r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Ra(e,t,n){let r=e[t];r!==void 0&&(O(typeof r=="string",`${n} must be a string`),O(Le(r),`${n} must be a valid ISO timestamp`))}function t0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){O(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();O(Kn.includes(n),`event.recurrence.by_weekday entries must be one of: ${Kn.join(", ")}`)}}}function n0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)O(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function r0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)O(typeof t=="string","event.recurrence.exdates entries must be strings"),O(Le(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function o0(e){let t=kr(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();O(uo.includes(n),`event.recurrence.freq must be one of: ${uo.join(", ")}`),Ff(t,"interval","event.recurrence.interval"),Ff(t,"count","event.recurrence.count"),Ra(t,"until","event.recurrence.until"),t0(t.by_weekday),n0(t.by_month_day),r0(t.exdates)}function i0(e){for(let r of Bf)O(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;O(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=Ea,`pm_format_version must be an integer >= ${Ea}`),t}function s0(e,t){let n=e.status;O(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Ko(n,r),i=r?r.definitions.map(s=>s.id):[...an];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function a0(e){let t=e.priority;O(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;O(Array.isArray(n),"tags must be an array");for(let r of n)O(typeof r=="string","tags entries must be strings")}function c0(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){O(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||lo.includes(n);O(r,`confidence string value must be one of: ${[...lo,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function d0(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Ze("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||co.includes(n);O(r,`severity value must be one of: ${[...co,"med"].join(", ")}`)}function l0(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Ze("regression must be a boolean")}function u0(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let n of t){let r=kr(n,"reminders entries must be objects");O(typeof r.at=="string","reminder.at must be a string"),O(Le(r.at),"reminder.at must be a valid ISO timestamp"),O(typeof r.text=="string","reminder.text must be a string"),O(r.text.trim().length>0,"reminder.text must not be empty")}}}function f0(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(O(typeof e[t]=="string",`event.${t} must be a string`),O(e[t].trim().length>0,`event.${t} must not be empty`))}function m0(e){e.recurrence!==void 0&&(o0(e.recurrence),e.recurrence.until!==void 0&&O(re(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function p0(e){let t=kr(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O(Le(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(O(typeof t.end_at=="string","event.end_at must be a string"),O(Le(t.end_at),"event.end_at must be a valid ISO timestamp"),O(re(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),f0(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),m0(t)}function _0(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let n of t)p0(n)}}function y0(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&O(typeof n=="string",`${t} must be a string`)}}function h0(e){let t=e.type_options;if(t===void 0)return;let n=kr(t,"type_options must be an object");for(let[r,o]of Object.entries(n))O(r.trim().length>0,"type_options keys must be non-empty"),O(typeof o=="string","type_options values must be strings"),O(o.trim().length>0,"type_options values must be non-empty strings")}function g0(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){e0(r,t)&&Ze(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=br(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){Ze(String(i?.message).replace(/^Invalid\s+/u,""))}}}function b0(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Kf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Ze(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function xa(e,t){let n=kr(e,"item metadata must be an object"),r=i0(n);s0(n,t),a0(n),c0(n),d0(n),l0(n),Aa(n,"created_at"),Aa(n,"updated_at"),n.deadline!==void 0&&Aa(n,"deadline"),u0(n),_0(n),Ra(n,"closed_at","closed_at"),Ra(n,"completed_at","completed_at"),y0(n),h0(n),g0(n,r,t),b0(n,t)}function w0(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&Qn(t.created_at),`dependencies.${n}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=re(t.created_at??"",n.created_at??"");if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}var qM=new Set(["comments","notes","learnings"]),v0="[unconvertible]";function wn(e,t){try{return String(e?.[t])}catch{return v0}}function E0(e,t){let n=re(wn(e,"created_at"),wn(t,"created_at"));if(n!==0)return n;let r=wn(e,"text").localeCompare(wn(t,"text"));return r!==0?r:wn(e,"author").localeCompare(wn(t,"author"))}function Ia(e){if(!(!e||e.length===0))return[...e].sort(E0)}function k0(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=re(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function S0(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!uo.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Kn.includes(s)))).sort((s,a)=>gs(s)-gs(a)),r=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>Le(s)))).sort((s,a)=>re(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:n.length>0?n:void 0,by_month_day:r.length>0?r:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function O0(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(A0).sort(I0)}function A0(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:S0(e.recurrence)};return Jo(t),t}function I0(e,t){return Vf([re(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function T0(e){if(!(!e||e.length===0))return e.map(t=>({path:kn(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function C0(e){if(!e||e.length===0)return;let t=e.map(D0).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>Vf([re(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function vn(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function R0(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Ta(e){return typeof e=="string"?e:""}function x0(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function Xo(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function N0(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:Xo(n.requested_pm_context_mode,Ca),pm_context_mode:Xo(n.pm_context_mode,Ca),workspace_context_mode:Xo(n.workspace_context_mode,qf),trust_reason:Xo(n.trust_reason,XE)}));return t.length>0?t:void 0}function D0(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=JE.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Ta(e.started_at),finished_at:Ta(e.finished_at),recorded_at:Ta(e.recorded_at),attempt:R0(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:vn(e.passed)??0,failed:vn(e.failed)??0,skipped:vn(e.skipped)??0,items:vn(e.items),linked_tests:vn(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:x0(e.measurements),executions:N0(e.executions)};return Jo(o),o}function P0(e){if(!(!Array.isArray(e)||e.length===0))return e.map(F0)}function wr(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Ma(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ja(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Uf(e){if(!Ma(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!ja(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function M0(e){if(!Ma(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!ja(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function j0(e){let t=e?.trim().toLowerCase();if(!(!t||!Ca.has(t)))return t}function $0(e){let t=e?.trim().toLowerCase();if(!(!t||!qf.has(t)))return t}function L0(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Ma(e))return{provenance_invalid:!0};let n=E(e.author),r=E(e.created_at),o=e.source_kind;return!n||!r||!Le(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:E(e.source_ref)}}}function F0(e){let t={command:e.command?.trim()||void 0,path:e.path?kn(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:j0(e.pm_context_mode),workspace_context_mode:$0(e.workspace_context_mode),...L0(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:Uf(e.env_set),env_clear:wr(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:wr(e.assert_stdout_contains),assert_stdout_regex:wr(e.assert_stdout_regex),assert_stderr_contains:wr(e.assert_stderr_contains),assert_stderr_regex:wr(e.assert_stderr_regex),assert_stdout_min_lines:vn(e.assert_stdout_min_lines),assert_json_field_equals:Uf(e.assert_json_field_equals),assert_json_field_gte:M0(e.assert_json_field_gte),note:e.note?.trim()||void 0};return Jo(t),t}function U0(e){if(!(!e||e.length===0))return[...e].map(t=>({path:kn(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function z0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.id),i=E(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function H0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:kn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function q0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.command),i=E(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=kn(i));let a=E(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function V0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:kn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function B0(e){if(e===null||typeof e!="object")return;let t=e,n=E(t.id),r=E(t.title),o=E(t.status),i=o&&QE.has(o)?o:void 0,s=go(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return W0(d,t),d}function W0(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=E(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",z0],["files","files",H0],["tests","tests",q0],["docs","docs",V0]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function G0(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=B0(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function K0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(r.rationale);c&&(a.rationale=c);let d=E(r.evidence);d&&(a.evidence=d);let l=E(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function Y0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function X0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.text);if(!o)continue;let i={text:o},s=E(r.command);s&&(i.command=s);let a=E(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function J0(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function En(e){let t=0;for(;t<e.length&&e[t]===`
4
- `;)t+=1;return e.slice(t).trimEnd()}function Q0(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(lo.includes(t))return t}function Z0(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(co.includes(t))return t}function vr(e){return e||void 0}function ek(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))ja(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function tk(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=br(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function nk(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Kf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length>0&&t.unknownFieldPolicy==="reject"&&Ze(`unknown schema fields are not allowed: ${r.join(", ")}`),r.length>0&&t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`)}function Qo(e,t={}){let n=Wf(t),r=Ko(e.status,n?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:$f(e.pm_format_version),source_type:E(e.source_type),type_options:J0(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:w0(e.dependencies),comments:Ia(e.comments),notes:Ia(e.notes),learnings:Ia(e.learnings),files:T0(e.files),tests:P0(e.tests),test_runs:C0(e.test_runs),docs:U0(e.docs),deadline:vr(e.deadline),reminders:k0(e.reminders),events:O0(e.events),closed_at:vr(e.closed_at),completed_at:vr(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:vr(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:E(e.definition_of_ready),order:e.order,goal:E(e.goal),objective:E(e.objective),value:E(e.value),impact:E(e.impact),outcome:E(e.outcome),why_now:E(e.why_now),parent:E(e.parent),reviewer:E(e.reviewer),risk:e.risk??void 0,confidence:Q0(e.confidence),sprint:E(e.sprint),release:E(e.release),blocked_by:E(e.blocked_by),blocked_reason:E(e.blocked_reason),unblock_note:E(e.unblock_note),reporter:E(e.reporter),severity:Z0(e.severity),environment:E(e.environment),repro_steps:E(e.repro_steps),resolution:E(e.resolution),expected_result:E(e.expected_result),actual_result:E(e.actual_result),affected_version:E(e.affected_version),fixed_version:E(e.fixed_version),component:E(e.component),regression:e.regression,customer_impact:E(e.customer_impact),close_reason:vr(e.close_reason),plan_mode:E(e.plan_mode),plan_scope:E(e.plan_scope),plan_harness:E(e.plan_harness),plan_resume_context:E(e.plan_resume_context),plan_steps:G0(e.plan_steps),plan_decisions:K0(e.plan_decisions),plan_discoveries:Y0(e.plan_discoveries),plan_validation:X0(e.plan_validation)};return ek(i,e),tk(i,n),nk(i,n),Jo(i),i}function Yf(e){return A(e,Ve)}function rk(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function ok(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=rk(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function ik(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
5
- `,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function Na(e,t){return Qo(e,{...t,onWarning:void 0})}function sk(e,t,n={}){let r=ik(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=ok(r.content);o||(e.trimStart().startsWith("{")&&Er("json_markdown","JSON front matter is not valid JSON"),Er("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{Er("json_markdown","JSON front matter is not valid JSON")}return Gf(s,n.requireSupportedFormat),xa(s,t),{metadata:Na(s,n),body:En(i)}}function ak(e,t,n={}){let r;try{r=Oa(e).value}catch{Er("toon","TOON item document is not valid TOON")}O(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(Gf(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!Bf.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&Er("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return xa(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:Na(o.front_matter,n),body:En(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return O(i===void 0||typeof i=="string","TOON item document body must be a string"),xa(s,t),{metadata:Na(s,n),body:En(typeof i=="string"?i:"")}}function ck(e,t={}){let n=Qo(e.metadata,t),r=Yf(n),o=En(e.body??"");Pa(JSON.parse(JSON.stringify(r))),Pa({body:o});let i=JSON.stringify(r,null,2);return o?`${i}
1
+ import{A as h,C as g,E as gt,F as be,G as Q,H as Ae,I as Zd,J as ys,K as bt,L as Qd,a as $e,b as _s,c as Wd,e as Yr,f as Xr,g as Jr,h as Gd,i as Zr,j as on,k as Kd,m as Ve,n as Yd,o as Xd,p as Qr,q as eo,u as Bn,v as Jd,y as S,z as Wn}from"./chunk-O4ZLEN4T.js";import Sh 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]="77f9d61e-e78b-5b6a-a769-1ad6e5b91777")}catch{}})();function Oh(e){if(e===null)return null;if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")return e;if(typeof e=="bigint")return e.toString();if(e===void 0)return"undefined";if(typeof e=="symbol")return e.toString();if(typeof e=="function")return`[function:${e.name||"anonymous"}]`}function Ah(e){let t=Object.keys(e).sort(),n={};for(let r of t){let o=e[r];o!==void 0&&(n[r]=to(o))}return n}function to(e){let t=Oh(e);if(t!==void 0)return t;if(Array.isArray(e))return e.map(r=>to(r));if(e instanceof Date)return e.toISOString();let n=e;if(typeof n.toJSON=="function"){let r=n.toJSON();if(r!==e)return to(r)}return Ah(e)}function R(e){return JSON.stringify(to(e))}function el(e,t,n,r){for(let o=0;o<t.length;o+=1)if(!n.has(o)&&r(e,t[o]))return n.add(o),!0;return!1}function Ih(e,t){if(e instanceof RegExp||t instanceof RegExp)return e instanceof RegExp&&t instanceof RegExp&&e.toString()===t.toString()}function Th(e,t){if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime()}function Ch(e,t){if(!(e instanceof Set||t instanceof Set))return;if(!(e instanceof Set&&t instanceof Set)||e.size!==t.size)return!1;let n=[...t],r=new Set;for(let o of e)if(!el(o,n,r,B))return!1;return!0}function Rh(e,t){if(!(e instanceof Map||t instanceof Map))return;if(!(e instanceof Map&&t instanceof Map)||e.size!==t.size)return!1;let n=[...t.entries()],r=new Set;for(let[o,i]of e.entries())if(!el([o,i],n,r,([s,a],[c,d])=>B(s,c)&&B(a,d)))return!1;return!0}function xh(e,t){if(Array.isArray(e)||Array.isArray(t))return!Array.isArray(e)||!Array.isArray(t)||e.length!==t.length?!1:e.every((n,r)=>B(n,t[r]))}function Nh(e,t){let n=Object.keys(e).sort((o,i)=>o.localeCompare(i)),r=Object.keys(t).sort((o,i)=>o.localeCompare(i));if(n.length!==r.length)return!1;for(let o=0;o<n.length;o+=1){let i=n[o];if(i!==r[o]||!B(e[i],t[i]))return!1}return!0}var Dh=[Ih,Th,Ch,Rh,xh];function B(e,t){if(Object.is(e,t))return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;for(let n of Dh){let r=n(e,t);if(r!==void 0)return r}return Nh(e,t)}function no(e){return Sh.createHash("sha256").update(e,"utf8").digest("hex")}function A(e,t){let n={};for(let o of t){let i=e[o];i!==void 0&&(n[o]=i)}let r=Object.keys(e).filter(o=>!t.includes(o)).sort((o,i)=>o.localeCompare(i));for(let o of r){let i=e[o];i!==void 0&&(n[o]=i)}return n}import{createHash as nl}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]="f675993f-c483-5751-baed-d968b4fd24c0")}catch{}})();var Ph=["policies","policy-put","policy-remove","policy-mode","policy-check","policy-approve","policy-presets"],tl=256,hs=64;function le(e){throw new g(`Invalid workflow policy: ${e}`,h.USAGE,{code:"workflow_policy_invalid",nextSteps:["Inspect pm schema policies and correct the declaration using pm schema policy-put."]})}function je(e,t,n){if(typeof e!="object"||e===null||Array.isArray(e))return le(`${n} must be an object`);let r=e;return Object.keys(r).some(o=>!t.includes(o))?le(`${n} contains an unknown key`):r}function wt(e,t,n=128){return typeof e!="string"||!e.trim()||e.length>n?le(`${t} must be nonempty text of at most ${n} characters`):e.trim()}function Gn(e,t){if(!Array.isArray(e)||e.length===0||e.length>hs)return le(`${t} requires 1-${hs} terms`);let n=e.map(r=>wt(r,t));return t==="fields"&&n.some(r=>!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*){0,7}$/.test(r)||r.split(".").some(o=>["__proto__","constructor","prototype"].includes(o)))?le("fields must be safe metadata paths of at most eight segments"):[...new Set(n)]}function Mh(e){let t=je(e,["kind","fields","authors","allowed"],"rule");return t.kind==="transition"?(je(t,["kind","allowed"],"transition rule"),!Array.isArray(t.allowed)||t.allowed.length>hs?le("transition.allowed must be a bounded array"):{kind:"transition",allowed:t.allowed.map(n=>!Array.isArray(n)||n.length!==2?le("transition pairs need two statuses"):[wt(n[0],"from"),wt(n[1],"to")])}):t.kind==="authors"?(je(t,["kind","authors"],"authors rule"),{kind:"authors",authors:Gn(t.authors,"authors")}):t.kind==="require_fields"?(je(t,["kind","fields"],"require_fields rule"),{kind:"require_fields",fields:Gn(t.fields,"fields")}):t.kind==="field_writers"||t.kind==="approval"?(je(t,["kind","fields","authors"],"field rule"),{kind:t.kind,fields:Gn(t.fields,"fields"),authors:Gn(t.authors,"authors")}):le("unknown rule kind")}function $h(e){let t={},n=je(e,["types","tags","statuses","operations","parents","dependency"],"subject");for(let r of["types","tags","statuses","operations","parents"])n[r]!==void 0&&(t[r]=Gn(n[r],r));if(n.dependency!==void 0){let r=je(n.dependency,["kind","id"],"dependency");t.dependency={kind:wt(r.kind,"dependency kind"),...r.id===void 0?{}:{id:wt(r.id,"dependency id")}}}return t}function jh(e){let t=je(e,["id","description","subject","effect","rule"],"policy"),n=wt(t.id,"id");return/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(n)?t.effect!==void 0&&(typeof t.effect!="string"||!["advise","warn","refuse"].includes(t.effect))?le("effect must be advise, warn, or refuse"):{id:n,rule:Mh(t.rule),...t.subject===void 0?{}:{subject:$h(t.subject)},...t.description===void 0?{}:{description:wt(t.description,"description",500)},...t.effect===void 0?{}:{effect:t.effect}}:le("id must be a stable token")}function Lh(e){let t=je(e,["version","enforcement","policies"],"document");if(t.version!==1)return le("unsupported version");if(t.enforcement!==void 0&&t.enforcement!=="advise"&&t.enforcement!=="refuse")return le("enforcement must be advise or refuse");if(!Array.isArray(t.policies)||t.policies.length>tl)return le(`policies must contain at most ${tl} declarations`);let n=t.policies.map(jh);return new Set(n.map(r=>r.id)).size!==n.length?le("duplicate policy id"):{version:1,enforcement:t.enforcement??"advise",policies:n}}function ro(e,t){let n=e;for(let r of t.split(".")){if(typeof n!="object"||n===null||!Object.hasOwn(n,r))return;n=n[r]}return n}function Fh(e){return e==null?!1:typeof e=="string"?e.trim().length>0:typeof e=="number"?Number.isFinite(e):Array.isArray(e)?e.length>0:typeof e=="object"?Object.keys(e).length>0:!0}function rl(e){return nl("sha256").update(R(e)).digest("hex")}function Uh(e,t){let n=e.rule.kind==="approval"?e.rule.fields:[];return nl("sha256").update(R({id:t.id,fields:n.map(r=>[r,ro(t,r)])})).digest("hex")}function zh(e,t){return Array.isArray(t)&&t.some(n=>typeof n=="object"&&n!==null&&"kind"in n&&n.kind===e.kind&&(e.id===void 0||"id"in n&&n.id===e.id))}function Hh(e,t,n){return!(e.types&&!e.types.some(r=>r.toLowerCase()===String(t.type).toLowerCase())||e.statuses&&!e.statuses.includes(String(t.status))||e.operations&&!e.operations.includes(n)||e.parents&&!e.parents.includes(String(t.parent))||e.tags&&(!Array.isArray(t.tags)||!e.tags.some(r=>t.tags.includes(r)))||e.dependency&&!zh(e.dependency,t.dependencies))}function qh(e,t){if(t.completeness_only&&(e.rule.kind!=="require_fields"||e.subject?.operations!==void 0)||e.rule.kind==="approval"&&t.before===null)return!1;let n=e.subject??{},r=t.after?.status??t.before?.status;return[t.before,t.after].some(o=>o!==null&&Hh(n,{...o,status:r},t.operation))}function Vh(e,t,n,r){let o=["type","tags","parent","dependencies"].some(i=>!B(t.before?.[i],t.after?.[i]));return t.after&&(t.completeness_only||n||r||o)?e.filter(i=>!Fh(ro(t.after,i))):[]}function Bh(e,t,n,r){let o=t.after??t.before,i=Uh(e,o);return t.approvals?.some(s=>s.policy_fingerprint===r&&s.content_fingerprint===i&&s.author!==t.author&&n.includes(s.author))??!1}function Wh(e,t,n){let r=e.rule,o=t.before?.status!==t.after?.status,i="fields"in r&&r.fields.some(s=>!B(ro(t.before,s),ro(t.after,s)));switch(r.kind){case"require_fields":{let s=Vh(r.fields,t,o,i);return{satisfied:s.length===0,missing_fields:s,remediation:"Supply the declared required fields before this lifecycle transition."}}case"transition":return{satisfied:!o||r.allowed.some(([s,a])=>s===String(t.before?.status??"$create")&&a===String(t.after?.status??"$delete")),missing_fields:[],remediation:"Choose a declared allowed transition; inspect pm schema policies."};case"authors":return{satisfied:r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared workflow actor perform this operation."};case"field_writers":return{satisfied:!i||r.authors.includes(t.author),missing_fields:[],remediation:"Have a declared field writer change the protected fields."};case"approval":return{satisfied:!o||Bh(e,t,r.authors,n),missing_fields:[],remediation:`Record an independent approval with pm schema policy-approve <item-id> --policy ${e.id} after preparing the reviewed fields.`}}}function ol(e,t,n){let r=e.policies.filter(o=>qh(o,t)).map(o=>{let i=o.effect??"advise",s=n(o);return{policy_id:o.id,policy_fingerprint:s,rule:o.rule.kind,effect:i==="refuse"&&e.enforcement!=="refuse"?"warn":i,...Wh(o,t,s)}});return{allowed:!r.some(o=>!o.satisfied&&o.effect==="refuse"),decisions:r,warnings:r.filter(o=>!o.satisfied).map(o=>`workflow_policy:${o.effect}:${o.policy_id}:${o.rule}`)}}function XR(e,t){return ol(e,t,rl)}function JR(e){let t=Lh(e),n=new Map(t.policies.map(r=>[r,rl(r)]));return r=>ol(t,r,o=>n.get(o))}(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]="451b262c-a9b6-5f1c-b397-2686a5fd953a")}catch{}})();var Gh=[["history-redact","history redact"],["history-repair","history repair"],["history-compact","history compact"],["activity","history activity"],["restore","history restore"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-tqel"})),Kh=[...["next","focus"].map(e=>({alias:e,canonical:`context ${e}`,owner:"pm-kcs4"})),...["stats","health","validate","gc","telemetry","eval","test-all"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-6apl"})),...["normalize","reindex"].map(e=>({alias:e,canonical:`ops ${e}`,owner:"pm-3i9q8g"})),{alias:"events",canonical:"history events",owner:"pm-3i9q8g"}].map(e=>({...e,canonical_argv:e.canonical.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap"})),Yh=[["update-many","update many"],["close-many","close many"],["delete","close delete"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-ik19"})),Xh=[...Kh,...Yh,...["init","config","schema","profile"].map(e=>({alias:e,canonical:`workspace ${e}`,canonical_argv:["workspace",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-npr3"})),...[...["comments","notes","learnings","files","docs","deps","append","test"].map(e=>[e,`item ${e}`,"pm-yql1"]),["test-runs-worker","item test worker","pm-lp4j"],...["statuses","tags","types"].map(e=>[`completion-${e}`,`completion ${e}`,"pm-szdc"]),["history-author-acknowledge","history acknowledge","pm-djyvbk"],["copy","item copy","pm-m6g87m"],["merge","workspace merge","pm-m6g87m"],["duplicates","item duplicates","pm-fmy9ih"],["dedupe-audit","item duplicates audit","pm-fmy9ih"],["dedupe-merge","item duplicates merge","pm-fmy9ih"],["comments-audit","item audit-comments","pm-fmy9ih"],["search-advanced","search advanced","pm-wfskfn"],...["meet","event","remind"].map(e=>[e,`calendar ${e}`,"pm-o3fh"])].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:n}))],gs=[{alias:"history-attest",canonical:"history attest",canonical_argv:["history","attest"],lifecycle:"permanent",hidden:!0,registration:"commander",owner:"pm-3z0k"},...Gh,...Xh,...["discover","lookup"].map(e=>({alias:`files ${e}`,canonical:`item files ${e}`,canonical_argv:["item","files",e],lifecycle:"permanent",hidden:!0,registration:"bootstrap",owner:"pm-yql1"}))];function QR(e){let t;for(let n of gs)n.canonical_argv.length<=(t?.canonical_argv.length??0)||n.canonical_argv.every((r,o)=>r===(o===0&&e[o]==="ctx"?"context":e[o]))&&(t=n);return t}function Jh(e){let t=e.trim().replace(/\s+/gu," ");return gs.find(n=>n.canonical===t.replace(/^ctx /u,"context "))?.alias??t}function Kn(e){return Jh(e)}var oo=[...gs,...[["ctx","context"],["packages","package"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:[t],lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-pbyu"})),...[["start-task","claim","--start"],["pause-task","release","--pause"],["close-task","close","--release-assignment"]].map(([e,t,n])=>({alias:e,canonical:t,canonical_argv:[t,n],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-eq4x"})),{alias:"tests",canonical:"item test",canonical_argv:["item","test"],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-u4t9gp"},...[["fetch","get"],["read","get"],["show","get"],["view","get"],["comment","comments"],["note","notes"],["learning","learnings"]].map(([e,t])=>({alias:e,canonical:["comments","notes","learnings"].includes(t)?`item ${t}`:t,canonical_argv:["comments","notes","learnings"].includes(t)?["item",t]:[t],lifecycle:"permanent",hidden:!1,registration:"bootstrap",owner:"pm-pbyu"})),...[["extension list","extension catalog"],["extension scaffold","extension init"],["package list","package catalog"],["package scaffold","package init"],["packages list","package catalog"],["packages scaffold","package init"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"permanent",hidden:!1,registration:"commander",owner:"pm-ya7x55"})),{alias:"list-all",canonical:"list",canonical_argv:["list","--all"],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"},...[["list-draft","draft"],["list-open","open"],["list-in-progress","in_progress"],["list-blocked","blocked"],["list-closed","closed"],["list-canceled","canceled"]].map(([e,t])=>({alias:e,canonical:"list",canonical_argv:["list","--status",t],lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-pfqi"})),...[["extension","package"],["install","package install"],["upgrade","package upgrade"]].map(([e,t])=>({alias:e,canonical:t,canonical_argv:t.split(" "),lifecycle:"deprecated",hidden:!0,registration:"commander",owner:"pm-tnud"}))],ex=Object.fromEntries(oo.filter(e=>e.registration==="bootstrap").map(e=>[e.alias,e.canonical]));function tx(e){let t=e.trim().toLowerCase();return oo.find(n=>n.alias===t)}function nx(e){return`Deprecated command \`${e.alias}\`; use \`pm ${e.canonical_argv.join(" ")}\`.`}(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]="3348c61d-a03e-5023-a5dc-fd6149f478c1")}catch{}})();var Zh=[...$e],Qh=[...on],eg=[...Yr],ax=[...Xr],cx=[...Jr],tg=[...Zr],io=["init","config","extension","package","packages","install","upgrade","create","item","copy","focus","list","list-all","list-draft","list-open","list-in-progress","list-blocked","list-closed","list-canceled","aggregate","context","ctx","get","graph","search","duplicates","eval","next","history","events","history-redact","history-repair","history-compact","history-attest","history-author-acknowledge","merge","schema","profile","activity","restore","update","update-many","close","close-many","delete","append","comments","notes","learnings","files","docs","deps","plan","test","test-all","telemetry","stats","health","validate","assurance","gc","workspace","contracts","claim","release","start-task","pause-task","close-task","meet","event","remind","help"],dx=["ancestors","descendants","predecessors","successors","paths","impact","analyze","audit","communities","redundancy","dominators","slack","centrality","articulation","plan","index"],lx=["install","reconcile","report","driver"],ng=["init","install","uninstall","explore","manage","describe","reload","doctor","catalog","adopt","adopt-all","activate","deactivate"],rg=["upgrade"],og=["reopen"],il={help:"Commander help rendering has no SDK operation result.",packages:"The plural package alias only renders package-oriented help."},sn=Object.freeze(io.flatMap(e=>e in il?[]:e==="extension"||e==="package"?[...ng.map(t=>`${e}-${t}`),...e==="package"?rg.map(t=>`package-${t}`):[],e]:e==="item"?og.map(t=>`item-${t}`):[e])),ig=Object.freeze(oo.filter(e=>e.lifecycle==="deprecated"&&e.registration==="commander"&&sn.includes(e.alias)).map(e=>e.alias)),ux=Object.freeze(sn.filter(e=>!ig.includes(e)));function fx(e=io,t=sn,n=il){let r=new Set(t),o=new Set(e);return{missing_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]===void 0),waived_cli_actions:e.filter(i=>!r.has(i)&&!t.some(s=>s.startsWith(`${i}-`))&&n[i]!==void 0),stale_waivers:Object.keys(n).filter(i=>!o.has(i)||r.has(i)||t.some(s=>s.startsWith(`${i}-`)))}}function mx(e){return sn.includes(e)}function px(e){return Zh.includes(e)}function _x(e){return Qh.includes(e)}function yx(e){return eg.includes(e)}function hx(e){return tg.includes(e)}var gx=new Set(["update","item-reopen","close","claim","release","start-task","pause-task","close-task","restore","append","update-many","close-many","delete","comments","notes","learnings","files","docs","test","test-all","plan","history-redact","history-repair","history-compact","validate"]);(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]="b181d38e-7120-5d34-98d9-fd9b4619b9d9")}catch{}})();var sg=["Epic","Feature","Task","Chore","Issue","Decision","Event","Reminder","Milestone","Meeting","Plan"],sl=sg,an=["draft","open","in_progress","blocked","closed","canceled"],so=["draft","active","blocked","terminal","terminal_done","terminal_canceled","default_open","default_close","default_cancel"],cn=["string","number","boolean","string_array","array","object"],ao=["create","update","update_many","list","search","calendar","context"],co=["allow","warn","reject"],wx=["blocks","parent","child","parent_child","child_of","related","related_to","discovered_from","blocked_by","incident_from","epic","implements","recurs_from","supersedes","task","verifies"],vx=["project","global"],Ex=["low","medium","high","critical"],lo=["low","medium","high","critical"],uo=["low","medium","high"];var al=["minimal","default","strict","custom"],kx=["none","warn","strict"],Sx=["progressive","strict"],Ox=["off","warn","strict"],Ax=["off","warn","strict"],cl=["off","warn","strict"];var fo=["daily","weekly","monthly","yearly"],Yn=["mon","tue","wed","thu","fri","sat","sun"];function bs(e){return Yn.indexOf(e)}var Ix=["draft","research","review","approved","executing","paused","completed","superseded"],dl=["pending","in_progress","completed","blocked","skipped","superseded"],Tx=["codex","claude-code","cursor","generic"],Cx=["related","blocks","blocked_by","depends_on","discovered_from","implements","recurs_from","verifies","supersedes"],ll=["brief","standard","deep","full"],Rx=["hierarchy","activity","progress","recently_created","unparented","blockers","files","workload","staleness","tests"];(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]="0ca7f52c-fb31-5cd9-b689-a918f4e61816")}catch{}})();import ug 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]="75f74db3-9547-5c78-8561-f371c016b90d")}catch{}})();function Be(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ag(e){let t=e.key.trim();if(t.length===0)return null;let n=Be(e.aliases),r=e.description?.trim();return{key:t,values:Be(e.values),required:e.required===!0?!0:void 0,aliases:n.length>0?n:void 0,description:r&&r.length>0?r:void 0}}var cg=e=>e,fl=e=>{let t=e.trim().toLowerCase();return t==="create"||t==="update"?t:null};function dg(e,t){let n=t(e.command);if(n===null)return null;let r=e.option.trim();return r.length===0?null:{command:n,option:r,required:e.required,visible:e.visible,enabled:e.enabled}}function lg(e,t){let n=new Map;for(let r of e??[]){let o=dg(r,t);o&&n.set(`${o.command}:${o.option.toLowerCase()}`,o)}return[...n.values()].sort((r,o)=>r.command===o.command?r.option.localeCompare(o.option):r.command.localeCompare(o.command))}function ul(e,t){return t?Be(e):void 0}function ws(e){let t=e?.trim();return t&&t.length>0?t:void 0}function vs(e){if(e===void 0||e==="agent"||e==="human"||e==="gate")return e;throw new Error("Item type execution_role must be agent, human, or gate.")}function mo(e,t={}){let n=t.resolvePolicyCommand??cg,r=e.name.trim();if(r.length===0)return null;let o=e.required_create_fields!==void 0,i=e.required_create_repeatables!==void 0,s=e.options!==void 0,a=e.command_option_policies!==void 0,c=Be(e.aliases),d=(e.options??[]).map(u=>ag(u)).filter(u=>u!==null).sort((u,f)=>u.key.localeCompare(f.key)),l=lg(e.command_option_policies,n);return{name:r,description:ws(e.description),default_status:ws(e.default_status),...e.execution_role===void 0?{}:{execution_role:vs(e.execution_role)},folder:ws(e.folder),aliases:c.length>0?c:void 0,required_create_fields:ul(e.required_create_fields,o),required_create_repeatables:ul(e.required_create_repeatables,i),options:s?d:void 0,command_option_policies:a?l:void 0}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f40ddc8e-1dd5-5f26-b2ba-fbbac30a1781")}catch{}})();var fg=Object.freeze({decision:"human",milestone:"gate"}),mg=["title","description","status","priority","tags","body","deadline","estimatedMinutes","acceptanceCriteria","author","message","assignee"],pg=["dep","comment","note","learning","file","test","doc"],pl=["deadline","estimatedMinutes","acceptanceCriteria","definitionOfReady","order","goal","objective","value","impact","outcome","whyNow","assignee","parent","reviewer","risk","confidence","sprint","release","blockedBy","blockedReason","unblockNote","reporter","severity","environment","reproSteps","resolution","expectedResult","actualResult","affectedVersion","fixedVersion","component","regression","customerImpact"],_g=["title","description","type","status","priority","tags","body",...pl,"author","message","dep","comment","note","learning","file","test","doc","reminder","event","typeOption","field"],yg=["title","description","body","status","closeReason","priority","type","tags",...pl,"author","message","comment","note","learning","file","test","doc","reminder","event","typeOption","field","ownershipMetadataBypass","ownershipDependencyBypass","force"],_l={"close-reason":"closeReason",close_reason:"closeReason","estimated-minutes":"estimatedMinutes",estimated_minutes:"estimatedMinutes",estimate:"estimatedMinutes","acceptance-criteria":"acceptanceCriteria",acceptance_criteria:"acceptanceCriteria",ac:"acceptanceCriteria","definition-of-ready":"definitionOfReady",definition_of_ready:"definitionOfReady",rank:"order","why-now":"whyNow",why_now:"whyNow","blocked-by":"blockedBy",blocked_by:"blockedBy","blocked-reason":"blockedReason",blocked_reason:"blockedReason","unblock-note":"unblockNote",unblock_note:"unblockNote","repro-steps":"reproSteps",repro_steps:"reproSteps","expected-result":"expectedResult",expected_result:"expectedResult","actual-result":"actualResult",actual_result:"actualResult","affected-version":"affectedVersion",affected_version:"affectedVersion","fixed-version":"fixedVersion",fixed_version:"fixedVersion","customer-impact":"customerImpact",customer_impact:"customerImpact","type-option":"typeOption",type_option:"typeOption",type_options:"typeOption"},hg={..._l},gg={..._l},yl=[["deadline","--deadline"],["estimatedMinutes","--estimate/--estimated-minutes"],["acceptanceCriteria","--acceptance-criteria/--ac"],["definitionOfReady","--definition-of-ready"],["order","--order/--rank"],["goal","--goal"],["objective","--objective"],["value","--value"],["impact","--impact"],["outcome","--outcome"],["whyNow","--why-now"],["assignee","--assignee"],["parent","--parent"],["reviewer","--reviewer"],["risk","--risk"],["confidence","--confidence"],["sprint","--sprint"],["release","--release"],["blockedBy","--blocked-by"],["blockedReason","--blocked-reason"],["unblockNote","--unblock-note"],["reporter","--reporter"],["severity","--severity"],["environment","--environment"],["reproSteps","--repro-steps"],["resolution","--resolution"],["expectedResult","--expected-result"],["actualResult","--actual-result"],["affectedVersion","--affected-version"],["fixedVersion","--fixed-version"],["component","--component"],["regression","--regression"],["customerImpact","--customer-impact"]],hl=[["comment","--comment"],["note","--note"],["learning","--learning"],["file","--file"],["test","--test"],["doc","--doc"],["reminder","--reminder"],["event","--event"],["typeOption","--type-option"]];function gl(e){return Object.fromEntries(e)}var bg=gl([["title","--title"],["description","--description"],["type","--type"],["status","--status"],["priority","--priority"],["tags","--tags"],["body","--body"],...yl,["author","--author"],["message","--message"],["dep","--dep"],...hl]),wg=gl([["title","--title"],["description","--description"],["body","--body"],["status","--status"],["closeReason","--close-reason"],["priority","--priority"],["type","--type"],["tags","--tags"],...yl,...hl,["author","--author"],["message","--message"],["force","--force"]]);function vg(e){return e.trim().replace(/^--+/,"").toLowerCase()}function Eg(e){return e==="create"?_g:yg}function kg(e){return e==="create"?hg:gg}function bl(e,t){let n=vg(t);return n.length===0?void 0:kg(e)[n]||Eg(e).find(r=>r.toLowerCase()===n)}function Fx(e,t){return(e==="create"?bg:wg)[t]??`--${t.replace(/([A-Z])/g,"-$1").toLowerCase()}`}function ks(e){let t=Og(e);return t.length===0?"items":t.endsWith("s")?t:`${t}s`}function Sg(e){let t=e.trim(),n=t.replaceAll("\\","/").replace(/^\/+/,""),r=ug.posix.normalize(n);if(t.includes("\0")||/^[A-Za-z]:/.test(r)||r==="."||r===".."||r.startsWith("../"))throw new Error(`Item type folder "${e}" must stay inside the pm tracker root.`);return r}function Og(e){let t=e.trim().toLowerCase(),n="",r=!1;for(let o of t){let i=o.charCodeAt(0),s=i>=97&&i<=122,a=i>=48&&i<=57;if(s||a){r&&n.length>0&&(n+="-"),n+=o,r=!1;continue}n.length>0&&(r=!0)}return n}function Ag(e){return mo(e,{resolvePolicyCommand:fl})}function Xn(e,t){let n=e[t];return Array.isArray(n)?n.filter(r=>typeof r=="string"):void 0}function Ig(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;return typeof t.key!="string"?null:{key:t.key,values:Xn(t,"values")??[],required:t.required===void 0?void 0:!!t.required,aliases:Xn(t,"aliases"),description:typeof t.description=="string"?t.description:void 0}}function Tg(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e;if(typeof t.command!="string"||typeof t.option!="string")return null;let n=t.command.trim().toLowerCase();return n!=="create"&&n!=="update"?null:{command:n,option:t.option,required:t.required===void 0?void 0:!!t.required,visible:t.visible===void 0?void 0:!!t.visible,enabled:t.enabled===void 0?void 0:!!t.enabled}}function Cg(e){if(Array.isArray(e.options))return e.options.map(t=>Ig(t)).filter(t=>t!==null)}function Rg(e){if(Array.isArray(e.command_option_policies))return e.command_option_policies.map(t=>Tg(t)).filter(t=>t!==null)}function xg(e){if(typeof e!="object"||e===null||Array.isArray(e))return null;let t=e,n=typeof t.name=="string"?t.name:"";if(n.trim().length===0)return null;let r=typeof t.folder=="string"?t.folder:void 0,o=typeof t.description=="string"?t.description:void 0,i=typeof t.default_status=="string"?t.default_status:void 0;return{name:n,description:o,default_status:i,execution_role:vs(t.execution_role),folder:r,aliases:Xn(t,"aliases"),required_create_fields:Xn(t,"required_create_fields"),required_create_repeatables:Xn(t,"required_create_repeatables"),options:Cg(t),command_option_policies:Rg(t)}}function Ng(e,t){return e.required_create_fields?Be(e.required_create_fields):t?.required_create_fields??[]}function Dg(e,t){return e.required_create_repeatables?Be(e.required_create_repeatables):t?.required_create_repeatables??[]}function Pg(e,t){return e.options?e.options:t?.options?[...t.options]:[]}function Mg(e,t){return e.command_option_policies?e.command_option_policies:t?.command_option_policies?[...t.command_option_policies]:[]}function $g(e,t){let n=t?.name??e.name,r=e.description??t?.description,o=e.default_status??t?.default_status,i=Sg(e.folder??t?.folder??ks(n)),s={name:n,execution_role:e.execution_role,folder:i,aliases:Be([...t?.aliases??[],...e.aliases??[]]),required_create_fields:Ng(e,t),required_create_repeatables:Dg(e,t),options:Pg(e,t),command_option_policies:Mg(e,t)};return r&&(s.description=r),o&&(s.default_status=o),s}function ml(e,t){for(let n of e){let r=Ag(n);if(!r)continue;let o=r.name.toLowerCase(),i=t.get(o);t.set(o,$g({...r,execution_role:r.execution_role??i?.execution_role},i))}}function jg(e){if(!e)return[];let t=[];for(let n of e.item_types??[]){let r=n.types;if(Array.isArray(r))for(let o of r){let i=xg(o);i&&t.push(i)}}return t}function Ux(e,t=null){let n=new Map;for(let c of sl)n.set(c.toLowerCase(),{name:c,execution_role:fg[c.toLowerCase()]??"agent",folder:Bn[c],aliases:[],required_create_fields:[...mg],required_create_repeatables:[...pg],options:[],command_option_policies:[]});ml(e.item_types?.definitions??[],n),ml(jg(t),n);let r=[...n.values()].sort((c,d)=>c.name.localeCompare(d.name)),o={},i={},s={};for(let c of r){o[c.name]=c,s[c.name]=c.folder,i[c.name.toLowerCase()]=c.name;for(let d of c.aliases)i[d.toLowerCase()]=c.name}let a=[...new Set(r.map(c=>c.folder))].sort((c,d)=>c.localeCompare(d));return{types:r.map(c=>c.name),folders:a,type_to_folder:s,by_type:o,alias_to_type:i}}function Lg(e,t){if(e!==void 0)return t.alias_to_type[e.trim().toLowerCase()]}function Fg(e,t){let n=Lg(e,t);if(n)return t.by_type[n]}function Ug(e,t,n,r){for(let o of r){let i=bl(n,o);if(i){e.required.add(i);continue}e.errors.push(`Unsupported base required option "${o}" for command "${n}" on type "${t.name}"`)}}function Es(e,t,n){if(n){e.add(t);return}e.delete(t)}function zg(e,t,n,r){let o=bl(n,r.option);if(!o){e.errors.push(`Unsupported command_option_policies option "${r.option}" for command "${n}" on type "${t.name}"`);return}r.required!==void 0&&Es(e.required,o,r.required),r.visible!==void 0&&Es(e.hidden,o,!r.visible),r.enabled!==void 0&&Es(e.disabled,o,!r.enabled)}function Hg(e,t,n){for(let r of t.command_option_policies)r.command===n&&zg(e,t,n,r)}function qg(e,t,n){for(let r of e.required)e.disabled.has(r)&&e.errors.push(`Option "${r}" cannot be both required and disabled for command "${n}" on type "${t.name}"`)}function zx(e,t,n){let r=[],o=new Set,i=new Set,s=new Set,a={required:o,hidden:i,disabled:s,errors:r};return Ug(a,e,t,n),Hg(a,e,t),qg(a,e,t),{required:[...o],hidden:[...i].sort((c,d)=>c.localeCompare(d)),disabled:[...s].sort((c,d)=>c.localeCompare(d)),errors:r}}function Vg(e){let t=new Map;for(let n of e.options){t.set(n.key.toLowerCase(),n);for(let r of n.aliases??[])t.set(r.toLowerCase(),n)}return t}function Bg(e,t,n){let r=e.values;if(r.length===0)return t;let o=new Map(r.map(i=>[i.toLowerCase(),i])).get(t.toLowerCase());if(!o){n.push(`Invalid value "${t}" for type option "${e.key}". Allowed: ${r.join(", ")}`);return}return o}function Hx(e,t,n){let r=Fg(e,n);if(!r)return{normalized:void 0,errors:[`Unknown type "${e}"`]};let o=[],i=Vg(r),s={};for(let[c,d]of Object.entries(t??{})){let l=c.trim(),u=d.trim();if(l.length===0){o.push("type option keys must not be empty");continue}if(u.length===0){o.push(`type option "${l}" must not be empty`);continue}let f=i.get(l.toLowerCase());if(!f){let _=r.options.map(y=>y.key).join(", ");o.push(r.options.length>0?`Unknown type option "${l}" for type "${r.name}". Allowed: ${_}`:`Type "${r.name}" does not define any configurable type options`);continue}let m=Bg(f,u,o);m!==void 0&&(s[f.key]=m)}for(let c of r.options)c.required&&!(c.key in s)&&o.push(`Missing required type option "${c.key}" for type "${r.name}"`);let a=Object.keys(s).sort((c,d)=>c.localeCompare(d));return a.length===0?{normalized:void 0,errors:o}:{normalized:Object.fromEntries(a.map(c=>[c,s[c]])),errors:o}}import{readFileSync as Wg,readdirSync as Gg,realpathSync as wl,statSync as vl}from"node:fs";import Kg from"node:os";import C 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]="7f4b8abe-997c-549c-9791-87c78506c8b5")}catch{}})();var Yg={json_markdown:".md",toon:".toon"},Xg={".md":"json_markdown",".toon":"toon"},Jg=new Set([".git","coverage","dist","node_modules"]),Jx=[".md",".toon"];function Jn(e){try{return vl(e),!0}catch{return!1}}function Zg(e){let t=C.resolve(e),n=[];for(;C.dirname(t)!==t;)try{return C.join(wl(t),...n)}catch(r){if(!be(r))throw r;n.unshift(C.basename(t)),t=C.dirname(t)}return C.join(wl(t),...n)}function Qg(e){try{return vl(e),!0}catch(t){if(be(t))return!1;throw t}}function El(e){try{let t=JSON.parse(Wg(e,"utf8"));return typeof t!="object"||t===null||Array.isArray(t)?!1:"id_prefix"in t||"item_format"in t}catch{return!1}}function eb(e){let t=Zg(e);for(;;){let n=C.join(t,Qr),r=C.join(n,eo);if(Jn(r))return n;let o=C.join(t,eo);if(Jn(o)&&El(o))return t;if(Qg(C.join(t,".git")))return n;let i=C.dirname(t);if(i===t)return;t=i}}function Ss(e){return eb(e)??C.resolve(e,Qr)}function Zx(e,t){let n=t?C.resolve(t):void 0;try{return Gg(C.resolve(e),{withFileTypes:!0}).filter(r=>r.isDirectory()&&!Jg.has(r.name)).map(r=>C.join(C.resolve(e),r.name)).filter(r=>r!==n).filter(r=>Jn(Ie(r))).filter(r=>El(Ie(r))).sort((r,o)=>r.localeCompare(o))[0]}catch{return}}function kl(e,t){let n=process.env.PM_PATH,r=t?.trim()||n?.trim();if(r){let o=C.resolve(e,r);if(!Jn(Ie(o))){let i=C.join(o,Qr);if(Jn(Ie(i)))return i}return o}return Ss(e)}function Sl(e){let t=C.resolve(e),n=C.dirname(t);return C.basename(t)==="pm"&&C.basename(n)===".agents"?C.dirname(n):t}function Ol(e){let t=process.env.PM_GLOBAL_PATH?.trim(),n=t&&t.length>0?t:C.join(Kg.homedir(),".pm-cli");return C.resolve(e,n)}function Ie(e){return C.join(e,eo)}function tb(e,t,n=Bn){let r=n[t]??ks(t);return C.join(e,r)}function Qx(e,t,n,r="toon",o=Bn){return C.join(tb(e,t,o),`${n}${Yg[r]}`)}function eN(e){let t=e.replaceAll("\\","/"),n=C.posix.extname(t).toLowerCase();return Xg[n]??null}function tN(e,t){if(!/^(?!\.{1,2}$)[^/\\:\0]+$/.test(t))throw new g("Invalid history item id: expected a single filename.",h.USAGE);return C.join(e,"history",`${t}.jsonl`)}function Os(e,t){return C.join(e,"locks",`${t}.lock`)}function As(e){return C.join(e,"runtime")}function po(e){return C.join(As(e),"test-runs")}function nb(e){return C.join(po(e),"runs")}function nN(e,t){return C.join(nb(e),`${t}.json`)}function rb(e){return C.join(po(e),"stdout")}function ob(e){return C.join(po(e),"stderr")}function rN(e,t){return C.join(rb(e),`${t}.log`)}function oN(e,t){return C.join(ob(e),`${t}.log`)}function ib(e){return C.join(po(e),"results")}function iN(e,t){return C.join(ib(e),`${t}.json`)}(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]="86412887-5659-5892-beaa-bdd15a02ff4c")}catch{}})();var _o=e=>{let t='"',n=0;for(let r of e){if(r==="\\"){n+=1;continue}t+="\\".repeat(r==='"'?n*2+1:n),t+=r,n=0}return`${t}${"\\".repeat(n*2)}"`},Al=(e,t=process.platform)=>(t==="win32"?/^[A-Za-z0-9._:/\\@=-]+$/:/^[A-Za-z0-9._:/@=-]+$/).test(e)?e:t==="win32"?_o(e):`"${e.replace(/(["\\$`])/g,"\\$1")}"`,dn=(e,t=process.platform)=>{let n=e.map(r=>Al(r,t)).join(" ");return n.length>0?`pm ${n}`:"pm"};import{AsyncLocalStorage as sb}from"node:async_hooks";(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]="4c000977-ebd7-5f07-93c7-32363e9ef2d9")}catch{}})();var Ts="[redacted]";function ab(e,t){if(/[\t\n\r]/u.test(e)||!/(?:^|[^A-Za-z0-9+.-])(?:https?|wss?|ftp)$/iu.test(e.slice(0,t)))return!1;let n=t+1;for(;e[n]==="/"||e[n]==="\\";)n+=1;let r=e.indexOf("/",n)-n;if(r<0)return!1;let o=n+r;return!/[:@%]/u.test(e.slice(n,o))&&!/[:%]|[/\\][/\\]/u.test(e.slice(o))}function Cs(e){let t=Math.max(e.lastIndexOf("@"),e.toLowerCase().lastIndexOf("%40")),n=e.indexOf(":");if(t<0||n<0||n>t)return;let r=n+1;for(;r<t&&r<n+3&&(e[r]==="/"||e[r]==="\\");)r+=1;return r===t||ab(e,n)?void 0:[r,t]}function Rs(e){let t=Cs(e);return t?`${e.slice(0,t[0])}${Ts}${e.slice(t[1])}`:e}function Il(e){return Rs(e)}var Tl=["author","assignee","claim_principal"];function fN(e){let t={...e};for(let n of Tl)typeof t[n]=="string"&&(t[n]=Il(t[n]));return t}function ln(e,t){if(!(typeof e!="string"||Cs(e.trim())===void 0))throw new g(`${t} must not carry URL credentials: an identity is a name, never a credential.`,h.USAGE,{code:"invalid_argument_value",field:t,required:`Set ${t} to a plain name such as agent-a, without user:password@ or token@ userinfo.`,nextSteps:[`Rerun with ${t} set to a plain name.`]})}function mN(e,t){return ln(e,t),e}var cb=[["comments","author"],["notes","author"],["learnings","author"],["dependencies","author"],["plan_decisions","author"],["plan_discoveries","author"],["tests","provenance","author"]],db=4;function Is(e,t,n=0){if(typeof e=="string"){ln(e,t);return}if(!(n>=db||typeof e!="object"||e===null))for(let r of Object.values(e))Is(r,t,n+1)}function lb(e,t){let n=e;for(let r of t){if(typeof n!="object"||n===null||Array.isArray(n))return;n=n[r]}return n}function Cl(e){let t=e;for(let n of Tl)Is(t[n],n);for(let[n,...r]of cb){let o=t[n];Array.isArray(o)&&o.forEach((i,s)=>{Is(lb(i,r),`${n}[${s}].${r.join(".")}`)})}}function pN(e){return typeof e=="string"?Il(e):e}var yo=6,ub=65536,Rl={carried:!1,fragments:new Set,fragmentLength:yo,shortSpellings:[]},xs=new sb;function xl(e){let t=e.toLowerCase();if(t.length===e.length)return t;let n="";for(let r of e){let o=r.toLowerCase();n+=o.length===r.length?o:r}return n}function fb(e){return[e,e.replaceAll(/(["\\$`])/gu,"\\$1"),_o(`${e}@`).slice(1,-2),JSON.stringify(e).slice(1,-1)]}function mb(e){let t=e.indexOf(":");return t>=0&&t<e.length-1?e.slice(t+1):e}function pb(e){let t=new Set,n=!1;for(let d of e){let l=Cs(d);if(l){n=!0;for(let u of fb(mb(d.slice(l[0],l[1]))))t.add(xl(u))}}let r=[...t],o=r.reduce((d,l)=>d+Math.max(0,l.length-yo+1)+1,0),i=Math.max(1,Math.ceil(o/ub)),s=Math.max(yo,i),a=new Set,c=new Set;for(let d of r){if(d.length<s){(d.length>=yo||/\s/u.test(d))&&c.add(d);continue}for(let l=0;l+s<=d.length;l+=i)a.add(d.slice(l,l+s));a.add(d.slice(-s))}return{carried:n,fragments:a,fragmentLength:s,shortSpellings:[...c]}}function _b(e,t){let n=xl(e),r=new Uint8Array(e.length),o=!1,i=t.fragmentLength;for(let a=0;a+i<=n.length;a+=1)t.fragments.has(n.slice(a,a+i))&&(r.fill(1,a,a+i),o=!0);for(let a of t.shortSpellings)for(let c=n.indexOf(a);c>=0;c=n.indexOf(a,c+1))r.fill(1,c,c+a.length),o=!0;if(!o)return e;let s="";for(let a=0;a<e.length;a+=1)r[a]?(a===0||!r[a-1])&&(s+=Ts):s+=e[a];return s}function yb(e,t){return xs.run(pb(e),t)}function hb(){return(xs.getStore()??Rl).carried}function gb(e){let t=xs.getStore()??Rl,n=t.carried?_b(e,t):e;return/@|%40/iu.test(n)?n.replaceAll(/\S+/gu,Rs):n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9bb3b2ed-c289-5b96-99ce-9df6e202c464")}catch{}})();var Nl=new Set(["--pm-path","--path","--author","--expect-hash","--output-include","--output-limit","--output-budget","--output-format","--format","--output-session","--output-cursor"]),bb=new Set(["--no-extensions","--no-pager","--json","--quiet","--lean","--token-accounting","--output-row-contract","--all"]);function wb(e){let t=e.indexOf("=");return t>0&&Nl.has(e.slice(0,t))}function vb(e,t){return typeof t!="string"?!1:e==="--path"||e==="--pm-path"||!t.startsWith("-")}function ho(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(n==="--")return;if(Nl.has(n)){t+=vb(n,e[t+1])?1:0;continue}if(!(wb(n)||bb.has(n)||n==="--profile"||n==="--id-only"||n==="--explain")&&!n.startsWith("-"))return t}}function yN(e){let t=ho(e);return t===void 0?void 0:e[t].trim().toLowerCase()}import Eb from"node:path";import Dl from"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]="01422574-583a-5fd1-bc00-f61f430073cd")}catch{}})();function Zn(e,t){let n=Dl.relative(e,t);return n.length===0?!0:!n.startsWith("..")&&!Dl.isAbsolute(n)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="7f08c44a-dfdf-5c23-8f68-0e3ed73582b0")}catch{}})();var Ns=new WeakMap;function AN(e){Ns.set(e,e.path)}function kb(e){if(!process.env.PM_PATH?.trim())return;let t=kl(e);return Zn(Sl(t),e)&&t===Ss(e)?void 0:Eb.relative(e,t)||"."}function IN(e,t=process.cwd()){let n=Ns.has(e)?Ns.get(e):e.path,r=n?.trim()?n:kb(t),o=r?["--pm-path",r]:[];return e.noExtensions&&o.push("--no-extensions"),o}var Sb=new Set(["--literal","--regex","--replacement"]);function Ob(e){let t=ho(e);if(t===void 0)return!1;if(e[t]==="history-redact")return!0;if(e[t]!=="history")return!1;let n=e.slice(t+1),r=ho(n);return r!==void 0&&n[r]==="redact"}function TN(e){if(!Ob(e))return[...e];let t=[],n=!1;for(let r of e){if(n){t.push("[redacted]"),n=!1;continue}n=!1;let o=r.indexOf("="),i=o>=0?r.slice(0,o):r;if(!Sb.has(i)){t.push(r);continue}if(o>=0){t.push(`${i}=[redacted]`);continue}t.push(i),n=!0}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d4155698-c244-5623-b627-92dd25297125")}catch{}})();var Ab=Object.freeze([{flag:"--json"},{flag:"--lean"},{flag:"--token-accounting"},{flag:"--output-include",value_name:"fields",extension_command_availability:"read_output"},{flag:"--output-limit",value_name:"count",extension_command_availability:"read_output"},{flag:"--output-budget",value_name:"tokens",extension_command_availability:"read_output"},{flag:"--output-format",value_name:"toon|json"},{flag:"--output-session",value_name:"state",extension_command_availability:"read_output"},{flag:"--output-cursor",value_name:"cursor",extension_command_availability:"read_output"},{flag:"--output-row-contract",extension_command_availability:"read_output"},{flag:"--quiet"},{flag:"--no-changed-fields"},{flag:"--full-changed-fields"},{flag:"--id-only"},{flag:"--pm-path",aliases:["--path"],discovery_value_name:"path"},{flag:"--no-extensions",extension_command_availability:"never"},{flag:"--no-pager"},{flag:"--profile"},{flag:"--help"},{flag:"--author",value_name:"id"},{flag:"--expect-hash",value_name:"revision"}]),go=new Set(Ab.flatMap(e=>[e.flag,...e.aliases??[]]));(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]="81054684-60df-57c9-af9d-0996874c1024")}catch{}})();var Pl=/^(--[a-z0-9][a-z0-9_-]*)(?:[ =](<[^<>]+>|\[[^[\]]+\]))?$/;function Ds(e){if(typeof e!="string")return null;let t=Pl.exec(e.trim());if(!t)return null;let n=t[2];return{name:t[1],valueName:n?n.slice(1,-1):null,optional:n?.startsWith("[")??!1}}function NN(e){let t=Ds(e);return t?t.name:typeof e=="string"&&e.trim()||null}function Ib(e){if(typeof e!="string")return null;let t=e.trim(),n=t.split(/[ =]/,1)[0];return go.has(n)||go.has(`--${n.slice(2).replaceAll("_","-")}`)?"host_owned_flag_collision":Pl.test(t)?null:"malformed_long_flag"}function Ml(e,t){let n=[e,t].find(i=>typeof i=="string"&&go.has(i.trim().split(/[ =]/,1)[0]));if(typeof n=="string")return{token:n.trim().split(/[ =]/,1)[0],failure:"host_owned_flag_collision"};if(typeof e!="string")return null;let r=e.trim(),o=Ib(r);return o===null?null:{token:r,failure:o}}function $l(e,t){return t==="host_owned_flag_collision"?`cannot shadow host-owned global flag "${e}"; read it from context.global instead`:`long flag "${e}" must start with a double-dash name such as "--my-flag" or "--my-flag <value>"`}(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]="a797572f-fbc6-5e62-a9b5-5a0bd6ef22b4")}catch{}})();function Tb(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}function PN(e){return Tb(e)??void 0}function MN(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t-=1;return t===e.length?e:e.slice(0,t)}function $N(e){return Array.isArray(e)&&e.every(t=>typeof t=="number"&&Number.isFinite(t))}function Ll(e){if(e instanceof Error){let t=e.message.trim();return t.length>0?t:e.name}return String(e)}function bo(e){let t=typeof e=="number"?e:typeof e=="string"&&e.trim().length>0?Number(e.trim()):Number.NaN;return Number.isFinite(t)?t:null}function jN(e){let t=bo(e);return t===null||t<=0||!Number.isInteger(t)?null:t}function LN(e,t,n){let r=bo(e);return r===null||r<t||r>n?null:r}function FN(e){return typeof e!="object"||e===null||Array.isArray(e)?null:e}function We(e){return typeof e!="object"||e===null?null:e}function jl(e){return typeof e!="object"&&typeof e!="function"||e===null?null:e}function Fl(e){let t=jl(e);if(!t)return null;if(typeof t.activate=="function")return t;let n=jl(t.default);return typeof n?.activate=="function"?n:null}function UN(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e}:{}}(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]="92573990-a040-526d-a0b1-b91d2ef401f1")}catch{}})();function wo(e){let t=Math.ceil(e.size/2);for(let n of e.keys()){if(t===0)return;e.delete(n),t-=1}}import Cb from"node:crypto";import{AsyncLocalStorage as Rb}from"node:async_hooks";(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]="ced47074-06d3-53b9-af75-63586cbd4f6a")}catch{}})();var Ps=new Rb,Ul=1024;function xb(e){let t=Date.parse(e.clock);if(!Number.isFinite(t))throw new Error(`Invalid reproducible workspace clock: ${e.clock}`);if(!Number.isSafeInteger(e.tickMs)||e.tickMs<0)throw new Error("Reproducible workspace tickMs must be a non-negative integer");if(e.seed.trim().length===0)throw new Error("Reproducible workspace seed must not be empty");return{...e,clock:new Date(t).toISOString()}}function Nb(e){let t={...xb(e),clockReads:0,tokenReads:0};return n=>Ps.run(t,n)}async function BN(e,t){return Nb(e)(t)}function zl(){let e=Ps.getStore();if(e===void 0)return;let t=new Date(Date.parse(e.clock)+e.clockReads*e.tickMs).toISOString();return e.clockReads+=1,t}function WN(e){let t=Ps.getStore();if(t===void 0)return;if(!Number.isSafeInteger(e)||e<0||e>Ul)throw new Error(`Reproducible token length must be an integer between 0 and ${Ul}`);let n="";for(;n.length<e;){let r=Cb.createHash("sha256").update(`${t.seed}\0${t.tokenReads}`).digest();t.tokenReads+=1;for(let o of r)if(n+=(o%36).toString(36),n.length===e)break}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0bf155fc-c690-5318-ba1e-275f1787858b")}catch{}})();var Db=/^([+-]?)(\d+)([hdwm])$/i,Pb=/^[+-]?\d+[hdwm](?:[+-]\d+[hdwm])+$/i,Mb=/^(\d{4})(\d{2})(\d{2})$/,$b=/^(\d{4})(\d{2})(\d{2})(?:[T\s]?)(\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,jb=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})-(\d{2})(?:-(\d{2}))?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Lb=/^(\d{4}-\d{2}-\d{2})[T\s](\d{2})(\d{2})(\d{2})?([.,]\d{1,3})?(Z|[+-]\d{2}:?\d{2})?$/i,Fb=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/i;function Te(){return zl()??new Date().toISOString()}function Le(e){return Number.isFinite(Date.parse(e))}function Qn(e){let t=Fb.exec(e);if(!t||!Number.isFinite(Date.parse(e)))return!1;let[,n,r,o,i,s,a,c,d]=t,[l,u,f,m,_,y]=[n,r,o,i,s,a].map(Number);return u>=1&&u<=12&&f>=1&&f<=js(l,u-1)&&m<=23&&_<=59&&y<=59&&(c===void 0||Number(c)<=23)&&(d===void 0||Number(d)<=59)}function un(e){let t=/\.(\d+)(?:Z|[+-]\d{2}:\d{2})$/iu.exec(e)?.[1];return Qn(e)&&(t===void 0||/^\d{0,3}0*$/u.test(t))}var Ub=1e4,vo=new Map;function Hl(e){let t=vo.get(e);if(t!==void 0)return t;let n=Date.parse(e);return vo.size>=Ub&&wo(vo),vo.set(e,n),n}function re(e,t){let n=Hl(e),r=Hl(t);return Number.isFinite(n)&&Number.isFinite(r)&&n!==r?n-r:e.localeCompare(t)}function ZN(e,t){return!(t.deadlineBefore&&(!e.deadline||re(e.deadline,t.deadlineBefore)>0)||t.deadlineAfter&&(!e.deadline||re(e.deadline,t.deadlineAfter)<0)||t.updatedAfter&&re(e.updated_at,t.updatedAfter)<0||t.updatedBefore&&re(e.updated_at,t.updatedBefore)>0||t.createdAfter&&re(e.created_at,t.createdAfter)<0||t.createdBefore&&re(e.created_at,t.createdBefore)>0)}function Ms(e){return e?`.${e.slice(1).padEnd(3,"0").slice(0,3)}`:""}function $s(e){if(!e)return"";if(e.toUpperCase()==="Z")return"Z";let t=/^([+-]\d{2})(\d{2})$/.exec(e);return t?`${t[1]}:${t[2]}`:e}function zb(e,t,n){n&&n!==t&&(e.includes(n)||e.push(n))}function Hb(e){let t=[],n=d=>zb(t,e,d),r=Mb.exec(e);if(r){let[,d,l,u]=r;n(`${d}-${l}-${u}`)}let o=$b.exec(e);if(o){let[,d,l,u,f,m,_,y,b]=o,v=_?`:${_}`:"";n(`${d}-${l}-${u}T${f}:${m}${v}${Ms(y)}${$s(b)}`)}let i=jb.exec(e);if(i){let[,d,l,u,f,m,_]=i,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${Ms(m)}${$s(_)}`)}let s=Lb.exec(e);if(s){let[,d,l,u,f,m,_]=s,y=f?`:${f}`:"";n(`${d}T${l}:${u}${y}${Ms(m)}${$s(_)}`)}let a=10,c=e.slice(0,a);if(Vb(c)){let d=a;for(;d<e.length&&Bb(e[d]);)d+=1;d<e.length&&n(`${c}T${e.slice(d)}`)}return t}function qb(e){let t=Date.parse(e);if(Number.isFinite(t))return t;for(let n of Hb(e)){let r=Date.parse(n);if(Number.isFinite(r))return r}return Number.NaN}function Vb(e){if(e.length!==10)return!1;for(let t=0;t<e.length;t+=1){let n=e[t];if(t===4||t===7){if(n!=="-")return!1;continue}let r=n.charCodeAt(0);if(r<48||r>57)return!1}return!0}function Bb(e){return e?e===" "||e===" "||e===`
2
+ `||e==="\r"||e==="\f"||e==="\v":!1}function js(e,t){return new Date(Date.UTC(e,t+1,0)).getUTCDate()}var Wb=["January","February","March","April","May","June","July","August","September","October","November","December"],Gb=/^(\d{4})-(\d{2})-(\d{2})/,Kb=/^(\d{4})(\d{2})(\d{2})(?:[T ]?\d{2}|$)/;function Yb(e,t,n){let r=Gb.exec(t)??Kb.exec(t);if(!r)return;let o=Number.parseInt(r[1],10),i=Number.parseInt(r[2],10),s=Number.parseInt(r[3],10),a=n?.trim()||"deadline";if(i<1||i>12)throw new g(`Invalid ${a} value "${e}". Month "${r[2]}" is out of range \u2014 use a month between 01 and 12.`,h.USAGE,{field:a,value:e});let c=js(o,i-1);if(s<1||s>c)throw new g(`Invalid ${a} value "${e}". ${Wb[i-1]} ${o} has ${c} days, so day "${r[3]}" does not exist. Use a real YYYY-MM-DD calendar date.`,h.USAGE,{field:a,value:e})}function Xb(e,t){let n=new Date(e.getTime()),r=n.getUTCDate(),o=n.getUTCMonth()+t,i=n.getUTCFullYear()+Math.floor(o/12),s=(o%12+12)%12,a=Math.min(r,js(i,s));return n.setUTCFullYear(i,s,a),n}function QN(e,t=new Date,n="deadline"){let r=e.trim();if(r.toLowerCase()==="now")return t.toISOString();let o=Db.exec(r);if(o){let s=o[1]==="-"?-1:1,a=Number.parseInt(o[2],10)*s,c=o[3].toLowerCase();if(c==="m")return Xb(t,a).toISOString();let d=c==="h"?3600*1e3:c==="d"?1440*60*1e3:10080*60*1e3;return new Date(t.getTime()+a*d).toISOString()}Yb(e,r,n);let i=qb(r);if(!Number.isFinite(i)){let s=n.trim().length>0?n.trim():"deadline",a=Pb.test(r)?"Compound relative expressions like +3d+1h are not supported; use a single relative token (for example +3d) or an ISO/date string.":'Use ISO/date string input, "now", or relative +6h/-6h/+1d/-1d/+2w/-2w/+6m/-6m.';throw new g(`Invalid ${s} value "${e}". ${a}`,h.USAGE,{field:s,value:e})}return new Date(i).toISOString()}(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]="5c3049c3-1d5a-5e7e-a070-35340737a6ab")}catch{}})();var ql=Object.freeze({string:"string",number:"number",int:"number",integer:"number",float:"number",boolean:"boolean",bool:"boolean"});function Eo(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.hasOwn(ql,t)?ql[t]:null}function Jb(e,t,n){return!!(e.value_name?.trim()||t||n||e.required===!0||e.list===!0||e.repeatable===!0)}function Zb(e){return(e.value_type?.trim()||e.type?.trim())?.toLowerCase()}function nD(e){let t=Zb(e),n=Eo(t),r=Ds(e.long),o=e.value_name?.trim()||null,i=!(n==="boolean"&&t!=="bool")&&Jb(e,r?.valueName,t),s=r?.valueName?r.optional:t==="bool";return{value_type:n,value_arity:i?s?"optional":"required":"none",value_name:i?o??r?.valueName??"value":null}}function Vl(e){let t=[],n=r=>{if(Array.isArray(r)){for(let o of r)n(o);return}if(typeof r=="string"){for(let o of r.split(",")){let i=o.trim();i.length>0&&t.push(i)}return}r!=null&&t.push(r)};return n(e),t}function Bl(e,t){return t==="string"?!0:t==="number"?typeof e=="number"?Number.isFinite(e):typeof e=="string"&&e.trim().length>0&&Number.isFinite(Number(e)):typeof e=="boolean"?!0:typeof e=="string"&&["true","false","1","0"].includes(e.trim().toLowerCase())}function rD(e,t){return t==="number"?typeof e=="number"&&Number.isFinite(e)?null:{kind:t,received:e,expected:"a finite number"}:typeof e=="boolean"?null:{kind:t,received:e,expected:"true, false, 1, or 0"}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="628615ea-5be3-5753-a6c5-3eba8400a8da")}catch{}})();function ko(e,t,n){if(e===t)return 0;if(Math.abs(e.length-t.length)>n)return null;let r=t.length+1,o=new Array(r),i=new Array(r),s=new Array(r);for(let c=0;c<r;c+=1)o[c]=0,i[c]=c;for(let c=1;c<=e.length;c+=1){s[0]=c;let d=s[0];for(let l=1;l<=t.length;l+=1){let u=e[c-1]===t[l-1]?0:1,f=i[l-1]+u,m=s[l-1]+1,_=i[l]+1,y=Math.min(f,m,_);c>1&&l>1&&e[c-1]===t[l-2]&&e[c-2]===t[l-1]&&(y=Math.min(y,o[l-2]+1)),s[l]=y,y<d&&(d=y)}if(d>n)return null;for(let l=0;l<r;l+=1)o[l]=i[l],i[l]=s[l]}let a=i[t.length];return a<=n?a:null}(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]="2ea7934f-4751-5245-a5ba-492681aa3794")}catch{}})();var Ls=[{kind:"blocked_by",direction:"directed",traversal:"ordering",inverse:"blocks",ordering:!0,precedence:"target_before_source",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["depends_on"],compatibilityVersion:1,allowSelf:!1},{kind:"blocks",direction:"directed",traversal:"ordering",inverse:"blocked_by",ordering:!0,precedence:"source_before_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"parent",direction:"directed",traversal:"hierarchy",outcomeTraversal:"source_to_target",inverse:"child",ordering:!1,hierarchy:!0,hierarchyDirection:"target_parent",outgoing:"one",incoming:"many",lifecycle:"supersedable",aliases:["child_of","epic"],compatibilityVersion:1,allowSelf:!1},{kind:"child",direction:"directed",traversal:"hierarchy",outcomeTraversal:"target_to_source",inverse:"parent",ordering:!1,hierarchy:!0,hierarchyDirection:"source_parent",outgoing:"many",incoming:"one",lifecycle:"supersedable",aliases:["parent_child","task"],compatibilityVersion:1,allowSelf:!1},{kind:"related",direction:"undirected",traversal:"association",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",aliases:["related_to"],compatibilityVersion:1,allowSelf:!1},{kind:"discovered_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"incident_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"implements",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"recurs_from",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,temporalOrder:"source_after_target",hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"verifies",direction:"directed",traversal:"semantic",outcomeTraversal:"source_to_target",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"persistent",compatibilityVersion:1,allowSelf:!1},{kind:"supersedes",direction:"directed",traversal:"semantic",outcomeTraversal:"both",ordering:!1,hierarchy:!1,outgoing:"many",incoming:"many",lifecycle:"supersedable",compatibilityVersion:1,allowSelf:!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]="418b3f7f-6350-5878-a362-3948de287baf")}catch{}})();function Ao(e){return e.trim().toLowerCase().replaceAll("-","_")}function Qb(e){if(e===void 0)return;let t=Ao(e);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid inverse relationship kind: ${e}`);return t}function Us(e,t=new Set){if(e===null||typeof e!="object"||t.has(e))return e;if(t.add(e),Array.isArray(e)){for(let n of e)Us(n,t);return Object.freeze(e)}for(let n of Object.values(e))Us(n,t);return Object.freeze(e)}function ew(e,t){if(e.precedence!==void 0&&e.precedence!=="source_before_target"&&e.precedence!=="target_before_source")throw new TypeError(`Invalid relationship precedence for ${t}`);if(!e.ordering&&e.precedence!==void 0)throw new TypeError(`Non-ordering relationship kind cannot declare precedence: ${t}`)}function tw(e,t){if(e.temporalOrder!==void 0&&e.temporalOrder!=="source_after_target")throw new TypeError(`Invalid relationship temporal order for ${t}`);if(e.direction!=="directed"&&e.temporalOrder!==void 0)throw new TypeError(`Undirected relationship kind cannot declare temporal order: ${t}`)}function nw(e,t){if(e.hierarchyDirection!==void 0&&e.hierarchyDirection!=="source_parent"&&e.hierarchyDirection!=="target_parent")throw new TypeError(`Invalid relationship hierarchy direction for ${t}`);if(!e.hierarchy&&e.hierarchyDirection!==void 0)throw new TypeError(`Non-hierarchy relationship kind cannot declare hierarchy direction: ${t}`)}function rw(e){if(typeof e!="object"||e===null)throw new TypeError("Relationship kind definition requires an object");if(typeof e.kind!="string")throw new TypeError("Relationship kind requires a string identifier");let t=Ao(e.kind);if(!/^[a-z][a-z0-9_]*$/.test(t))throw new TypeError(`Invalid relationship kind: ${e.kind}`);if(!Number.isInteger(e.compatibilityVersion)||e.compatibilityVersion<1)throw new TypeError(`Invalid compatibility version for ${t}`);return t}function ow(e,t){if(!["directed","undirected"].includes(e.direction))throw new TypeError(`Invalid relationship direction for ${t}`);if(typeof e.ordering!="boolean")throw new TypeError(`Invalid relationship ordering flag for ${t}`);if(![void 0,!0,!1].includes(e.hierarchy))throw new TypeError(`Invalid relationship hierarchy flag for ${t}`);if(!["one","many"].includes(e.outgoing))throw new TypeError(`Invalid outgoing relationship cardinality for ${t}`);if(!["one","many"].includes(e.incoming))throw new TypeError(`Invalid incoming relationship cardinality for ${t}`);if(!["persistent","supersedable","ephemeral"].includes(e.lifecycle))throw new TypeError(`Invalid relationship lifecycle for ${t}`);if(typeof e.allowSelf!="boolean")throw new TypeError(`Invalid relationship self-edge flag for ${t}`);if(e.traversal!==void 0&&!["hierarchy","ordering","semantic","association"].includes(e.traversal))throw new TypeError(`Invalid relationship traversal family for ${t}`);if(e.outcomeTraversal!==void 0&&!["source_to_target","target_to_source","both"].includes(e.outcomeTraversal))throw new TypeError(`Invalid outcome traversal for ${t}`);if(e.direction==="undirected"&&e.outcomeTraversal!==void 0&&e.outcomeTraversal!=="both")throw new TypeError(`Undirected relationship kind cannot declare directional outcome traversal: ${t}`)}function iw(e,t){if(e.payloadSchema!==void 0&&(typeof e.payloadSchema!="object"||e.payloadSchema===null||Array.isArray(e.payloadSchema)))throw new TypeError(`Invalid relationship payload schema for ${t}`);if(e.aliases!==void 0&&(!Array.isArray(e.aliases)||e.aliases.some(n=>typeof n!="string")))throw new TypeError(`Invalid relationship aliases for ${t}`)}function sw(e){return e.traversal?e.traversal:e.ordering?"ordering":e.hierarchy?"hierarchy":e.direction==="undirected"?"association":"semantic"}var zs=class{#e=new Map;#n=new Map;constructor(t=Ls){for(let n of t)this.register(n)}register(t){let n=rw(t);if(ow(t,n),iw(t,n),ew(t,n),tw(t,n),nw(t,n),this.#e.has(n)||this.#n.has(n))throw new TypeError(`Relationship kind already registered: ${n}`);let r=Qb(t.inverse),o=[...new Set((t.aliases??[]).map(Ao))].sort();for(let s of o){if(!/^[a-z][a-z0-9_]*$/.test(s))throw new TypeError(`Invalid relationship alias: ${s}`);if(s===n||this.#e.has(s)||this.#n.has(s))throw new TypeError(`Relationship alias already registered: ${s}`)}let i=Object.freeze({...t,kind:n,traversal:sw(t),hierarchy:t.hierarchy??!1,hierarchyDirection:t.hierarchy?t.hierarchyDirection??"source_parent":void 0,inverse:r,aliases:Object.freeze(o),payloadSchema:t.payloadSchema?Us(structuredClone(t.payloadSchema)):void 0});this.#e.set(n,i);for(let s of o)this.#n.set(s,n);return this}resolve(t){if(typeof t!="string")return;let n=Ao(t);return this.#e.get(this.#n.get(n)??n)}require(t){let n=this.resolve(t);if(!n)throw new TypeError(`Unknown relationship kind: ${t}`);return n}list(){return Object.freeze([...this.#e.values()].sort((t,n)=>t.kind.localeCompare(n.kind)))}};function Hs(){return new zs}var vt=Hs();function dD(e){return vt.require(e).kind}function lD(e){return vt.resolve(e)?.kind}function uD(e,t=vt){return t.resolve(e)?.ordering===!0}function aw(e,t,n,r=vt){let o=er(e),i=er(t);if(!o||!i)throw new TypeError("Relationship endpoint must not be empty");let s=r.require(n);if(o===i&&!s.allowSelf)throw new TypeError(`Self relationship is not allowed for ${s.kind}`);return s}function So(e,t){return e.source.localeCompare(t.source)||e.target.localeCompare(t.target)||e.kind.localeCompare(t.kind)}function cw(e,t,n){let r=typeof e.source=="string"?e.source.trim():"",o=typeof e.target=="string"?e.target.trim():"";if(!t.has(r)||!t.has(o))throw new TypeError(`Relationship endpoint not found: ${r} -> ${o}`);let i=aw(r,o,e.kind,n),s=Object.freeze({...e,source:r,target:o,kind:i.kind}),a=i.direction==="undirected"?[r,o].sort().join("\0"):`${r}\0${o}`;return{edge:s,identity:`${i.kind}\0${a}`}}function Oo(e,t,n){let r=e.get(t);r?r.push(n):e.set(t,[n])}function er(e){return typeof e=="string"?e.trim():""}function Fs(e,t){let n=er(e);return n&&t.has(n)?n:void 0}function dw(e,t,n){let r=[t],o=t;for(;o!==e;)o=n.get(o),r.push(o);return r.reverse()}var Wl=class e{#e;#n;#o;#r;#s=new Map;#a=new Map;constructor(t,n,r=vt){this.#e=r,this.#n=new Set([...t].filter(i=>typeof i=="string").map(i=>i.trim()).filter(Boolean)),this.#o=Object.freeze([...this.#n].sort());let o=new Map;for(let i of n){let{edge:s,identity:a}=cw(i,this.#n,r);o.set(a,s)}this.#r=Object.freeze([...o.values()].sort(So));for(let i of this.#r)Oo(this.#s,i.source,i),Oo(this.#a,i.target,i),r.require(i.kind).direction==="undirected"&&(Oo(this.#s,i.target,i),Oo(this.#a,i.source,i))}static fromItems(t,n=vt){let r=new Set(t.map(i=>er(i.id)).filter(Boolean)),o=[];for(let i of t){let s=er(i.id);if(!s)continue;let a=Fs(i.parent,r);a&&o.push({source:s,target:a,kind:"parent"});let c=Fs(i.blocked_by,r);c&&o.push({source:s,target:c,kind:"blocked_by"});for(let d of i.dependencies??[]){let l=Fs(d.id,r);l&&n.resolve(d.kind)&&o.push({source:s,target:l,kind:d.kind,createdAt:d.created_at,author:d.author})}}return new e(r,o,n)}edges(){return this.#r}incidentEdges(t){this.#i(t);let n=this.#s.get(t)??[],r=this.#a.get(t)??[];if(n.length===0)return Object.freeze([...r]);if(r.length===0)return Object.freeze([...n]);let o=[],i=0,s=0;for(;i<n.length||s<r.length;){let a=n[i],c=r[s],d=a===void 0?c:c===void 0||So(a,c)<=0?a:c;o.at(-1)!==d&&o.push(d),a===d&&(i+=1),c===d&&(s+=1)}return Object.freeze(o)}nodes(){return this.#o}hasNode(t){return this.#n.has(t)}registry(){return this.#e}#i(t){if(!this.#n.has(t))throw new TypeError(`Relationship node not found: ${t}`)}#c(t,n){if(!n)return!0;let r=this.#e.require(t.kind);return n.has(t.kind)||r.inverse!==void 0&&n.has(r.inverse)}#t(t,n,r){let o=[...n==="incoming"?[]:this.#s.get(t)??[],...n==="outgoing"?[]:this.#a.get(t)??[]];return[...new Set(o)].filter(i=>this.#c(i,r)).map(i=>({id:i.source===t?i.target:i.source,edge:i})).sort((i,s)=>i.id.localeCompare(s.id)||So(i.edge,s.edge))}adjacency(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=[...new Set(o.map(c=>c.id))],a=s.slice(0,i);return{value:a,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:a.length<s.length,nextCursor:a.at(-1)}}}neighborEdges(t,n={}){this.#i(t),n.signal?.throwIfAborted();let r=n.kinds?new Set(n.kinds.map(a=>this.#e.require(a).kind)):void 0,o=this.#t(t,n.direction??"outgoing",r),i=n.limit??Number.POSITIVE_INFINITY,s=o.slice(0,i);return{value:s,meta:{visitedNodes:1,inspectedEdges:o.length,truncated:s.length<o.length,nextCursor:s.at(-1)?.id}}}closure(t,n={}){this.#i(t);let r=n.kinds?new Set(n.kinds.map(m=>this.#e.require(m).kind)):void 0,o=n.direction??"outgoing",i=n.limit??Number.POSITIVE_INFINITY,s=n.maxDepth??Number.POSITIVE_INFINITY,a=new Set([t]),c=[],d=[{id:t,depth:0}],l=0,u=0,f=!1;e:for(let m=0;m<d.length;m+=1){n.signal?.throwIfAborted();let _=d[m];l+=1;let y=this.#t(_.id,o,r);if(u+=y.length,_.depth>=s){y.some(b=>!a.has(b.id))&&(f=!0);continue}for(let b of y)if(!a.has(b.id)){if(c.length>=i){f=!0;break e}a.add(b.id),c.push(b.id),d.push({id:b.id,depth:_.depth+1})}}return{value:c,meta:{visitedNodes:l,inspectedEdges:u,truncated:f,nextCursor:c.at(-1)}}}shortestPath(t,n,r={}){if(this.#i(t),this.#i(n),t===n)return{value:[t],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}};let o=r.kinds?new Set(r.kinds.map(m=>this.#e.require(m).kind)):void 0,i=r.direction??"outgoing",s=r.maxDepth??Number.POSITIVE_INFINITY,a=[{id:t,depth:0}],c=new Map,d=new Set([t]),l=0,u=0,f=!1;for(let m=0;m<a.length;m+=1){r.signal?.throwIfAborted();let _=a[m];l+=1;let y=this.#t(_.id,i,o);if(u+=y.length,_.depth>=s){y.some(b=>!d.has(b.id))&&(f=!0);continue}for(let b of y)if(!d.has(b.id)){if(c.set(b.id,_.id),b.id===n)return{value:dw(t,n,c),meta:{visitedNodes:l,inspectedEdges:u,truncated:!1}};d.add(b.id),a.push({id:b.id,depth:_.depth+1})}}return{value:[],meta:{visitedNodes:l,inspectedEdges:u,truncated:f}}}subgraph(t,n={}){let r=this.closure(t,n),o=[t,...r.value].sort(),i=new Set(o),s=n.kinds?new Set(n.kinds.map(c=>this.#e.require(c).kind)):void 0,a=new Set;for(let c of o)for(let d of this.#s.get(c)??[])i.has(d.source)&&i.has(d.target)&&this.#c(d,s)&&a.add(d);return{value:{nodes:o,edges:[...a].sort(So)},meta:r.meta}}};function fD(e,t,n=vt){return{source:e,target:t.id,kind:n.require(t.kind).kind,createdAt:t.created_at,author:t.author}}(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]="32aa20df-edf7-543d-b733-841130466f00")}catch{}})();var lw="__pm_suppress_host_output",qs="@unbrained/pm-cli:suppress-host-output:v1";function Gl(e){return e===void 0?{__pm_suppress_host_output:qs}:{__pm_suppress_host_output:qs,result:e}}function Io(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)&&e[lw]===qs}import fn from"node:fs";import Fe from"node:path";import{fileURLToPath as uw}from"node:url";(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]="efea1aa1-1ad1-5f53-a3a5-b83803d9deb1")}catch{}})();var fw="@unbrained/pm-cli";function mw(e){try{return JSON.parse(fn.readFileSync(e,"utf8")).name===fw}catch{return!1}}function pw(e){let t=fn.existsSync(e)&&fn.statSync(e).isDirectory()?Fe.resolve(e):Fe.dirname(Fe.resolve(e));for(;;){let n=Fe.join(t,"package.json");if(fn.existsSync(n)&&mw(n))return t;let r=Fe.dirname(t);if(r===t)return;t=r}}function To(e,t=[]){let n=uw(e);return pw(n)||Fe.resolve(Fe.dirname(n),...t)}function gD(e,t=[]){try{let n=Fe.join(To(e,t),"package.json");if(!fn.existsSync(n))return;let r=JSON.parse(fn.readFileSync(n,"utf8"));return typeof r.version=="string"&&r.version.trim().length>0?r.version:void 0}catch{return}}function bD(e=process.env,t="PM_CLI_PACKAGE_ROOT",n,r=[]){let o=e[t];return typeof o=="string"&&o.trim().length>0?Fe.resolve(o.trim()):n?To(n,r):process.cwd()}(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]="447bb510-051a-5dce-8b7d-e27f4ca781f4")}catch{}})();var Co={include:"--output-include",amount:"--output-limit",cost:"--output-budget",encoding:"--output-format"},Ro=Object.freeze(["--output-session","--output-cursor","--output-row-contract"]),Et=["list","context","search","get","next","health","deps","graph","history","activity","validate","events","contracts","comments","notes","learnings","files","docs","stats","aggregate","duplicates","package-catalog","package-manage","comments-audit","assurance"];(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]="f8657910-1392-5fae-afda-614b96dc8320")}catch{}})();function U(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function _w(){return{json:!1,quiet:!1,noExtensions:!1,profile:!1}}function pe(e){return e?P(e):{}}function _e(e){return e?P(e):_w()}function P(e){return structuredClone(e)}(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]="615b4955-a30d-5d45-a86d-4bcf7bd9bd7a")}catch{}})();var yw=new Set(["commands","command_overrides","command_handlers","flag_commands","parser_overrides"]),hw=["commands","command_overrides","command_handlers","hooks","flag_commands","item_types","item_fields","relationship_kinds","migrations","profiles","importers","exporters","search_providers","vector_store_adapters","assurance_providers","parser_overrides","service_overrides","renderer_overrides"];function gw(e,t){for(let n of hw){let r=e[n];if(r===void 0)continue;if(!Array.isArray(r)||r.some(i=>typeof i!="string"))return!1;let o=r.map(i=>yw.has(n)?U(i):i.trim()).filter(i=>i.length>0);t[n]=[...new Set(o)].sort((i,s)=>i.localeCompare(s))}return!0}function bw(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n;if(r.format!=="json"&&r.format!=="toon"||!Array.isArray(r.commands)||r.commands.some(o=>typeof o!="string")||typeof r.result_discriminator!="boolean")return null;t.push({format:r.format,commands:[...new Set(r.commands.map(o=>U(o)))].sort((o,i)=>o.localeCompare(i)),result_discriminator:r.result_discriminator})}return t.sort((n,r)=>n.format.localeCompare(r.format))}function ww(e){if(!Array.isArray(e))return null;let t=[];for(let n of e){if(typeof n!="object"||n===null)return null;let r=n.commands;if(!Array.isArray(r)||r.some(o=>typeof o!="string"))return null;t.push({commands:[...new Set(r.map(o=>U(o)))].filter(o=>o.length>0).sort((o,i)=>o.localeCompare(i))})}return t}function xo(e){if(e==null)return;if(typeof e!="object"||Array.isArray(e))return null;let t=e;if(t.schema_version!==1)return null;let n={schema_version:1};if(!gw(t,n))return null;let r=t.preflight_overrides;if(r!==void 0&&(!Number.isInteger(r)||r<0))return null;typeof r=="number"&&(n.preflight_overrides=r);let o=t.renderer_ownership;if(o!==void 0){let s=bw(o);if(s===null)return null;n.renderer_ownership=s}let i=t.preflight_ownership;if(i!==void 0){let s=ww(i);if(s===null)return null;n.preflight_ownership=s}return n}function SD(e){return{schema_version:1,commands:e.commands,command_overrides:e.command_overrides,command_handlers:e.command_handlers,hooks:e.hooks,flag_commands:e.flag_commands,item_types:e.item_types,item_fields:e.item_fields,...e.relationship_kinds?{relationship_kinds:e.relationship_kinds}:{},migrations:e.migrations,profiles:e.profiles,importers:e.importers,exporters:e.exporters,search_providers:e.search_providers,vector_store_adapters:e.vector_store_adapters,...e.assurance_providers?{assurance_providers:e.assurance_providers}:{},parser_overrides:e.parser_overrides,service_overrides:e.service_overrides,renderer_overrides:e.renderer_overrides,...e.renderer_ownership?{renderer_ownership:e.renderer_ownership}:{},preflight_overrides:e.preflight_overrides,...e.preflight_ownership?{preflight_ownership:e.preflight_ownership}:{}}}(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]="7359c10a-4c56-57ea-8254-fc26b19e5c84")}catch{}})();function tr(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function Ge(e){return $e.includes(e)}function Kl(e){let t=e.trim().toLowerCase();return Ge(t)?t:null}function Yl(e){return e.filter(t=>!Ge(t))}function Vs(e){let t=e.trim().toLowerCase();return t.length===0?null:Wd[t]??null}function Xl(e){let t=tr([...e].map(i=>i.toLowerCase())),n=[],r=[];for(let i of t){let s=Vs(i);if(s){n.push(s),r.push({alias:i,target:s});continue}n.push(i)}let o=[...new Map(r.map(i=>[`${i.alias}>${i.target}`,i])).values()].sort((i,s)=>i.alias.localeCompare(s.alias));return{capabilities:tr(n),legacy_aliases:o}}function vw(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Vs(t);if(n)return n;let r=Math.max(1,Math.floor(t.length*.34)),o=null,i=Number.POSITIVE_INFINITY;for(let s of $e){let a=ko(t,s,r);a!==null&&a<i&&(i=a,o=s)}return o}function Jl(e,t,n){let r=$e.join(","),o=vw(n)??"none";return`extension_capability_unknown:${e}:${t}:${n}:allowed=${r}:suggested=${o}`}function Zl(e,t,n){let r=n.map(o=>`${o.alias}>${o.target}`).join(",");return`extension_capability_legacy_alias:${e}:${t}:aliases=${r}`}function Ew(e){let t=/^extension_capability_unknown:(global|project):([^:]+):([^:]+):allowed=([^:]+):suggested=([^:]+)$/.exec(e.trim());if(!t)return null;let[,n,r,o,i,s]=t,a=n,c=i.split(",").map(u=>u.trim()).filter(u=>u.length>0),d=Vs(o),l=(s==="none"?void 0:s)??d??void 0;return{layer:a,name:r,capability:o,allowed_capabilities:c,capability_contract_version:_s,suggested_capability:l,suggestion_source:l?d===l?"legacy_alias":"nearest_match":void 0,legacy_alias_target:d??void 0}}function kw(e){let t=/^extension_capability_legacy_alias:(global|project):([^:]+):aliases=(.+)$/.exec(e.trim());if(!t)return[];let[,n,r,o]=t,i=n,s=[...$e],a=[];for(let c of o.split(",")){let[d,l]=c.split(">"),u=d?.trim(),f=l?.trim().toLowerCase();!u||!f||!Ge(f)||a.push({layer:i,name:r,capability:u,allowed_capabilities:s,capability_contract_version:_s,suggested_capability:f,suggestion_source:"legacy_alias",legacy_alias_target:f})}return a}(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]="01116a5e-62d1-591b-9fd0-84ac6e99f8d0")}catch{}})();function nr(){return{beforeCommand:[],beforeMutation:[],afterCommand:[],onWrite:[],onRead:[],onIndex:[]}}function Bs(){return{overrides:[],handlers:[]}}function Ws(){return{overrides:[]}}function Gs(){return{overrides:[]}}function Ks(){return{overrides:[]}}function Ys(){return{overrides:[]}}function Xs(){return{commands:[],flags:[],item_fields:[],item_types:[],relationship_kinds:[],migrations:[],profiles:[],importers:[],exporters:[],search_providers:[],vector_store_adapters:[],assurance_providers:[]}}(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]="67511565-01f8-58a6-ad06-45b5d0ce831b")}catch{}})();var Sw=new Set(["name","version","entry","priority","description","author","capabilities","manifest_version","pm_min_version","pm_max_version","engines","trusted","provenance","sandbox_profile","permissions","activation","contributions","legacy_capability_aliases"]);function Ow(e){return{unknownKeys:Object.keys(e).filter(t=>!Sw.has(t)).sort((t,n)=>t>n?1:-1),missingVersionBounds:e.pm_min_version===void 0&&e.pm_max_version===void 0}}function Aw(e){let t=Ow(e),n=t.unknownKeys.map(r=>({code:"manifest_unknown_key",path:r,...r==="compatibility"?{suggested_key:"pm_min_version"}:{},message:r==="compatibility"?'Manifest key "compatibility" is ignored; declare the canonical pm_min_version and optional pm_max_version fields instead.':`Manifest key "${r}" is not part of the extension manifest contract and will be ignored.`}));return t.missingVersionBounds&&n.push({code:"no_version_bounds_declared",path:"$",suggested_key:"pm_min_version",message:"No canonical pm version bounds are declared; add pm_min_version so compatibility intent is explicit."}),{ok:n.length===0,findings:n}}function Ql(e,t,n){return Aw(n).findings.map(r=>r.code==="manifest_unknown_key"?`extension_manifest_unknown_key:${e}:${t.name}:key=${r.path}${r.suggested_key?`:suggested=${r.suggested_key}`:""}`:`extension_manifest_no_version_bounds:${e}:${t.name}:suggested=pm_min_version`)}import{constants as Ke}from"node:os";(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]="151124a3-cefa-55d3-bf4f-bd8f2553ad72")}catch{}})();var eu=new Map([["EACCES",{summary:"was denied filesystem permission",recovery:"Grant the required filesystem access, then retry.",category:"permission"}],["EDQUOT",{summary:"exceeded the filesystem quota",recovery:"Raise or reclaim the filesystem quota, then retry.",category:"capacity"}],["EMFILE",{summary:"exhausted the process file-descriptor limit",recovery:"Close unused file handles or raise the process limit, then retry.",category:"resource"}],["ENFILE",{summary:"exhausted the host file-descriptor limit",recovery:"Free host file descriptors or raise the host limit, then retry.",category:"resource"}],["ENOMEM",{summary:"ran out of available memory",recovery:"Free memory or reduce concurrent work, then retry.",category:"resource"}],["ENOSPC",{summary:"ran out of storage space",recovery:"Free storage on the filesystem holding the project, then retry.",category:"capacity"}],["EPERM",{summary:"was denied by the host permission policy",recovery:"Grant the required filesystem permission, then retry.",category:"permission"}],["EROFS",{summary:"targeted a read-only filesystem",recovery:"Use a writable project filesystem or remount it read-write, then retry.",category:"permission"}]]),Iw=/^[a-z][a-z0-9_]{0,63}$/u,Tw=new Map([[Ke.errno.EACCES,"EACCES"],[Ke.errno.EDQUOT,"EDQUOT"],[Ke.errno.EMFILE,"EMFILE"],[Ke.errno.ENFILE,"ENFILE"],[Ke.errno.ENOMEM,"ENOMEM"],[Ke.errno.ENOSPC,"ENOSPC"],[Ke.errno.EPERM,"EPERM"],[Ke.errno.EROFS,"EROFS"]].filter(([e])=>Number.isInteger(e))),Cw={capacity:{code:"host_environment_capacity_fault"},permission:{code:"host_environment_permission_fault"},resource:{code:"host_environment_resource_fault"}};function Rw(e){if(typeof e!="object"||e===null)return null;let t=e;return typeof t.code=="string"&&eu.has(t.code)?t.code:typeof t.errno!="number"||!Number.isInteger(t.errno)?null:Tw.get(Math.abs(t.errno))??null}function xw(e,t,n={}){let r=Rw(e);if(r===null)return null;if(!Iw.test(t))throw new g("Host environment operation labels must be bounded identifiers.",h.USAGE,{code:"host_environment_operation_invalid",field:"operation"});let o=eu.get(r);return new g(`Host filesystem operation ${t} ${o.summary}.`,h.GENERIC_FAILURE,{code:n.codes?.[o.category]??Cw[o.category].code,reason:r,required:o.recovery,why:n.why??"The operating system refused a required project filesystem operation.",nextSteps:[o.recovery,...n.nextSteps??[]],...n.suggestedRetry?{recovery:{suggested_retry:n.suggestedRetry}}:{}})}async function tu(e,t,n={}){try{return await t()}catch(r){throw xw(r,e,n)??r}}(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]="4a7b042c-7fb8-57a5-8f94-de44f82d7589")}catch{}})();function Nw(e){return e.trim().toLowerCase().replace(/\s+/g," ")}function Ee(e,t){let n=e.slice(0,t),r=n.charCodeAt(n.length-1),o=e.charCodeAt(n.length);return r>=55296&&r<=56319&&o>=56320&&o<=57343?n.slice(0,-1):n}function MD(e){return Nw(e).split(/[^a-z0-9]+/).filter(t=>t.length>0)}function $D(e,t){if(e.length===0&&t.length===0)return 1;if(e.length===0||t.length===0)return 0;let n=new Set(e),r=new Set(t),o=0;for(let s of n)r.has(s)&&(o+=1);let i=new Set([...n,...r]).size;return o/i}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f49bad80-c246-59b3-950d-7143585fbdb5")}catch{}})();var Dw=5e3;async function rr(e,t,n){let r=[];for(let o of e)try{await o.run(P(n))}catch{r.push(`extension_hook_failed:${o.layer}:${o.name}:${t}`)}return r}async function Pw(e,t){return rr(e.beforeCommand,"beforeCommand",t)}function Mw(e,t,n){if(e===void 0)return;if(typeof e!="object"||e===null||!("allow"in e)||e.allow!==!0&&e.allow!==!1)throw new g(`Extension mutation guard ${t.name} returned an invalid decision.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_decision",reason:`${t.layer}:${t.name}`,nextSteps:["Return { allow: true } or a structured denial from the guard."]});if(e.allow)return;let r=e,o=typeof r.code=="string"?r.code.trim():"",i=typeof r.remediation=="string"?r.remediation.trim():"";if(o.length===0||i.length===0)throw new g(`Extension mutation guard ${t.name} returned an invalid denial.`,h.CONFLICT,{code:"extension_mutation_guard_invalid_denial",reason:`${t.layer}:${t.name}`,nextSteps:["Return non-empty code and remediation fields from the guard."]});let s=typeof r.message=="string"?r.message.trim():"";throw new g(s||`Extension mutation guard ${t.name} denied ${n}.`,h.CONFLICT,{code:o,reason:`${t.layer}:${t.name}`,nextSteps:[i]})}async function Js(e,t){for(let n of e.beforeMutation??[]){let r,o;try{let i=Promise.resolve().then(()=>n.run({pm_root:t.pm_root,operation:t.operation,before:t.before===null?null:P(t.before),after:t.after===null?null:P(t.after),changed_fields:[...t.changed_fields],sdk:t.sdk}));i.catch(()=>{}),r=await Promise.race([i,new Promise((s,a)=>{o=setTimeout(()=>{a(new g(`Extension mutation guard ${n.name} timed out before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_timed_out",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the stalled extension guard, then retry the mutation."]}))},Dw),o.unref?.()})])}catch(i){throw i instanceof g?i:new g(`Extension mutation guard ${n.name} failed before ${t.operation}.`,h.CONFLICT,{code:"extension_mutation_guard_failed",reason:`${n.layer}:${n.name}`,nextSteps:["Fix or disable the failing extension guard, then retry the mutation."]})}finally{clearTimeout(o)}Mw(r,n,t.operation)}}async function $w(e,t){return rr(e.afterCommand,"afterCommand",t)}async function Zs(e,t){return rr(e.onWrite,"onWrite",t)}async function Qs(e,t){return rr(e.onRead,"onRead",t)}async function ea(e,t){return rr(e.onIndex,"onIndex",t)}function jw(e){let t="";e instanceof Error&&typeof e.message=="string"?t=e.message:typeof e=="string"?t=e:typeof e=="object"&&e!==null&&typeof e.message=="string"&&(t=e.message);let n=t.replace(/\s+/gu," ").trim();if(n.length===0)return"";let r=300;return n.length>r?`${Ee(n,r-1)}\u2026`:n}function No(e,t){if(typeof e!="object"||e===null||typeof e[t]!="string")return;let n=String(e[t]).replace(/\s+/gu," ").trim();return n.length>0?Ee(n,300):void 0}function Lw(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"exit_code"))return;let t=e.exit_code;if(typeof t!="number"||!Number.isInteger(t)||t<1||t>255)throw new TypeError("Extension command result exit_code must be an integer from 1 to 255.");return t}async function ta(e,t){let n=U(t.command);if(n.length===0)return{handled:!1,result:null,warnings:[]};let r=[...e.handlers].reverse().find(o=>o.command===n);if(!r)return{handled:!1,result:null,warnings:[]};try{let o=await r.run({command:n,args:P(t.args),options:P(t.options),global:P(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,...t.sdk===void 0?{}:{sdk:t.sdk}});return{handled:!0,result:o,warnings:[],...Object.fromEntries([["exitCode",Lw(o)],["errorCode",No(o,"code")],["remediation",No(o,"remediation")]].filter(i=>i[1]!==void 0))}}catch(o){let i=typeof o=="object"&&o!==null&&"exitCode"in o?o.exitCode:void 0;if(typeof i=="number"&&Number.isFinite(i))throw o;return Object.defineProperty({handled:!1,result:null,warnings:[`extension_command_handler_failed:${r.layer}:${r.name}:${r.command}`],errorMessage:jw(o),...Object.fromEntries([["errorCode",No(o,"code")],["remediation",No(o,"remediation")]].filter(s=>s[1]!==void 0))},"cause",{value:o,configurable:!0})}}async function na(e,t){let n=U(t.command);if(n.length===0)return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]};try{let o=await Promise.resolve(r.run({command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel}))??{},i=Array.isArray(o.args)?P(o.args):P(t.args),s=o.options?pe(o.options):pe(t.options),a=o.global?_e(o.global):_e(t.global);return{overridden:!0,context:{command:n,args:i,options:s,global:a,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[]}}catch{return{overridden:!1,context:{command:n,args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},warnings:[`extension_parser_override_failed:${r.layer}:${r.name}:${r.command}`]}}}async function ra(e,t){let n={command:U(t.command),args:P(t.args),options:pe(t.options),global:_e(t.global),pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel},r=P(t.decision),o=[...e.overrides].reverse().find(i=>!i.commands?.length||i.commands.includes(n.command));if(!o)return{overridden:!1,context:n,decision:r,warnings:[]};try{let i=await Promise.resolve(o.run({command:n.command,args:P(n.args),options:pe(n.options),global:_e(n.global),pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel,decision:P(r)}))??{},s={command:n.command,args:Array.isArray(i.args)?P(i.args):n.args,options:i.options?pe(i.options):n.options,global:i.global?_e(i.global):n.global,pm_root:n.pm_root,source_workspace_root:n.source_workspace_root,repo_root:n.repo_root,pm_root_rel:n.pm_root_rel},a={enforce_item_format_gate:typeof i.enforce_item_format_gate=="boolean"?i.enforce_item_format_gate:r.enforce_item_format_gate,run_preflight_item_format_sync:typeof i.run_preflight_item_format_sync=="boolean"?i.run_preflight_item_format_sync:r.run_preflight_item_format_sync,run_extension_migrations:typeof i.run_extension_migrations=="boolean"?i.run_extension_migrations:r.run_extension_migrations,enforce_mandatory_migration_gate:typeof i.enforce_mandatory_migration_gate=="boolean"?i.enforce_mandatory_migration_gate:r.enforce_mandatory_migration_gate};return{overridden:!0,context:s,decision:a,warnings:[]}}catch{return{overridden:!1,context:n,decision:r,warnings:[`extension_preflight_override_failed:${o.layer}:${o.name}`]}}}function nu(e){return{handled:!1,result:e.payload,warnings:[]}}function ru(e,t){return[...e.overrides].reverse().filter(n=>n.service===t)}function ou(e){return{service:e.service,command:e.command?U(e.command):void 0,args:e.args?P(e.args):void 0,options:e.options?pe(e.options):void 0,global:e.global?_e(e.global):void 0,pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,payload:P(e.payload)}}function Fw(e){if(typeof e!="object"||e===null||!Object.hasOwn(e,"handled"))return!1;let t=e.handled;return t===!0?Object.hasOwn(e,"result"):t===!1&&Reflect.ownKeys(e).length===1}function iu(e,t){return Fw(e)?e.handled?{handled:!0,result:e.result}:{handled:!1,result:t.payload}:t.service==="output_format"&&e==null?{handled:!1,result:t.payload}:{handled:!0,result:e}}function su(e,t,n){return t.service==="output_format"&&typeof e=="object"&&e!==null&&B(e,n.payload)}function au(e,t,n){if(t.handled){if(e.passThrough===!0){n.push(`extension_service_pass_through_contract_violated:${e.layer}:${e.name}:${e.service}`);return}return{handled:!0,result:t.result,warnings:n}}}function oa(e,t){let n=ru(e,t.service);if(n.length===0)return nu(t);let r=[];for(let o of n)try{let i=ou(t),s=o.run(i);if(s instanceof Promise){r.push(`extension_service_override_async_unsupported:${o.layer}:${o.name}:${o.service}`);continue}if(su(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=au(o,iu(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}async function ia(e,t){let n=ru(e,t.service);if(n.length===0)return nu(t);let r=[];for(let o of n)try{let i=ou(t),s=await Promise.resolve(o.run(i));if(su(s,t,i)){r.push(`extension_output_format_payload_echo_deprecated:${o.layer}:${o.name}`);continue}let a=au(o,iu(s,t),r);if(a)return a}catch{r.push(`extension_service_override_failed:${o.layer}:${o.name}:${o.service}`)}return{handled:!1,result:t.payload,warnings:r}}function sa(e,t){let n=U(t.command);if(n.length===0)return{overridden:!1,result:t.result,warnings:[]};let r=[...e.overrides].reverse().find(o=>o.command===n);if(!r)return{overridden:!1,result:t.result,warnings:[]};try{let o=pe(t.options),i=_e(t.global),s=r.run({command:n,args:P(t.args),options:o,global:i,pm_root:t.pm_root,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:P(t.result)});return s instanceof Promise?{overridden:!1,result:t.result,warnings:[`extension_command_override_async_unsupported:${r.layer}:${r.name}:${r.command}`]}:{overridden:!0,result:s,warnings:[]}}catch{return{overridden:!1,result:t.result,warnings:[`extension_command_override_failed:${r.layer}:${r.name}:${r.command}`]}}}function Uw(e,t,n){if((e.commands?.length??0)>0&&!e.commands?.includes(t))return!1;if(e.resultDiscriminator===void 0)return!0;try{return e.resultDiscriminator(P(n))}catch{return!1}}function aa(e,t){let n=typeof t.command=="string"?U(t.command):"",r=[...e.overrides].reverse().find(o=>o.format===t.format&&Uw(o,n,t.result));if(!r)return{overridden:!1,rendered:null,warnings:[]};try{let o=Array.isArray(t.args)?P(t.args):[],i=pe(t.options),s=_e(t.global),a=typeof t.pm_root=="string"?t.pm_root:"",c=r.run({format:t.format,command:n,args:o,options:i,global:s,pm_root:a,source_workspace_root:t.source_workspace_root,repo_root:t.repo_root,pm_root_rel:t.pm_root_rel,result:P(t.result)});return c==null?{overridden:!1,rendered:null,warnings:[]}:typeof c!="string"?{overridden:!1,rendered:null,warnings:[`extension_renderer_invalid_result:${r.layer}:${r.name}:${r.format}`]}:{overridden:!0,rendered:c,warnings:[]}}catch{return{overridden:!1,rendered:null,warnings:[`extension_renderer_failed:${r.layer}:${r.name}:${r.format}`]}}}import It from"node:fs/promises";import At from"node:path";import{pathToFileURL as Ev}from"node:url";(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]="559b05dc-0290-5a7c-97b9-ef1e5e8670ba")}catch{}})();function cu(e){let t={beforeCommand:e.hooks.beforeCommand.length,beforeMutation:e.hooks.beforeMutation.length,afterCommand:e.hooks.afterCommand.length,onWrite:e.hooks.onWrite.length,onRead:e.hooks.onRead.length,onIndex:e.hooks.onIndex.length,commandOverrides:e.commands.overrides.length,commandHandlers:e.commands.handlers.length,parserOverrides:e.parsers.overrides.length,preflightOverrides:e.preflight.overrides.length,serviceOverrides:e.services.overrides.length,rendererOverrides:e.renderers.overrides.length,registrations:Object.fromEntries(Object.entries(e.registrations).map(([n,r])=>[n,r.length]))};return()=>{e.hooks.beforeCommand.length=t.beforeCommand,e.hooks.beforeMutation.length=t.beforeMutation,e.hooks.afterCommand.length=t.afterCommand,e.hooks.onWrite.length=t.onWrite,e.hooks.onRead.length=t.onRead,e.hooks.onIndex.length=t.onIndex,e.commands.overrides.length=t.commandOverrides,e.commands.handlers.length=t.commandHandlers,e.parsers.overrides.length=t.parserOverrides,e.preflight.overrides.length=t.preflightOverrides,e.services.overrides.length=t.serviceOverrides,e.renderers.overrides.length=t.rendererOverrides;for(let[n,r]of Object.entries(t.registrations))e.registrations[n].length=r}}(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]="17ae377d-20c2-5e45-825a-48a79c6c7601")}catch{}})();function K(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return t}function ee(e,t){if(t!==void 0&&typeof t!="boolean")throw new TypeError(`${e} must be a boolean when provided`)}function V(e,t){if(t!==void 0&&(typeof t!="string"||t.trim().length===0))throw new TypeError(`${e} must be a non-empty string when provided`)}function du(e,t){if(t===void 0)return;let n=r=>typeof r=="string"||typeof r=="number"||typeof r=="boolean";if(Array.isArray(t)){for(let[r,o]of t.entries())if(!n(o))throw new TypeError(`${e}[${r}] must be a string, number, or boolean`);return}if(!n(t))throw new TypeError(`${e} must be a string, number, or boolean, or an array of these when provided`)}function kt(e,t){if(t!==void 0){if(!Array.isArray(t))throw new TypeError(`${e} must be an array of non-empty strings when provided`);for(let[n,r]of t.entries())if(typeof r!="string"||r.trim().length===0)throw new TypeError(`${e}[${n}] must be a non-empty string`)}}function or(e,t){if(kt(e,t),!Array.isArray(t))return[];let n=[],r=new Set;for(let o of t){let i=o.trim();i.length===0||r.has(i)||(r.add(i),n.push(i))}return n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="34536eba-0f92-5599-a807-5b39b000e733")}catch{}})();var ca=Object.freeze(["workspace","intake","context","lifecycle","evidence","graph","quality","automation","extensions","internal"]);(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]="60fd882d-7c92-5be5-bf46-7e3c128bfb58")}catch{}})();var zw=new Set(ca);function Hw(e){if(e!==void 0&&!zw.has(String(e)))throw new Error(`registerCommand definition.family must be one of: ${ca.join(", ")}`)}function lu(e){V("registerCommand definition.action",e.action),V("registerCommand definition.family",e.family),V("registerCommand definition.description",e.description),V("registerCommand definition.intent",e.intent),V("registerCommand definition.tier",e.tier);let t=e.tier;if(t!==void 0&&t!=="core"&&t!=="standard"&&t!=="full"&&t!=="internal")throw new Error("registerCommand definition.tier must be core, standard, full, or internal");Hw(e.family)}(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]="095ea29d-eda3-5287-b54d-8a961658f7bc")}catch{}})();function uu(e,t="",n=""){if(e===void 0)return;if(mn(t)||mn(n))throw new TypeError("Native pm commands and actions cannot declare read_output");let r=K("registerCommand definition.read_output",e);if(Object.keys(r).some(s=>s!=="row_keys")||!Array.isArray(r.row_keys))throw new TypeError("registerCommand definition.read_output requires only row_keys: string[]");let o=Array.from(r.row_keys),i=new Set(["__proto__","constructor","prototype","row_contract","read_output","read_session","omission_receipt","output_budget_truncation"]);if(o.some(s=>typeof s!="string"||!/^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*$/u.test(s)||s.split(".").some(a=>i.has(a))))throw new TypeError("registerCommand definition.read_output row_keys must be safe dot-delimited property paths");if(new Set(o).size!==o.length||o.some(s=>o.some(a=>a.startsWith(`${s}.`))))throw new TypeError("registerCommand definition.read_output row_keys must be unique and non-overlapping");return Object.freeze({row_keys:Object.freeze([...o])})}function mn(e){let t=e.trim().toLowerCase().replace(/\s+/gu,"-");return sn.includes(t)||Et.includes(t)}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="07cb237c-3956-5997-85f8-972d2ee490d0")}catch{}})();function qw(e){let t=K("registerExporter options.output",e),n=new Set(["channel","receipt","media_type"]);for(let r of Object.keys(t))if(!n.has(r))throw new TypeError(`registerExporter options.output contains unsupported field ${r}`);if(t.channel!=="stdout"&&t.channel!=="file")throw new TypeError("registerExporter options.output.channel must be stdout|file");if(t.receipt!==void 0&&t.receipt!=="suppress"&&t.receipt!=="render")throw new TypeError("registerExporter options.output.receipt must be suppress|render");if(t.channel==="stdout"&&t.receipt==="render")throw new TypeError("registerExporter stdout artifacts cannot render a host receipt");return V("registerExporter options.output.media_type",t.media_type),{channel:t.channel,receipt:t.receipt??(t.channel==="stdout"?"suppress":"render"),...typeof t.media_type=="string"?{media_type:t.media_type}:{}}}function fu(e,t,n){if(e==="registerImporter"&&t.output!==void 0)throw new TypeError("registerImporter options.output is exporter-only");if(e!=="registerExporter"||t.output===void 0)return;let r=qw(t.output);return!n&&r.channel==="stdout"&&(t.description="Export items with the registered extension adapter. Artifact bytes are written exclusively to stdout and the host receipt is suppressed by default."),r}function da(e,t,n){return{registration:t,action:n,command:e.command,args:P(e.args),options:P(e.options),global:P(e.global),pm_root:e.pm_root,source_workspace_root:e.source_workspace_root,repo_root:e.repo_root,pm_root_rel:e.pm_root_rel,...e.sdk===void 0?{}:{sdk:e.sdk}}}(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]="fc2e7eac-cd1c-5885-aa27-e98455008a4f")}catch{}})();function mu(e){return!e.extensionReady||!e.enabledForLoad?null:{layer:e.layer,directory:e.directory,manifest_path:e.manifestPath,entry_path:e.entryPath,manifest:e.manifest,source_package:e.sourceIdentity?.package_name,source_aliases:e.sourceIdentity?.aliases,contributions:e.sourceIdentity?.contributions}}(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]="bb1b4879-079c-50d4-afa5-e8a36ead2e5c")}catch{}})();function we(e){return typeof e!="string"?"":e.trim().toLowerCase()}function M(e){return new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))}function Vw(e){let t=e.trim().toLowerCase();if(t.length===0)return"";let n=t.split(/[.:/]/).map(r=>r.replace(/[\s_-]+/g,"")).filter(r=>r.length>0);return n.length===0?"":n.length===1?n[0]:`${n[0]}.${n.slice(1).join("")}`}function pn(e){return new Set((e??[]).map(t=>Vw(t)).filter(t=>t.length>0))}function pu(e){let t=we(e);return Yr.includes(t)?t:"off"}function _u(e){let t=we(e);return Xr.includes(t)?t:"off"}function ir(e){let t=we(e);return Jr.includes(t)?t:"none"}function la(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();return Gd.includes(t)?t:void 0}function yu(e){if(typeof e=="string"){let t=la(e)??"block";return{global:t,project:t}}return typeof e=="object"&&e!==null&&!Array.isArray(e)?{global:la(e.global)??"block",project:la(e.project)??"block"}:{global:"block",project:"block"}}function Bw(e){return e.global===e.project?e.global:{global:e.global,project:e.project}}function L(e){return[...new Set(e)].sort((t,n)=>t.localeCompare(n))}function Ww(e){let t=we(e.name);return t.length===0?null:{name:t,normalized:{name:t,disabled:e.disabled===!0,requireTrusted:e.require_trusted===!0,requireProvenance:e.require_provenance===!0,sandboxProfile:e.sandbox_profile!==void 0?ir(e.sandbox_profile):void 0,allowedCapabilities:M(e.allowed_capabilities),blockedCapabilities:M(e.blocked_capabilities),allowedSurfaces:pn(e.allowed_surfaces),blockedSurfaces:pn(e.blocked_surfaces),allowedCommands:M(e.allowed_commands),blockedCommands:M(e.blocked_commands),allowedActions:M(e.allowed_actions),blockedActions:M(e.blocked_actions),allowedServices:M(e.allowed_services),blockedServices:M(e.blocked_services)}}}function hu(e){let t=new Map;for(let n of e??[]){let r=Ww(n);r&&t.set(r.name,r.normalized)}return t}function Gw(e){let t=[],n=[...e.overridesByName.values()].sort((o,i)=>o.name.localeCompare(i.name));for(let o of L([...e.allowedCapabilities,...e.blockedCapabilities]))Ge(o)||t.push(`extension_policy_unknown_capability:${o}`);for(let o of n)for(let i of L([...o.allowedCapabilities,...o.blockedCapabilities]))Ge(i)||t.push(`extension_policy_unknown_capability:${o.name}:${i}`);let r=new Set(Zr);for(let o of L([...e.allowedSurfaces,...e.blockedSurfaces]))r.has(o)||t.push(`extension_policy_unknown_surface:${o}`);for(let o of n)for(let i of L([...o.allowedSurfaces,...o.blockedSurfaces]))r.has(i)||t.push(`extension_policy_unknown_surface:${o.name}:${i}`);return[...new Set(t)].sort((o,i)=>o.localeCompare(i))}function gu(e){let t=e.extensions?.policy??{},n=M(t.allowed_capabilities),r=M(t.blocked_capabilities),o=pn(t.allowed_surfaces),i=pn(t.blocked_surfaces),s=hu(t.extension_overrides);return{mode:pu(t.mode),trustMode:_u(t.trust_mode),pmMaxVersionExceededMode:yu(t.pm_max_version_exceeded_mode),requireProvenance:t.require_provenance===!0,trustedExtensions:M(t.trusted_extensions),defaultSandboxProfile:ir(t.default_sandbox_profile),allowedExtensions:M(t.allowed_extensions),blockedExtensions:M(t.blocked_extensions),allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,allowedCommands:M(t.allowed_commands),blockedCommands:M(t.blocked_commands),allowedActions:M(t.allowed_actions),blockedActions:M(t.blocked_actions),allowedServices:M(t.allowed_services),blockedServices:M(t.blocked_services),overridesByName:s,warnings:Gw({allowedCapabilities:n,blockedCapabilities:r,allowedSurfaces:o,blockedSurfaces:i,overridesByName:s})}}function bu(e){let t=[...e.overridesByName.values()].sort((n,r)=>n.name.localeCompare(r.name)).map(n=>({name:n.name,...n.disabled?{disabled:!0}:{},...n.requireTrusted?{require_trusted:!0}:{},...n.requireProvenance?{require_provenance:!0}:{},...n.sandboxProfile?{sandbox_profile:n.sandboxProfile}:{},...n.allowedCapabilities.size>0?{allowed_capabilities:L(n.allowedCapabilities)}:{},...n.blockedCapabilities.size>0?{blocked_capabilities:L(n.blockedCapabilities)}:{},...n.allowedSurfaces.size>0?{allowed_surfaces:L(n.allowedSurfaces)}:{},...n.blockedSurfaces.size>0?{blocked_surfaces:L(n.blockedSurfaces)}:{},...n.allowedCommands.size>0?{allowed_commands:L(n.allowedCommands)}:{},...n.blockedCommands.size>0?{blocked_commands:L(n.blockedCommands)}:{},...n.allowedActions.size>0?{allowed_actions:L(n.allowedActions)}:{},...n.blockedActions.size>0?{blocked_actions:L(n.blockedActions)}:{},...n.allowedServices.size>0?{allowed_services:L(n.allowedServices)}:{},...n.blockedServices.size>0?{blocked_services:L(n.blockedServices)}:{}}));return{mode:e.mode,trust_mode:e.trustMode,pm_max_version_exceeded_mode:Bw(e.pmMaxVersionExceededMode),require_provenance:e.requireProvenance,trusted_extensions:L(e.trustedExtensions),default_sandbox_profile:e.defaultSandboxProfile,allowed_extensions:L(e.allowedExtensions),blocked_extensions:L(e.blockedExtensions),allowed_capabilities:L(e.allowedCapabilities),blocked_capabilities:L(e.blockedCapabilities),allowed_surfaces:L(e.allowedSurfaces),blocked_surfaces:L(e.blockedSurfaces),allowed_commands:L(e.allowedCommands),blocked_commands:L(e.blockedCommands),allowed_actions:L(e.allowedActions),blocked_actions:L(e.blockedActions),allowed_services:L(e.allowedServices),blocked_services:L(e.blockedServices),extension_overrides:t}}function wu(e){let t=hu(e.extension_overrides);return{mode:pu(e.mode),trustMode:_u(e.trust_mode),pmMaxVersionExceededMode:yu(e.pm_max_version_exceeded_mode),requireProvenance:e.require_provenance===!0,trustedExtensions:M(e.trusted_extensions),defaultSandboxProfile:ir(e.default_sandbox_profile),allowedExtensions:M(e.allowed_extensions),blockedExtensions:M(e.blocked_extensions),allowedCapabilities:M(e.allowed_capabilities),blockedCapabilities:M(e.blocked_capabilities),allowedSurfaces:pn(e.allowed_surfaces),blockedSurfaces:pn(e.blocked_surfaces),allowedCommands:M(e.allowed_commands),blockedCommands:M(e.blocked_commands),allowedActions:M(e.allowed_actions),blockedActions:M(e.blocked_actions),allowedServices:M(e.allowed_services),blockedServices:M(e.blocked_services),overridesByName:t,warnings:[]}}function Ye(e,t){return e.overridesByName.get(we(t))??null}function _n(e,t,n,r,o){return t.has(n)?o:e.size>0&&!e.has(n)?r:null}function vu(e,t,n){let r=n.trim().toLowerCase(),o=Ye(e,t.name),i=o&&o.allowedCapabilities.size>0?o.allowedCapabilities:e.allowedCapabilities,s=new Set([...e.blockedCapabilities,...o?o.blockedCapabilities:[]]);return _n(i,s,r,"capability_not_allowlisted","capability_blocked")}function Kw(e,t,n){let r=Ye(e,t.name),o=r&&r.allowedSurfaces.size>0?r.allowedSurfaces:e.allowedSurfaces,i=new Set([...e.blockedSurfaces,...r?r.blockedSurfaces:[]]);return _n(o,i,n,"surface_not_allowlisted","surface_blocked")}function Yw(e,t,n){let r=U(n);if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedCommands.size>0?o.allowedCommands:e.allowedCommands,s=new Set([...e.blockedCommands,...o?o.blockedCommands:[]]);return _n(i,s,r,"command_not_allowlisted","command_blocked")}function Xw(e,t,n){let r=we(n).replace(/\s+/g,"-");if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedActions.size>0?o.allowedActions:e.allowedActions,s=new Set([...e.blockedActions,...o?o.blockedActions:[]]);return _n(i,s,r,"action_not_allowlisted","action_blocked")}function Jw(e,t,n){let r=we(n);if(r.length===0)return null;let o=Ye(e,t.name),i=o&&o.allowedServices.size>0?o.allowedServices:e.allowedServices,s=new Set([...e.blockedServices,...o?o.blockedServices:[]]);return _n(i,s,r,"service_not_allowlisted","service_blocked")}function Zw(e,t){let n=we(t.name);return Ye(e,t.name)?.disabled===!0?"extension_override_disabled":_n(e.allowedExtensions,e.blockedExtensions,n,"extension_not_allowlisted","extension_blocked")}function Qw(e,t){if(e.trustMode==="off")return null;let n=Ye(e,t.name),r=we(t.name),o=t.trusted===!0,i=t.provenanceVerified===!0;return e.trustedExtensions.size>0&&!e.trustedExtensions.has(r)?"extension_not_trusted":(n?.requireTrusted===!0||e.trustMode==="warn"||e.trustMode==="enforce")&&!o?"extension_untrusted":(e.requireProvenance||n?.requireProvenance===!0)&&!i?"provenance_missing_or_unverified":null}function ev(e,t){if(e.mode==="off")return null;let n=Ye(e,t.name)?.sandboxProfile??t.sandboxProfile??e.defaultSandboxProfile;if(n==="none")return null;let r=t.permissions;if(!r)return"sandbox_permissions_missing";let o=i=>r[i]===!0;return n==="restricted"?o("process_spawn")?"sandbox_restricted_disallows_process_spawn":o("env_write")?"sandbox_restricted_disallows_env_write":null:o("process_spawn")?"sandbox_strict_disallows_process_spawn":o("network")?"sandbox_strict_disallows_network":o("fs_write")?"sandbox_strict_disallows_fs_write":o("env_write")?"sandbox_strict_disallows_env_write":null}function Do(e,t,n,r,o={}){let i=Object.entries(o).sort((a,c)=>a[0].localeCompare(c[0])).map(([a,c])=>`${a}=${c}`).join(":"),s=i.length>0?`:${i}`:"";return`extension_policy_${e}_${t}:${n.layer}:${n.name}:reason=${r}${s}`}function Eu(e,t){if(e.mode==="off"&&e.trustMode==="off")return{allowed:!0,warning:null};let n=[],r=Zw(e,t);r&&n.push({reason:r,scope:"extension",mode:e.mode});let o=Qw(e,t);o&&n.push({reason:o,scope:"trust",mode:e.trustMode});let i=ev(e,t);i&&n.push({reason:i,scope:"extension",mode:e.mode});let s=n.find(c=>c.mode==="enforce");if(s)return{allowed:!1,warning:Do("blocked",s.scope,t,s.reason)};let a=n.find(c=>c.mode==="warn");return a?{allowed:!0,warning:Do("violation",a.scope,t,a.reason)}:{allowed:!0,warning:null}}function ku(e,t,n){if(e.mode==="off")return{allowed:!0,warning:null};let r=vu(e,t,n);return r?{allowed:e.mode==="warn",warning:Do(e.mode==="warn"?"violation":"blocked","capability",t,r,{capability:n.trim().toLowerCase()})}:{allowed:!0,warning:null}}function tv(e,t,n,r,o){let i=typeof r=="string"?vu(e,t,r):null,s=Kw(e,t,n),a=o.command?Yw(e,t,o.command):null,c=o.action?Xw(e,t,o.action):null,d=o.service?Jw(e,t,o.service):null;return i??s??a??c??d}function nv(e,t,n,r){let o={method:we(e).replace(/\s+/g,"_"),surface:t};return n&&(o.capability=n),r.command&&(o.command=U(r.command)),r.action&&(o.action=we(r.action).replace(/\s+/g,"-")),r.service&&(o.service=we(r.service)),o}function Su(e,t,n,r,o,i){if(e.mode==="off")return{allowed:!0,warning:null};let s=i??{},a=tv(e,t,n,o,s);if(!a)return{allowed:!0,warning:null};let c=Do(e.mode==="warn"?"violation":"blocked","registration",t,a,nv(r,n,o,s));return{allowed:e.mode==="warn",warning:c}}(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]="cd1de600-27e4-522b-842e-1993c12e9f0e")}catch{}})();var Au=100;function Ou(e,t){let n=e[t];if(n!=null)return typeof n!="string"||n.trim().length===0?null:n.trim()}function rv(e){if(e==null)return;let t=We(e);if(!t)return null;let n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i))){if(r.trim().length===0)return null;let o=t[r];if(typeof o!="string"||o.trim().length===0)return null;n[r.trim()]=o.trim()}return Object.keys(n).length>0?n:void 0}function ua(e,t){let n=e[t];return typeof n!="string"||n.trim().length===0?null:n.trim()}function Iu(e){if(e!=null)return typeof e!="number"||!Number.isInteger(e)?null:e}function St(e){if(e!=null)return typeof e!="boolean"?null:e}function ov(e){let t=Iu(e.priority);return t===void 0?Au:t}function iv(e){let t=e.sandbox_profile;if(t==null)return;if(typeof t!="string")return null;let n=ir(t);return n!==t.trim().toLowerCase()?null:n}function fa(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}function sv(e){if(e==null)return;let t=We(e);if(!t)return null;let n=fa(t.source),r=fa(t.signature),o=fa(t.attestation),i=t.verified===void 0||t.verified===null?void 0:typeof t.verified=="boolean"?t.verified:null;return i===null?null:{...n?{source:n}:{},...r?{signature:r}:{},...o?{attestation:o}:{},...typeof i=="boolean"?{verified:i}:{}}}function av(e){if(e==null)return;let t=We(e);if(!t)return null;let n=St(t.fs_read),r=St(t.fs_write),o=St(t.network),i=St(t.env_read),s=St(t.env_write),a=St(t.process_spawn);return[n,r,o,i,s,a].includes(null)?null:{...typeof n=="boolean"?{fs_read:n}:{},...typeof r=="boolean"?{fs_write:r}:{},...typeof o=="boolean"?{network:o}:{},...typeof i=="boolean"?{env_read:i}:{},...typeof s=="boolean"?{env_write:s}:{},...typeof a=="boolean"?{process_spawn:a}:{}}}function cv(e){if(e==null)return{capabilities:[],legacy_aliases:[]};if(!Array.isArray(e)||e.some(n=>typeof n!="string"))return null;let t=Xl(e);return{capabilities:t.capabilities,legacy_aliases:t.legacy_aliases}}function dv(e){if(e==null)return;let t=We(e);if(!t)return null;let n=t.commands;if(n==null)return;if(!Array.isArray(n)||n.some(o=>typeof o!="string"))return null;let r=[...new Set(n.map(o=>U(o)).filter(o=>o.length>0))].sort((o,i)=>o.localeCompare(i));return r.length>0?{commands:r}:void 0}function lv(e){let t=Iu(e.manifest_version);if(t===null)return null;let n=Ou(e,"pm_min_version");if(n===null)return null;let r=Ou(e,"pm_max_version");if(r===null)return null;let o=rv(e.engines);if(o===null)return null;let i=St(e.trusted);if(i===null)return null;let s=iv(e);if(s===null)return null;let a=sv(e.provenance);if(a===null)return null;let c=av(e.permissions);if(c===null)return null;let d=cv(e.capabilities);if(d===null)return null;let l=dv(e.activation);if(l===null)return null;let u=xo(e.contributions);return u===null?null:{manifest_version:t,pm_min_version:n,pm_max_version:r,engines:o,trusted:i,sandbox_profile:s,provenance:a,permissions:c,capabilities:d.capabilities,legacy_capability_aliases:d.legacy_aliases,activation:l,contributions:u}}function ma(e){if(typeof e!="object"||e===null)return null;let t=e,n=ua(t,"name");if(n===null)return null;let r=ua(t,"version");if(r===null)return null;let o=ua(t,"entry");if(o===null)return null;let i=ov(t);if(i===null)return null;let s=lv(t);return s===null?null:{name:n,version:r,entry:o,priority:i,manifest_version:s.manifest_version,pm_min_version:s.pm_min_version,pm_max_version:s.pm_max_version,engines:s.engines,trusted:s.trusted,provenance:s.provenance,sandbox_profile:s.sandbox_profile,permissions:s.permissions,activation:s.activation,contributions:s.contributions,capabilities:s.capabilities,legacy_capability_aliases:s.legacy_capability_aliases.length>0?s.legacy_capability_aliases:void 0}}import uv from"node:fs/promises";import sr 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]="029e0066-2ef5-5204-92ad-4866321710f4")}catch{}})();async function Tu(e,t){let n=sr.dirname(t.manifest_path),r=sr.relative(n,t.entry_path);if(r.startsWith("..")||sr.isAbsolute(r))throw new Error(`Cannot snapshot extension entry outside its package directory: ${t.entry_path}`);let o=sr.join(e,`${t.layer}-${t.directory.replace(/[^a-zA-Z0-9._-]/gu,"_")}`);return await tu("extension_module_graph_snapshot",()=>uv.cp(n,o,{recursive:!0,force:!0})),sr.join(o,r)}(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]="bf5c3834-b388-507e-a13c-3beb5d096abb")}catch{}})();function Cu(e){let t=typeof e=="function"?e:e.run;if(typeof t!="function")throw new TypeError("registerPreflight override requires a function handler");let n=[...new Set((typeof e=="function"?[]:e.commands??[]).map(r=>{if(typeof r!="string"||r.trim().length===0)throw new TypeError("registerPreflight ownership.commands must contain non-empty command paths");return U(r)}))];return{run:t,...n.length>0?{commands:n}:{}}}function Ru(e){let t=[];for(let n=1;n<e.overrides.length;n+=1){let r=e.overrides[n];for(let o of e.overrides.slice(0,n))r.commands?.length&&o.commands?.length&&!o.commands.some(i=>r.commands.includes(i))||t.push(`extension_preflight_override_collision:${r.layer}:${r.name}:${o.layer}:${o.name}`)}return t}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="47d10c23-88f8-5ba1-bcc2-458f339121a8")}catch{}})();var Po=cn;function xu(e){let t=e.trim().toLowerCase();return Po.includes(t)?t:null}function Nu(e){let t=e.trim().toLowerCase();if(t.length===0)return null;let n=Math.max(1,Math.floor(t.length*.34));for(let r of Po)if(ko(t,r,n)!==null)return r;return null}(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]="355fe619-e6f3-51d9-b88c-0b57267c25be")}catch{}})();function Du(e){return e==="toon"||e==="json"}function Pu(e){return on.includes(e)}function Ot(e,t){if(typeof t!="function")throw new TypeError(`api.hooks.${e} requires a function handler`)}var Mu=Symbol("extension_registration_trace");function Ue(e,t){let n=new TypeError(e);return Object.defineProperty(n,Mu,{value:t,enumerable:!1,configurable:!1,writable:!1}),n}function $u(e){return e instanceof Error?e[Mu]:void 0}function ar(e){if(e===null)return null;if(Array.isArray(e))return e.map(t=>ar(t));if(typeof e=="function")return"[Function]";if(typeof e=="bigint"||typeof e=="symbol")return e.toString();if(typeof e=="object"){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=ar(t[r]);return n}return e}function cr(e){if(Array.isArray(e))return e.map(t=>cr(t));if(typeof e=="object"&&e!==null){let t=e,n={};for(let r of Object.keys(t).sort((o,i)=>o.localeCompare(i)))n[r]=cr(t[r]);return n}return e}function yn(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return ar(t)}function dr(e,t){if(typeof t!="object"||t===null||Array.isArray(t))throw new TypeError(`${e} requires an object definition`);return cr(t)}function lr(e,t){if(!Array.isArray(t))throw new TypeError(`${e} requires an array of object definitions`);return t.map(n=>yn(e,n))}function oe(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function ur(e,t){if(typeof t!="function")throw new TypeError(`${e} requires a function handler`)}function pa(e){return e.trim().toLowerCase().split(/\s+/).filter(t=>t.length>0).join(" ")}function _a(e,t){return U(`${e} ${t}`)}function fr(e,t){return Object.defineProperty(e,"runtime_definition",{value:t,enumerable:!1,writable:!1,configurable:!1}),e}var fv=new Set(["low","medium","high"]),mv=new Set(["number","string_set"]),pv=new Set(["string","number","boolean"]);function ju(e,t){if(typeof t!="string"||t.trim().length===0)throw new TypeError(`${e} requires a non-empty string`);return t.trim()}function _v(e,t,n){let r=`registerAssuranceMeasurementProvider provider.keys.${t}`,o=K(r,n);if(!mv.has(String(o.value_type)))throw new TypeError(`${r}.value_type must be number or string_set`);if(V(`${r}.description`,o.description),o.parameters===void 0)return;let i=K(`${r}.parameters`,o.parameters);for(let[s,a]of Object.entries(i)){let c=`${r}.parameters.${s}`;ju(`${c}.name`,s);let d=K(c,a);if(!pv.has(String(d.type)))throw new TypeError(`${c}.type must be string, number, or boolean`);ee(`${c}.required`,d.required),V(`${c}.description`,d.description)}if(Object.keys(i).length>50)throw new TypeError(`assurance provider ${e} key ${t} exceeds 50 parameters`)}function Lu(e){let t=K("registerAssuranceMeasurementProvider provider",e),n=ju("registerAssuranceMeasurementProvider provider.id",t.id);if(!/^[a-z0-9][a-z0-9-]*$/u.test(n))throw new TypeError("registerAssuranceMeasurementProvider provider.id must be a stable lowercase id");if(!fv.has(String(t.cost_class)))throw new TypeError("registerAssuranceMeasurementProvider provider.cost_class must be low, medium, or high");if(typeof t.network!="boolean")throw new TypeError("registerAssuranceMeasurementProvider provider.network must be boolean");let r=K("registerAssuranceMeasurementProvider provider.keys",t.keys);if(Object.keys(r).length===0)throw new TypeError("registerAssuranceMeasurementProvider provider.keys requires at least one key");for(let[o,i]of Object.entries(r)){if(!/^[a-z0-9][a-z0-9-]*$/u.test(o))throw new TypeError(`registerAssuranceMeasurementProvider provider key ${o} must be a stable lowercase id`);_v(n,o,i)}if(t.timeout_ms!==void 0&&(typeof t.timeout_ms!="number"||!Number.isInteger(t.timeout_ms)||t.timeout_ms<1||t.timeout_ms>3e5))throw new TypeError("registerAssuranceMeasurementProvider provider.timeout_ms must be an integer from 1 through 300000");if(typeof t.resolve!="function")throw new TypeError("registerAssuranceMeasurementProvider provider.resolve requires a function handler")}(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]="4abca948-e9ba-52b5-b63c-a20fc344980a")}catch{}})();var yv=new Set(["default","description","enabled","list","long","repeatable","required","short","type","value_name","value_type","value_validation","visible"]);function Mo(e,t){return lr(e,t).map(n=>(n.repeatable===!0&&(n.list=!0),n))}function hv(e){return e.trim().toLowerCase().replace(/[\s_]+/g,"-").replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")}function ya(e,t){if(t===void 0)return e.replace(/\s+/g,"-");if(typeof t!="string"||t.trim().length===0)throw new TypeError("registerCommand definition.action must be a non-empty string when provided");let n=hv(t);if(n.length===0)throw new TypeError("registerCommand definition.action must contain alphanumeric characters");return n}function ha(e){if(e===void 0)return[];if(!Array.isArray(e))throw new TypeError("registerCommand definition.arguments must be an array when provided");let t=[];for(let[r,o]of e.entries()){let i=K(`registerCommand definition.arguments[${r}]`,o),s=oe(`registerCommand definition.arguments[${r}].name`,i.name);if(ee(`registerCommand definition.arguments[${r}].required`,i.required),ee(`registerCommand definition.arguments[${r}].variadic`,i.variadic),V(`registerCommand definition.arguments[${r}].description`,i.description),s.includes(" "))throw new TypeError(`registerCommand definition.arguments[${r}].name must not contain spaces`);let a={name:s};i.required===!0&&(a.required=!0),i.variadic===!0&&(a.variadic=!0),typeof i.description=="string"&&(a.description=i.description.trim()),t.push(a)}let n=t.map((r,o)=>r.variadic?o:-1).filter(r=>r>=0);if(n.length>1)throw new TypeError("registerCommand definition.arguments supports at most one variadic argument");if(n.length===1&&n[0]!==t.length-1)throw new TypeError("registerCommand definition.arguments variadic argument must be the final argument");return t}function $o(e){if(!Array.isArray(e))throw new TypeError("registerFlags flags requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerFlags flags[${t}]`,n),o=Object.keys(r).filter(c=>!yv.has(c)).sort((c,d)=>c.localeCompare(d));if(o.length>0)throw new TypeError(`registerFlags flags[${t}] contains unknown field(s): ${o.join(", ")}`);let i=r.long,s=r.short;if(i===void 0&&s===void 0)throw new TypeError(`registerFlags flags[${t}] requires at least one of long or short`);V(`registerFlags flags[${t}].long`,i),V(`registerFlags flags[${t}].short`,s);let a=Ml(i,s);if(a!==null)throw new TypeError(`registerFlags flags[${t}] ${$l(a.token,a.failure)}`);if(V(`registerFlags flags[${t}].value_name`,r.value_name),V(`registerFlags flags[${t}].description`,r.description),ee(`registerFlags flags[${t}].required`,r.required),ee(`registerFlags flags[${t}].enabled`,r.enabled),ee(`registerFlags flags[${t}].visible`,r.visible),ee(`registerFlags flags[${t}].list`,r.list),ee(`registerFlags flags[${t}].repeatable`,r.repeatable),r.list!==void 0&&r.repeatable!==void 0&&r.list!==r.repeatable)throw new TypeError(`registerFlags flags[${t}].list and repeatable must match when both are provided`);if(du(`registerFlags flags[${t}].default`,r.default),Array.isArray(r.default)&&r.list!==!0&&r.repeatable!==!0)throw new TypeError(`registerFlags flags[${t}].default cannot be an array unless list is true.`);Fu(`registerFlags flags[${t}]`,r),gv(`registerFlags flags[${t}]`,r)}}function gv(e,t){if(t.value_validation===void 0)return;if(t.value_validation!=="coerce"&&t.value_validation!=="strict")throw new TypeError(`${e}.value_validation must be "coerce" or "strict" (received ${JSON.stringify(t.value_validation)}).`);if(t.value_validation!=="strict")return;let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0),r=n===void 0?null:Eo(n);if(r!=="number"&&r!=="boolean")throw new TypeError(`${e}.value_validation "strict" requires value_type "number" or "boolean" (string values are never malformed).`)}function Fu(e,t){let n=(typeof t.value_type=="string"?t.value_type:void 0)??(typeof t.type=="string"?t.type:void 0);if(n===void 0)return;let r=Eo(n);if(r===null)throw new TypeError(`${e} value_type "${n}" is not a known flag value type (expected one of: string, number, boolean).`);if(t.default===void 0)return;let o=t.list===!0||t.repeatable===!0?Vl(t.default):[t.default];for(let[i,s]of o.entries())if(!Bl(s,r)){let a=o.length>1?`default[${i}]`:"default";throw new TypeError(`${e}.${a} (${JSON.stringify(s)}) is not coercible to ${r}.`)}}function Uu(e){if(!Array.isArray(e))throw new TypeError("registerItemFields fields requires an array of object definitions");for(let[t,n]of e.entries()){let r=K(`registerItemFields fields[${t}]`,n);oe(`registerItemFields fields[${t}].name`,r.name);let o=oe(`registerItemFields fields[${t}].type`,r.type);if(xu(o)===null){let i=Nu(o),s=i?` Did you mean "${i}"?`:"";throw new TypeError(`registerItemFields fields[${t}].type "${o}" is not a known field type (expected one of: ${Po.join(", ")}).${s}`)}ee(`registerItemFields fields[${t}].optional`,r.optional)}}function bv(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].command_option_policies`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.command`,s.command),oe(`${i}.option`,s.option),ee(`${i}.enabled`,s.enabled),ee(`${i}.required`,s.required),ee(`${i}.visible`,s.visible)}}function wv(e,t){if(t===void 0)return;let n=`registerItemTypes types[${e}].options`;if(!Array.isArray(t))throw new TypeError(`${n} must be an array when provided`);for(let[r,o]of t.entries()){let i=`${n}[${r}]`,s=K(i,o);oe(`${i}.key`,s.key),kt(`${i}.values`,s.values),ee(`${i}.required`,s.required),kt(`${i}.aliases`,s.aliases)}}function zu(e){if(!Array.isArray(e))throw new TypeError("registerItemTypes types requires an array of object definitions");for(let[t,n]of e.entries()){let r=`registerItemTypes types[${t}]`,o=K(r,n);oe(`${r}.name`,o.name),V(`${r}.folder`,o.folder),kt(`${r}.aliases`,o.aliases),kt(`${r}.required_create_fields`,o.required_create_fields),kt(`${r}.required_create_repeatables`,o.required_create_repeatables),bv(t,o.command_option_policies),wv(t,o.options)}}function Hu(e){let t=K("registerMigration definition",e);if(t.id!==void 0&&typeof t.id!="string")throw new TypeError("registerMigration definition.id must be a string when provided");if(t.description!==void 0&&typeof t.description!="string")throw new TypeError("registerMigration definition.description must be a string when provided");if(t.status!==void 0&&typeof t.status!="string")throw new TypeError("registerMigration definition.status must be a string when provided");if(ee("registerMigration definition.mandatory",t.mandatory),t.run!==void 0&&typeof t.run!="function")throw new TypeError("registerMigration definition.run must be a function when provided")}var qu=["types","statuses","fields","workflows","config","templates","packages"],vv={types:(e,t)=>{if(t.name!==void 0&&typeof t.name!="string")throw new TypeError(`${e}.name must be a string when provided`)},workflows:(e,t)=>{if(typeof t.type!="string")throw new TypeError(`${e}.type must be a string`);if(!Array.isArray(t.allowed_transitions))throw new TypeError(`${e}.allowed_transitions must be an array`);for(let[n,r]of t.allowed_transitions.entries())if(!Array.isArray(r))throw new TypeError(`${e}.allowed_transitions[${n}] must be a [from, to] array`)},templates:(e,t)=>{if(typeof t.name!="string")throw new TypeError(`${e}.name must be a string`);if(typeof t.options!="object"||t.options===null||Array.isArray(t.options))throw new TypeError(`${e}.options must be an object`)},packages:(e,t)=>{if(typeof t.spec!="string")throw new TypeError(`${e}.spec must be a string`)}};function Vu(e){let t=K("registerProfile profile",e);if(oe("registerProfile profile.name",t.name),oe("registerProfile profile.title",t.title),t.summary!==void 0&&typeof t.summary!="string")throw new TypeError("registerProfile profile.summary must be a string when provided");for(let n of qu){let r=t[n];if(r!==void 0){if(!Array.isArray(r))throw new TypeError(`registerProfile profile.${n} must be an array when provided`);for(let[o,i]of r.entries()){if(typeof i!="object"||i===null||Array.isArray(i))throw new TypeError(`registerProfile profile.${n}[${o}] must be an object`);vv[n]?.(`registerProfile profile.${n}[${o}]`,i)}}}}function Bu(e){e.summary===void 0&&(e.summary="");for(let t of qu)e[t]===void 0&&(e[t]=[]);return e}(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]="45ff820c-32af-5bdb-a570-3059684129ce")}catch{}})();function Wu(e){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError("registerService ownership must be an object");if(Reflect.ownKeys(e).some(t=>t!=="passThrough"))throw new TypeError("registerService ownership supports only passThrough");if(e.passThrough!==void 0&&typeof e.passThrough!="boolean")throw new TypeError("registerService ownership.passThrough must be a boolean when provided");return e.passThrough===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="b5de5028-f981-599b-8d11-0fc7b07beda4")}catch{}})();function Gu(e){return typeof e=="string"?e:String(e)}function mr(e){let t=e.trim().replace(/^>=\s*/,"").replace(/^v/i,"").split(/[+-]/,1)[0];return/^\d+(?:[.-]\d+)*$/.test(t)?t.split(/[.-]/).map(n=>Number(n)):null}function ga(e,t){let n=mr(e),r=mr(t);if(!n||!r)return null;let o=Math.max(n.length,r.length);for(let i=0;i<o;i+=1){let s=n[i]??0,a=r[i]??0;if(s>a)return 1;if(s<a)return-1}return 0}function Ku(e,t){if(e==null)return{kind:"pm_min_version",status:"absent",allowed:!0,required:"",current:t};let n=Gu(e);if(typeof e!="string"||n.trim().length===0)return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(!mr(n))return{kind:"pm_min_version",status:"invalid",allowed:!1,required:n,current:t};if(t===null)return{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:null};let r=ga(t,n);return r===null?{kind:"pm_min_version",status:"unchecked",allowed:!0,required:n,current:t}:r<0?{kind:"pm_min_version",status:"unmet",allowed:!1,required:n,current:t}:{kind:"pm_min_version",status:"ok",allowed:!0,required:n,current:t}}function Yu(e,t,n){if(e==null)return{kind:"pm_max_version",status:"absent",allowed:!0,required:"",current:t};let r=Gu(e);if(typeof e!="string"||r.trim().length===0)return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(/^[<>=~^]/.test(r.trim())||!mr(r))return{kind:"pm_max_version",status:"invalid",allowed:!1,required:r,current:t};if(t===null)return{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:null};let o=ga(t,r);return o===null?{kind:"pm_max_version",status:"unchecked",allowed:!0,required:r,current:t}:o>0?n==="warn"?{kind:"pm_max_version",status:"exceeded_warn",allowed:!0,required:r,current:t}:{kind:"pm_max_version",status:"exceeded",allowed:!1,required:r,current:t}:{kind:"pm_max_version",status:"ok",allowed:!0,required:r,current:t}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3abe36f7-3c97-58d2-a56d-b4e0ea958461")}catch{}})();var Xu=null,kv=Object.freeze(Kd()),Ju=0;function Sv(e=Date.now()){return Ju+=1,`${Ju}-${e}`}function Ov(e,t,n){return n.has(e)?!1:t.size===0?!0:t.has(e)}async function Av(e,t){let[n,r]=await Promise.all([It.realpath(e),It.realpath(t)]);return Zn(n,r)}function Iv(e,t=process.cwd()){return{global:At.join(Ol(t),"extensions"),project:At.join(e,"extensions")}}async function Tv(e){try{return(await It.readdir(e,{withFileTypes:!0})).filter(t=>t.isDirectory()).map(t=>t.name).sort((t,n)=>t.localeCompare(n))}catch{return[]}}function Cv(e){let t={layer:e.layer,directory:e.directory,manifest_path:e.manifest_path,name:e.manifest.name,version:e.manifest.version,entry:e.manifest.entry,priority:e.manifest.priority,entry_path:e.entry_path,manifest_version:e.manifest.manifest_version,pm_min_version:e.manifest.pm_min_version,pm_max_version:e.manifest.pm_max_version,engines:e.manifest.engines,trusted:e.manifest.trusted,provenance:e.manifest.provenance,sandbox_profile:e.manifest.sandbox_profile,permissions:e.manifest.permissions,capabilities:[...e.manifest.capabilities],activation:e.manifest.activation?{commands:[...e.manifest.activation.commands]}:void 0,contributions:e.manifest.contributions??e.contributions};return e.source_package&&(t.source_package=e.source_package),e.source_aliases&&(t.source_aliases=[...e.source_aliases]),t}function Zu(e){return typeof e=="string"&&e.trim().length>0?e.trim():void 0}async function Rv(e){let t=new Map;try{let n=JSON.parse(await It.readFile(At.join(e,".managed-extensions.json"),"utf8")),r=We(n)?.entries;if(!Array.isArray(r))return t;for(let o of r){if(typeof o!="object"||o===null)continue;let i=o,s=Zu(i.source?.package),a=[i.source?.input,i.source?.name,s].map(l=>Zu(l)).filter(l=>l!==void 0),c=xo(i.contributions),d={aliases:[...new Set(a)],...s?{package_name:s}:{},...c?{contributions:c}:{}};typeof i.directory=="string"&&i.directory.trim().length>0&&t.set(`directory:${i.directory.trim()}`,d),typeof i.name=="string"&&i.name.trim().length>0&&t.set(`name:${i.name.trim()}`,d)}}catch{return t}return t}function Qu(e){return[...e].sort((t,n)=>{if(t.manifest.priority!==n.manifest.priority)return t.manifest.priority-n.manifest.priority;let r=t.manifest.name.localeCompare(n.manifest.name);return r!==0?r:t.directory.localeCompare(n.directory)})}function xv(e,t){let n=[...Qu(e),...Qu(t)],r=[];for(let o of n){let i=r.findIndex(s=>s.manifest.name===o.manifest.name);i>=0&&r.splice(i,1),r.push(o)}return r}async function ef(e,t,n,r,o){let i=[],s=[],a=[],c=await Tv(t),d=await Rv(t);for(let l of c){let u=await Pv(e,t,l,n,r,d,o);i.push(u.diagnostic),s.push(...u.warnings),u.candidate&&a.push(u.candidate)}return{diagnostics:i,warnings:s,candidates:a}}function Nv(){return{diagnostics:[],warnings:[],candidates:[]}}function tf(e,t,n,r){return{diagnostic:{layer:e,directory:t,manifest_path:n,name:null,version:null,entry:null,priority:null,entry_path:null,enabled:null,status:"warn"},warnings:[r],candidate:null}}function Dv(e,t,n,r,o,i,s,a){let c=Ql(e,t,n);Array.isArray(t.legacy_capability_aliases)&&t.legacy_capability_aliases.length>0&&c.push(Zl(e,t.name,t.legacy_capability_aliases));for(let d of Yl(t.capabilities))c.push(Jl(e,t.name,d));return r?o||c.push(`extension_entry_missing:${e}:${t.name}`):c.push(`extension_entry_outside_extension:${e}:${t.name}`),i.warning&&c.push(a?i.warning:i.warning.replace("extension_pm_","extension_disabled_pm_")),s.warning&&c.push(a?s.warning:s.warning.replace("extension_pm_","extension_disabled_pm_")),c}async function Pv(e,t,n,r,o,i,s){let a=At.join(t,n),c=At.join(a,"manifest.json");if(!await gt(c))return tf(e,n,c,`extension_manifest_missing:${e}:${n}`);let d,l;try{let de=JSON.parse(await It.readFile(c,"utf8"));l=We(de),d=ma(de)}catch{l=null,d=null}if(!d||!l)return tf(e,n,c,`extension_manifest_invalid:${e}:${n}`);let u=At.resolve(a,d.entry),f=Zn(a,u),m=f?await gt(u):!1,_=f&&m?await Av(a,u):f,y=Ov(d.name,r,o),b=await jv(e,d),v=await Lv(e,d,s),T=Dv(e,d,l,_,m,b,v,y),G=_&&m&&b.allowed&&v.allowed,ce=i.get(`directory:${n}`)??i.get(`name:${d.name}`);return{diagnostic:{layer:e,directory:n,manifest_path:c,name:d.name,version:d.version,entry:d.entry,priority:d.priority,entry_path:u,enabled:y,status:G?"ok":"warn"},warnings:T,candidate:mu({layer:e,directory:n,manifestPath:c,entryPath:u,manifest:d,sourceIdentity:ce,extensionReady:G,enabledForLoad:y})}}async function Mv(e){let t=Iv(e.pmRoot,e.cwd??process.cwd()),n=tr(e.settings.extensions.enabled),r=tr(e.settings.extensions.disabled),o=gu(e.settings),i=bu(o);if(e.noExtensions)return{disabled_by_flag:!0,roots:t,configured_enabled:n,configured_disabled:r,discovered:[],effective:[],warnings:[...o.warnings],policy:i};let s=new Set(n),a=new Set(r),c=e.ignoreGlobalExtensions===!0?Nv():await ef("global",t.global,s,a,o.pmMaxVersionExceededMode.global),d=await ef("project",t.project,s,a,o.pmMaxVersionExceededMode.project),l=[...o.warnings],u=xv(c.candidates,d.candidates),f=[];for(let m of u){let _={layer:m.layer,name:m.manifest.name,trusted:m.manifest.trusted===!0,provenanceVerified:m.manifest.provenance?.verified===!0,sandboxProfile:m.manifest.sandbox_profile,permissions:m.manifest.permissions&&typeof m.manifest.permissions=="object"?{fs_read:m.manifest.permissions.fs_read,fs_write:m.manifest.permissions.fs_write,network:m.manifest.permissions.network,env_read:m.manifest.permissions.env_read,env_write:m.manifest.permissions.env_write,process_spawn:m.manifest.permissions.process_spawn}:void 0},y=Eu(o,_);if(y.warning&&l.push(y.warning),!!y.allowed){for(let b of m.manifest.capabilities){let v=ku(o,_,b);v.warning&&l.push(v.warning)}f.push(Cv(m))}}return{disabled_by_flag:!1,roots:t,configured_enabled:n,configured_disabled:r,discovered:[...c.diagnostics,...d.diagnostics],effective:f,warnings:[...new Set([...c.warnings,...d.warnings,...l])],policy:i}}function jo(e){return e instanceof Error&&e.message.trim().length>0?e.message:String(e)}async function $v(){try{let e=To(import.meta.url,["../../.."]),t=await It.readFile(At.join(e,"package.json"),"utf8"),n=JSON.parse(t);return typeof n.version=="string"&&n.version.trim().length>0?n.version.trim():null}catch{return null}}function of(){return Xu??=$v(),Xu}function sf(e,t,n){let r=n.current??"unknown";if(n.kind==="pm_min_version")switch(n.status){case"invalid":return`extension_pm_min_version_invalid:${e}:${t.name}:required=${n.required}`;case"unchecked":return`extension_pm_min_version_unchecked:${e}:${t.name}:required=${n.required}:current=${r}`;case"unmet":return`extension_pm_min_version_unmet:${e}:${t.name}:required=${n.required}:current=${r}`;default:return}switch(n.status){case"invalid":return`extension_pm_max_version_invalid:${e}:${t.name}:allowed=${n.required}`;case"unchecked":return`extension_pm_max_version_unchecked:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded_warn":return`extension_pm_max_version_exceeded_warn:${e}:${t.name}:allowed=${n.required}:current=${r}`;case"exceeded":return`extension_pm_max_version_exceeded:${e}:${t.name}:allowed=${n.required}:current=${r}`;default:return}}async function jv(e,t){if(t.pm_min_version===void 0)return{allowed:!0};let n=Ku(t.pm_min_version,await of()),r=sf(e,t,n);return r?{allowed:n.allowed,warning:r}:{allowed:n.allowed}}async function Lv(e,t,n){if(t.pm_max_version===void 0)return{allowed:!0};let r=Yu(t.pm_max_version,await of(),n),o=sf(e,t,r);return o?{allowed:r.allowed,warning:o}:{allowed:r.allowed}}async function nf(e){try{let t=await It.stat(e);return`${Math.trunc(t.mtimeMs)}-${t.size}`}catch{return"missing"}}async function Fv(e,t){let n=e.entry_path;t.module_graph_snapshot_root&&(n=await Tu(t.module_graph_snapshot_root,e));let r=new URL(Ev(n).href);if(!(t.cache_bust===!0||typeof t.reload_token=="string"))return r.href;let[o,i]=await Promise.all([nf(e.entry_path),nf(e.manifest_path)]),s=t.reload_token??Sv();return r.searchParams.set("pm_ext_reload",s),r.searchParams.set("pm_ext_entry",o),r.searchParams.set("pm_ext_manifest",i),r.href}async function _1(e){let t=await Mv(e),n=[],r=[],o=[...t.warnings];if(t.disabled_by_flag)return{...t,warnings:o,loaded:n,failed:r};let i=typeof e.extensionFilter=="function"?t.effective.filter(e.extensionFilter):t.effective;for(let s of i)try{let a=await import(await Fv(s,e));n.push({...s,module:a})}catch(a){o.push(`extension_load_failed:${s.layer}:${s.name}`),r.push({layer:s.layer,name:s.name,entry_path:s.entry_path,error:jo(a)})}return{...t,warnings:o,loaded:n,failed:r}}var rf=5e3,Uv=2147483647;function zv(e){let t={activate:e.activate.bind(e)};if(typeof e.deactivate=="function"){let n=e.deactivate;t.deactivate=n.bind(e)}return t}function af(e){let t=Fl(e);return t?zv(t):null}async function y1(e,t,n={}){let r=Hv(n?.deactivate_timeout_ms),o=new Set((t?.failed??[]).map(l=>`${l.layer}:${l.name}`)),i=[];for(let l of e.loaded){if(o.has(`${l.layer}:${l.name}`))continue;let u=af(l.module);!u||typeof u.deactivate!="function"||i.push({extension:l,deactivate:u.deactivate})}let s=await Promise.all(i.map(async({extension:l,deactivate:u})=>{try{return await qv(u,r),{ok:!0}}catch(f){return{ok:!1,layer:l.layer,name:l.name,error:jo(f)}}})),a=[],c=[],d=0;for(let l of s){if(l.ok){d+=1;continue}a.push(`extension_deactivate_failed:${l.layer}:${l.name}`),c.push({layer:l.layer,name:l.name,error:l.error})}return{deactivated:d,warnings:a,failed:c}}function Hv(e){return typeof e!="number"||e<0?rf:e===0||e===1/0?0:Number.isFinite(e)?Math.min(Uv,Math.max(1,Math.floor(e))):rf}async function qv(e,t){if(t===0){await e();return}let n;try{let r=Promise.resolve().then(()=>e());r.catch(()=>{}),await Promise.race([r,new Promise((o,i)=>{n=setTimeout(()=>{i(new Error(`extension deactivate timed out after ${t}ms`))},t),n.unref?.()})])}finally{clearTimeout(n)}}function Vv(e){if(!Array.isArray(e.capabilities))return null;let t=new Set;for(let n of e.capabilities){let r=n.trim().toLowerCase();Ge(r)&&t.add(r)}return t}function H(e,t,n){let r=Vv(e);if(r!==null&&!r.has(t))throw Ue(`${n} requires capability '${t}' in extension manifest capabilities`,{method:n,registration_index:-1,capability:t,missing_capability:t,expected_schema:`"capabilities": [..., "${t}"]`,received:e.capabilities,hint:`Add "${t}" to ${e.name} manifest capabilities, or remove the ${n} registration call.`})}function Bv(e){return Object.freeze({name:e.name,layer:e.layer,version:e.version,capabilities:Object.freeze((e.capabilities??[]).filter(t=>$e.includes(t))),pm_min_version:e.pm_min_version,pm_max_version:e.pm_max_version,source_package:e.source_package})}function Wv(e){return{layer:e.layer,name:e.name,trusted:e.trusted===!0,provenanceVerified:e.provenance?.verified===!0,sandboxProfile:e.sandbox_profile,permissions:e.permissions&&typeof e.permissions=="object"?{fs_read:e.permissions.fs_read,fs_write:e.permissions.fs_write,network:e.permissions.network,env_read:e.permissions.env_read,env_write:e.permissions.env_write,process_spawn:e.permissions.process_spawn}:void 0}}var ba=class{extension;hooks;#e;#n;#o;#r;#s;#a;#i;#c;#t;#d;#l;#u;constructor(t,n,r,o,i,s,a,c,d,l,u){this.#e=t,this.extension=Bv(t),this.#n=Wv(t),this.#o=n,this.#r=r,this.#s=o,this.#a=i,this.#i=s,this.#c=a,this.#t=c,this.#d=d,this.#l=l,this.#u=u,this.registerCommand=this.registerCommand.bind(this),this.registerParser=this.registerParser.bind(this),this.registerPreflight=this.registerPreflight.bind(this),this.registerService=this.registerService.bind(this),this.registerFlags=this.registerFlags.bind(this),this.registerItemFields=this.registerItemFields.bind(this),this.registerItemTypes=this.registerItemTypes.bind(this),this.registerRelationshipKinds=this.registerRelationshipKinds.bind(this),this.registerMigration=this.registerMigration.bind(this),this.registerProfile=this.registerProfile.bind(this),this.registerRenderer=this.registerRenderer.bind(this),this.registerImporter=this.registerImporter.bind(this),this.registerExporter=this.registerExporter.bind(this),this.registerSearchProvider=this.registerSearchProvider.bind(this),this.registerVectorStoreAdapter=this.registerVectorStoreAdapter.bind(this),this.registerAssuranceMeasurementProvider=this.registerAssuranceMeasurementProvider.bind(this),this.hooks={beforeCommand:f=>this.registerBeforeCommand(f),beforeMutation:f=>this.registerBeforeMutation(f),afterCommand:f=>this.registerAfterCommand(f),onWrite:f=>this.registerOnWrite(f),onRead:f=>this.registerOnRead(f),onIndex:f=>this.registerOnIndex(f)}}allowRegistration(t,n,r,o){let i=Su(this.#u,this.#n,t,n,r,o);return i.warning&&this.#d.push(i.warning),i.allowed}registerCommandTrace(t,n,r,o,i){return{method:"registerCommand",registration_index:t==="override"?this.#r.overrides.length:this.#r.handlers.length,command:n,expected_schema:r,received:ar(o),hint:i}}registerCommandOverride(t,n){let r=U(t);if(r.length===0)throw Ue("registerCommand requires a non-empty command name",this.registerCommandTrace("override",t,'registerCommand("<command>", (context) => unknown)',t,"Provide a non-empty command path as the first argument."));if(typeof n!="function"){let o=this.registerCommandTrace("override",r,'registerCommand("<command>", (context) => unknown)',n,"Provide a function as the second registerCommand argument.");throw Ue(`registerCommand requires an override function when command name is provided (command="${r}", registration_index=${o.registration_index})`,o)}this.allowRegistration("commands.override","registerCommand","commands",{command:r})&&this.#r.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}resolveCommandDefinitionRunHandler(t,n){let r=typeof t.run=="function"?t.run:void 0,o=typeof t.handler=="function"?t.handler:void 0;return!r&&o&&this.#d.push(`extension_command_definition_legacy_handler_alias:${this.#e.layer}:${this.#e.name}:${n}`),r??o}registerCommandDefinition(t){if(typeof t!="object"||t===null)throw Ue("registerCommand requires a command definition object",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,'Use registerCommand({ name: "command path", run: (context) => ... }).'));if(typeof t.name!="string")throw Ue("registerCommand requires a command definition name",this.registerCommandTrace("definition",void 0,"{ name: string; run: (context) => unknown; }",t,"Set command definition.name to a non-empty string command path."));let n=U(t.name);if(n.length===0)throw Ue("registerCommand requires a non-empty command definition name",this.registerCommandTrace("definition",t.name,"{ name: string; run: (context) => unknown; }",t,"Ensure command definition.name contains a non-empty command path."));let r=this.resolveCommandDefinitionRunHandler(t,n);if(typeof r!="function"){let o=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; }",r,"Define command definition.run as a function.");throw Ue(`registerCommand requires a command definition run handler (command="${n}", registration_index=${o.registration_index})`,o)}try{lu(t);let o=ya(n,t.action),i=uu(t.read_output,n,o);if(!this.allowRegistration("commands.handler","registerCommand","commands",{command:n,action:o}))return;let s=t.description?.trim(),a=t.intent?.trim(),c=or("registerCommand definition.examples",t.examples),d=or("registerCommand definition.failure_hints",t.failure_hints),l=ha(t.arguments);t.flags!==void 0&&(H(this.#e,"schema","registerCommand flags"),this.allowRegistration("schema.flags","registerCommand flags","schema")&&($o(t.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Mo("registerCommand definition.flags",t.flags)})));let u={source_version:this.#e.version,read_output:i,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:o,examples:c,failure_hints:d,arguments:l,tier:t.tier??"standard",family:t.family??"extensions"};s&&(u.description=s),a&&(u.intent=a),this.#t.commands.push(u)}catch(o){let i=jo(o),s=this.registerCommandTrace("definition",n,"{ name: string; run: (context) => unknown; action?: string; arguments?: object[]; flags?: object[]; }",t,i),a=Ue(`registerCommand definition metadata invalid (command="${n}", registration_index=${s.registration_index}): ${i}`,s);this.#d.push(`extension_command_quarantined:${this.#e.layer}:${this.#e.name}:${n}`),this.#l.push({layer:this.#e.layer,name:this.#e.name,entry_path:this.#e.entry_path,error:a.message,trace:s});return}this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:n,run:r})}registerCommand(t,n){if(H(this.#e,"commands","registerCommand"),typeof t=="string"){this.registerCommandOverride(t,n);return}this.registerCommandDefinition(t)}registerParser(t,n){if(H(this.#e,"parser","registerParser"),!this.allowRegistration("parser.override","registerParser","parser"))return;let r=U(oe("registerParser command",t));ur("registerParser override",n),this.#s.overrides.push({layer:this.#e.layer,name:this.#e.name,command:r,run:n})}registerPreflight(t){if(H(this.#e,"preflight","registerPreflight"),!this.allowRegistration("preflight.override","registerPreflight","preflight"))return;let n=Cu(t);this.#a.overrides.push({layer:this.#e.layer,name:this.#e.name,...n})}registerService(t,n,r={}){H(this.#e,"services","registerService");let o=String(t).trim().toLowerCase();if(!Pu(o))throw new TypeError(`registerService service must be one of: ${on.join(", ")}`);this.allowRegistration("services.override","registerService","services",{service:o})&&(ur("registerService override",n),this.#i.overrides.push({layer:this.#e.layer,name:this.#e.name,service:o,run:n,...Wu(r)?{passThrough:!0}:{}}))}registerRenderer(t,n,r={}){if(H(this.#e,"renderers","registerRenderer"),!this.allowRegistration("renderers.override","registerRenderer","renderers"))return;if(typeof n!="function")throw new TypeError("registerRenderer requires a renderer function");let o=String(t).trim().toLowerCase();if(!Du(o))throw new Error(`registerRenderer format must be toon|json, received: ${String(t)}`);if(r.resultDiscriminator!==void 0&&typeof r.resultDiscriminator!="function")throw new TypeError("registerRenderer ownership.resultDiscriminator must be a function when provided");let i=[...new Set((r.commands??[]).map(s=>{if(typeof s!="string"||s.trim().length===0)throw new TypeError("registerRenderer ownership.commands must contain non-empty command paths");return U(s)}))];this.#c.overrides.push({layer:this.#e.layer,name:this.#e.name,format:o,run:n,commands:i,...r.resultDiscriminator?{resultDiscriminator:r.resultDiscriminator}:{}})}registerFlags(t,n){if(H(this.#e,"schema","registerFlags"),!this.allowRegistration("schema.flags","registerFlags","schema"))return;let r=U(oe("registerFlags targetCommand",t));$o(n);let o=Mo("registerFlags flags",n);if(o.length===0)throw new TypeError("registerFlags requires at least one flag definition");this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:r,flags:o})}registerItemFields(t){if(H(this.#e,"schema","registerItemFields"),!this.allowRegistration("schema.itemfields","registerItemFields","schema"))return;Uu(t);let n=lr("registerItemFields fields",t);if(n.length===0)throw new TypeError("registerItemFields requires at least one field definition");this.#t.item_fields.push({layer:this.#e.layer,name:this.#e.name,fields:n})}registerItemTypes(t){if(H(this.#e,"schema","registerItemTypes"),!this.allowRegistration("schema.itemtypes","registerItemTypes","schema"))return;zu(t);let n=lr("registerItemTypes types",t);if(n.length===0)throw new TypeError("registerItemTypes requires at least one type definition");this.#t.item_types.push({layer:this.#e.layer,name:this.#e.name,types:n})}registerRelationshipKinds(t){if(H(this.#e,"schema","registerRelationshipKinds"),!this.allowRegistration("schema.relationshipkinds","registerRelationshipKinds","schema"))return;if(!Array.isArray(t))throw new TypeError("registerRelationshipKinds definitions requires an array of object definitions");if(t.length===0)throw new TypeError("registerRelationshipKinds requires at least one definition");let n=Hs();for(let o of this.#t.relationship_kinds)for(let i of o.definitions)n.register(i);let r=t.map(o=>(n.register(o),n.require(o.kind)));this.#t.relationship_kinds.push({layer:this.#e.layer,name:this.#e.name,definitions:r})}registerMigration(t){if(H(this.#e,"schema","registerMigration"),!this.allowRegistration("schema.migrations","registerMigration","schema"))return;Hu(t);let n=dr("registerMigration definition",t);this.#t.migrations.push(fr({layer:this.#e.layer,name:this.#e.name,definition:yn("registerMigration definition",t)},n))}registerProfile(t){if(H(this.#e,"schema","registerProfile"),!this.allowRegistration("schema.profiles","registerProfile","schema"))return;let n=cr(t);Vu(n),this.#t.profiles.push({layer:this.#e.layer,name:this.#e.name,profile:Bu(n)})}registerImportExportCommandFlags(t,n,r){r.flags!==void 0&&(H(this.#e,"schema",`${t} options.flags`),this.allowRegistration("schema.flags",`${t} options.flags`,"schema")&&($o(r.flags),this.#t.flags.push({layer:this.#e.layer,name:this.#e.name,target_command:n,flags:Mo(`${t} options.flags`,r.flags)})))}applyImportExportCommandMetadata(t,n,r){if(r!==void 0&&(typeof r!="object"||r===null||Array.isArray(r)))throw new TypeError(`${t} options must be an object when provided`);let o=`${t==="registerImporter"?"Import":"Export"} items with the registered extension adapter.`,i=[{name:"file",required:!1,description:"Optional input or output file path."}],s={...r,description:r?.description??o,arguments:r?.arguments??i},a=fu(t,s,r?.description!==void 0);V(`${t} options.action`,s.action),V(`${t} options.description`,s.description),V(`${t} options.intent`,s.intent);let c=ya(n,s.action),d=or(`${t} options.examples`,s.examples),l=or(`${t} options.failure_hints`,s.failure_hints),u=ha(s.arguments);this.registerImportExportCommandFlags(t,n,s);let f={source_version:this.#e.version,layer:this.#e.layer,name:this.#e.name,source_package:this.#e.source_package,command:n,action:c,examples:d,failure_hints:l,arguments:u},m=s.description?.trim();m&&(f.description=m);let _=s.intent?.trim();return _&&(f.intent=_),this.#t.commands.push(f),a}registerImporter(t,n,r){if(H(this.#e,"importers","registerImporter"),!this.allowRegistration("importers.importer","registerImporter","importers"))return;let o=pa(oe("registerImporter name",t));ur("registerImporter importer",n);let i=_a(o,"import");this.applyImportExportCommandMetadata("registerImporter",i,r),this.#t.importers.push({layer:this.#e.layer,name:this.#e.name,importer:o}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async s=>n(da(s,o,"import"))})}registerExporter(t,n,r){if(H(this.#e,"importers","registerExporter"),!this.allowRegistration("importers.exporter","registerExporter","importers"))return;let o=pa(oe("registerExporter name",t));ur("registerExporter exporter",n);let i=_a(o,"export"),s=this.applyImportExportCommandMetadata("registerExporter",i,r);this.#t.exporters.push({layer:this.#e.layer,name:this.#e.name,exporter:o,...s===void 0?{}:{output:s}}),this.#r.handlers.push({layer:this.#e.layer,name:this.#e.name,command:i,run:async a=>{let c=await n(da(a,o,"export"));return s?.receipt==="suppress"&&!Io(c)?Gl(c):c}})}registerSearchProvider(t){if(H(this.#e,"search","registerSearchProvider"),!this.allowRegistration("search.provider","registerSearchProvider","search"))return;let n=dr("registerSearchProvider provider",t);this.#t.search_providers.push(fr({layer:this.#e.layer,name:this.#e.name,definition:yn("registerSearchProvider provider",t)},n))}registerVectorStoreAdapter(t){if(H(this.#e,"search","registerVectorStoreAdapter"),!this.allowRegistration("search.vectorstore","registerVectorStoreAdapter","search"))return;let n=dr("registerVectorStoreAdapter adapter",t);this.#t.vector_store_adapters.push(fr({layer:this.#e.layer,name:this.#e.name,definition:yn("registerVectorStoreAdapter adapter",t)},n))}registerAssuranceMeasurementProvider(t){if(H(this.#e,"services","registerAssuranceMeasurementProvider"),!this.allowRegistration("services.assuranceprovider","registerAssuranceMeasurementProvider","services"))return;if(Lu(t),t.network&&this.#e.permissions?.network!==!0)throw new TypeError("registerAssuranceMeasurementProvider network provider requires permissions.network=true");let n=dr("registerAssuranceMeasurementProvider provider",t);this.#t.assurance_providers.push(fr({layer:this.#e.layer,name:this.#e.name,network_permission:this.#e.permissions?.network===!0,definition:yn("registerAssuranceMeasurementProvider provider",t)},n))}registerBeforeCommand(t){H(this.#e,"hooks","api.hooks.beforeCommand"),this.allowRegistration("hooks.beforecommand","api.hooks.beforeCommand","hooks")&&(Ot("beforeCommand",t),this.#o.beforeCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerBeforeMutation(t){H(this.#e,"hooks","api.hooks.beforeMutation"),this.allowRegistration("hooks.beforemutation","api.hooks.beforeMutation","hooks")&&(Ot("beforeMutation",t),this.#o.beforeMutation.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerAfterCommand(t){H(this.#e,"hooks","api.hooks.afterCommand"),this.allowRegistration("hooks.aftercommand","api.hooks.afterCommand","hooks")&&(Ot("afterCommand",t),this.#o.afterCommand.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnWrite(t){H(this.#e,"hooks","api.hooks.onWrite"),this.allowRegistration("hooks.onwrite","api.hooks.onWrite","hooks")&&(Ot("onWrite",t),this.#o.onWrite.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnRead(t){H(this.#e,"hooks","api.hooks.onRead"),this.allowRegistration("hooks.onread","api.hooks.onRead","hooks")&&(Ot("onRead",t),this.#o.onRead.push({layer:this.#e.layer,name:this.#e.name,run:t}))}registerOnIndex(t){H(this.#e,"hooks","api.hooks.onIndex"),this.allowRegistration("hooks.onindex","api.hooks.onIndex","hooks")&&(Ot("onIndex",t),this.#o.onIndex.push({layer:this.#e.layer,name:this.#e.name,run:t}))}};function Gv(e,t,n,r,o,i,s,a,c,d,l){return new ba(e,t,n,r,o,i,s,a,c,d,l)}function Kv(e){let t=e.commands.length,n=e.flags.reduce((s,a)=>s+a.flags.length,0),r=e.item_fields.reduce((s,a)=>s+a.fields.length,0),o=e.item_types.reduce((s,a)=>s+a.types.length,0),i=(e.relationship_kinds??[]).reduce((s,a)=>s+a.definitions.length,0);return{commands:t,flags:n,item_fields:r,item_types:o,...i>0?{relationship_kinds:i}:{},migrations:e.migrations.length,profiles:e.profiles.length,importers:e.importers.length,exporters:e.exporters.length,search_providers:e.search_providers.length,vector_store_adapters:e.vector_store_adapters.length,...(e.assurance_providers?.length??0)>0?{assurance_providers:e.assurance_providers.length}:{}}}function Yv(e){let t=[],n=(i,s)=>{let a=new Map;for(let c of i){let d=a.get(c.command)??[];d.push(c),a.set(c.command,d)}for(let c of[...a.keys()].sort((d,l)=>d.localeCompare(l))){let d=a.get(c);if(d.length<=1)continue;let l=d[d.length-1];for(let u of d.slice(0,-1))t.push(`${s}:${c}:${l.layer}:${l.name}:${u.layer}:${u.name}`)}};n(e.handlers,"extension_command_handler_collision"),n(e.overrides,"extension_command_override_collision");let r=new Set(e.handlers.map(i=>i.command)),o=[...new Set(e.overrides.map(i=>i.command))].filter(i=>r.has(i));o.sort((i,s)=>i.localeCompare(s));for(let i of o){let s=e.handlers.filter(c=>c.command===i),a=e.overrides.filter(c=>c.command===i);for(let c of a)for(let d of s)t.push(`extension_command_override_handler_overlap:${i}:${c.layer}:${c.name}:${d.layer}:${d.name}`)}return t}function Xv(e){let t=new Map;for(let r of e.overrides){let o=t.get(r.format)??[];o.push(r),t.set(r.format,o)}let n=[];for(let r of[...t.keys()].sort((o,i)=>o.localeCompare(i))){let o=t.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))i.commands?.length&&s.commands?.length&&!s.commands.some(a=>i.commands?.includes(a))||n.push(`extension_renderer_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return n}function Jv(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.command)??[];o.push(r),n.set(r.command,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1)continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_parser_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}var Zv=new Set(["output_format"]);function Qv(e){let t=[],n=new Map;for(let r of e.overrides){let o=n.get(r.service)??[];o.push(r),n.set(r.service,o)}for(let r of[...n.keys()].sort((o,i)=>o.localeCompare(i))){let o=n.get(r);if(o.length<=1||Zv.has(r))continue;let i=o[o.length-1];for(let s of o.slice(0,-1))t.push(`extension_service_override_collision:${r}:${i.layer}:${i.name}:${s.layer}:${s.name}`)}return t}async function h1(e){let t=wu(e.policy??kv),n=nr(),r=Bs(),o=Ws(),i=Gs(),s=Ks(),a=Ys(),c=Xs(),d=[],l=[];for(let m of e.loaded){let _=af(m.module);if(!_)continue;let y=d.length,b=cu({hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c});try{await _.activate(Gv(m,n,r,o,i,s,a,c,l,d,t)),d.length>y&&(b(),l.push(`extension_activation_rolled_back:${m.layer}:${m.name}`))}catch(v){b(),l.push(`extension_activate_failed:${m.layer}:${m.name}`);let T=$u(v);d.push({layer:m.layer,name:m.name,entry_path:m.entry_path,error:jo(v),trace:T})}}let u=[...Yv(r),...Jv(o),...Ru(i),...Qv(s),...Xv(a)],f=[...new Set([...l,...u])];return{hooks:n,commands:r,parsers:o,preflight:i,services:s,renderers:a,registrations:c,failed:d,warnings:f,hook_counts:{before_command:n.beforeCommand.length,before_mutation:n.beforeMutation.length,after_command:n.afterCommand.length,on_write:n.onWrite.length,on_read:n.onRead.length,on_index:n.onIndex.length},command_override_count:r.overrides.length,command_handler_count:r.handlers.length,parser_override_count:o.overrides.length,preflight_override_count:i.overrides.length,service_override_count:s.overrides.length,renderer_override_count:a.overrides.length,registration_counts:Kv(c)}}(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]="b1a38f8c-8f65-59e2-bddf-ed0606a0f0b5")}catch{}})();function v1(e){return{...e,hooks:nr(),profileEnabled:!!e.globalOptions.profile,migrationBlockers:[]}}(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]="4da25248-2914-5bc5-aa42-87f677ef4ea8")}catch{}})();function k1(){let e=Promise.resolve(),t=new Set;return{async read(n){let r=e,o,i=new Promise(s=>{o=s});t.add(i),await r;try{return await n()}finally{t.delete(i),o()}},write(n){let r=Promise.all([e,...t]).then(()=>n());return e=r.then(()=>{},()=>{}),r}}}function eE(){let e=Promise.resolve(),t=0,n=[],r=()=>{if(t!==0)return;let o=n.splice(0);for(let i of o)i()};return{enqueue(o){t++;let i=e.then(()=>o());return e=i.then(()=>{},()=>{}).finally(()=>{t--,r()}),i},idle(){return t===0?Promise.resolve():new Promise(o=>n.push(o))}}}(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]="d8844150-afb4-5f2e-a005-4cfb8482660c")}catch{}})();var tE={commands:["registerCommand","command override","command handler"],renderers:["registerRenderer"],hooks:["hooks.beforeCommand","hooks.beforeMutation","hooks.afterCommand","hooks.onWrite","hooks.onRead","hooks.onIndex"],schema:["registerFlags","registerItemFields","registerItemTypes","registerRelationshipKinds","registerMigration","registerProfile"],importers:["registerImporter","registerExporter"],search:["registerSearchProvider","registerVectorStoreAdapter"],parser:["registerParser"],preflight:["registerPreflight"],services:["registerService","registerAssuranceMeasurementProvider"]},cf=":";function df(e,t){return`${e}${cf}${wa(t)}`}function nE(e){return e.slice(e.indexOf(cf)+1)}function wa(e){return e.trim().toLowerCase()}function rE(e){if(!Array.isArray(e))return[];let t=new Set;for(let n of e){let r=Kl(n);r!==null&&t.add(r)}return[...t].sort((n,r)=>n.localeCompare(r))}function lf(e){let t=new Map,n=(l,u)=>{for(let f of l){let m=df(f.layer,f.name),_=t.get(m);_===void 0&&(_=new Set,t.set(m,_)),_.add(u)}},{registrations:r,commands:o,parsers:i,preflight:s,services:a,renderers:c,hooks:d}=e;return n(r.commands,"commands"),n(o.overrides,"commands"),n(o.handlers,"commands"),n(r.flags,"schema"),n(r.item_fields,"schema"),n(r.item_types,"schema"),n(r.relationship_kinds??[],"schema"),n(r.migrations,"schema"),n(r.profiles,"schema"),n(r.importers,"importers"),n(r.exporters,"importers"),n(r.search_providers,"search"),n(r.vector_store_adapters,"search"),n(i.overrides,"parser"),n(s.overrides,"preflight"),n(a.overrides,"services"),n(r.assurance_providers??[],"services"),n(c.overrides,"renderers"),n(d.beforeCommand,"hooks"),n(d.beforeMutation,"hooks"),n(d.afterCommand,"hooks"),n(d.onWrite,"hooks"),n(d.onRead,"hooks"),n(d.onIndex,"hooks"),t}function oE(e,t={}){let n=lf(e),r=new Set;t.extensionName!==void 0&&r.add(wa(t.extensionName));for(let i of t.extensionNames??[])r.add(wa(i));let o=new Set;for(let[i,s]of n)if(!(r.size>0&&!r.has(nE(i))))for(let a of s)o.add(a);return[...o].sort((i,s)=>i.localeCompare(s))}function iE(e,t){let n=lf(t),r=[];for(let o of e){let i=rE(o.capabilities);if(i.length===0)continue;let s=n.get(df(o.layer,o.name))??new Set,a=[...s].sort((d,l)=>d.localeCompare(l)),c=i.filter(d=>!s.has(d));r.push({layer:o.layer,name:o.name,declared:i,used:a,unused:c})}return r}import{existsSync as sE}from"node:fs";import{AsyncLocalStorage as aE}from"node:async_hooks";import ze 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]="7c2e7a35-cbf9-5bb6-abfd-f1ae75c6afc2")}catch{}})();var He=null,hn=null,pr=null,_r=null,gn=null,yr=null,hr=null,Xe=null,Fo,Lo=[],ff=new aE;function $(){return ff.getStore()}function x1(e){return ff.run({hooks:null,commands:null,parsers:null,preflight:null,services:null,renderers:null,registrations:null,commandContext:null,commandResult:void 0,affectedItems:[]},e)}var cE=new Set(["body","comments","dependencies","docs","events","files","learnings","notes","reminders","test_runs","tests"]);function uf(e){let t=ze.resolve(e);for(;;){if(sE(ze.join(t,".git")))return t;let n=ze.dirname(t);if(n===t)return;t=n}}function Uo(e){let t=process.env.PM_SOURCE_WORKSPACE_ROOT?.trim()||process.cwd(),n=uf(t)??ze.resolve(t),r=uf(n);if(!e)return{source_workspace_root:n,...r?{repo_root:r}:{}};let o=ze.relative(n,ze.resolve(e)),i=o.length>0&&!o.startsWith(`..${ze.sep}`)&&o!==".."&&!ze.isAbsolute(o);return{source_workspace_root:n,...r?{repo_root:r}:{},...i?{pm_root_rel:o.split(ze.sep).join("/")}:{}}}function N1(e){let t=$();if(t){t.hooks=e;return}He=e}function D1(e){let t=$();if(t){t.commands=e;return}hn=e}function P1(e){let t=$();if(t){t.parsers=e;return}pr=e}function M1(e){let t=$();if(t){t.preflight=e;return}_r=e}function $1(e){let t=$();if(t){t.services=e;return}gn=e}function j1(e){let t=$();if(t){t.renderers=e;return}yr=e}function L1(e){let t=$();if(t){t.registrations=e;return}hr=e}function mf(){let e=$();return e?e.registrations:hr}function F1(){let e=$();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=null,e.affectedItems=[];return}He=null,hn=null,pr=null,_r=null,gn=null,yr=null,hr=null,Xe=null,Fo=null}function U1(e){let t=e?{...e,...Uo(e.pm_root)}:null,n=$();if(n){n.commandContext=t;return}Xe=t}function pf(){let e=$(),t=e?e.commandContext:Xe;return t?{...t,args:[...t.args],options:t.options?{...t.options}:{},global:t.global?{...t.global}:void 0}:null}function z1(e){let t=$()??{commandContext:Xe,hooks:He,commands:hn,parsers:pr,preflight:_r,services:gn,renderers:yr,registrations:hr};return t.commandContext?.command!==e||[t.hooks,t.preflight,t.services,t.renderers].some(n=>Object.values(n??{}).some(r=>r.length>0))||[t.commands,t.parsers].some(n=>Object.values(n??{}).some(r=>r.some(o=>o.command===e)))?!1:!Object.entries(t.registrations??{}).some(([n,r])=>["migrations","search_providers","vector_store_adapters","assurance_providers"].includes(n)&&r.length>0)}function zo(e){let t=$();if(t){t.commandResult=e;return}Fo=e}function H1(){let e=$();return e?e.commandResult:Fo}function q1(e){if(!e)return;let t=$();t?t.affectedItems.push(e):Lo.push(e)}function V1(e,t){if(!e||!e.id)return{};let n={id:e.id,type:e.type,status:e.status};if(!Array.isArray(t))return n;let r=e;for(let o of t){if(typeof o!="string")continue;let i=o.startsWith("unset:")?o.slice(6):o;i==="id"||i==="type"||i==="status"||cE.has(i)||Object.hasOwn(r,i)&&r[i]!==void 0&&(n[i]=r[i])}return n}function B1(){let e=$(),t=e?.affectedItems??Lo;if(t.length===0)return;let n=t;return e?e.affectedItems=[]:Lo=[],n}function W1(){let e=$();if(e){e.hooks=null,e.commands=null,e.parsers=null,e.preflight=null,e.services=null,e.renderers=null,e.registrations=null,e.commandContext=null,e.commandResult=void 0,e.affectedItems=[];return}He=null,hn=null,pr=null,_r=null,gn=null,yr=null,hr=null,Xe=null,Fo=void 0,Lo=[]}async function Ho(e){let t=$(),n=t?t.hooks:He;return n?Zs(n,e):[]}async function G1(e){let t=$(),n=t?t.hooks:He;n&&await Js(n,e)}async function bn(e){let t=$(),n=t?t.hooks:He;return n?Qs(n,e):[]}function K1(){let e=$();return((e?e.hooks:He)?.onRead?.length??0)>0}async function Y1(e){let t=$(),n=t?t.hooks:He;return n?ea(n,e):[]}function _f(e){let t=$(),n=t?t.commands:hn,r=t?t.commandContext:Xe;return!n||!r?{overridden:!1,result:e,warnings:[]}:sa(n,{command:r.command,args:[...r.args],options:r.options?{...r.options}:{},global:r.global?{...r.global}:void 0,pm_root:r.pm_root,source_workspace_root:r.source_workspace_root,repo_root:r.repo_root,pm_root_rel:r.pm_root_rel,result:e})}async function X1(e){let t=$(),n=t?t.commands:hn;return n?ta(n,{...e,...Uo(e.pm_root)}):{handled:!1,result:null,warnings:[]}}async function J1(e){let t=$(),n=t?t.parsers:pr;return n?na(n,{...e,...Uo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},warnings:[]}}async function Z1(e){let t=$(),n=t?t.preflight:_r;return n?ra(n,{...e,...Uo(e.pm_root)}):{overridden:!1,context:{command:e.command,args:[...e.args],options:{...e.options},global:{...e.global},pm_root:e.pm_root},decision:{...e.decision},warnings:[]}}function yf(e,t){let n=$(),r=n?n.renderers:yr,o=n?n.commandContext:Xe;return r?aa(r,{format:e,command:o?.command,args:o?[...o.args]:[],options:o?.options?{...o.options}:{},global:o?.global?{...o.global}:void 0,pm_root:o?.pm_root,source_workspace_root:o?.source_workspace_root,repo_root:o?.repo_root,pm_root_rel:o?.pm_root_rel,result:t}):{overridden:!1,rendered:null,warnings:[]}}function hf(e,t){let n=$(),r=n?n.commandContext:Xe;return{service:e,command:r?.command,args:r?[...r.args]:[],options:r?.options?{...r.options}:{},global:r?.global?{...r.global}:void 0,pm_root:r?.pm_root,source_workspace_root:r?.source_workspace_root,repo_root:r?.repo_root,pm_root_rel:r?.pm_root_rel,payload:t}}async function wn(e,t){let n=$(),r=n?n.services:gn;return r?ia(r,hf(e,t)):{handled:!1,result:t,warnings:[]}}function va(e,t){let n=$(),r=n?n.services:gn;return r?oa(r,hf(e,t)):{handled:!1,result:t,warnings:[]}}import{createHash as dE}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]="ca5b60a5-80a7-5e7d-917f-4c7649bcbab6")}catch{}})();var iM=["sha256","sha512"],lE="sha256",gf="sha256";function Tt(e){if(e===void 0)return lE;if(e==="sha256"||e==="sha512")return e;throw new TypeError(`unsupported_history_hash_algorithm:${String(e)}`)}function Je(e,t){return dE(Tt(t)).update(e,"utf8").digest("hex")}(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]="3bfeb8d2-52c2-587a-9611-c4d5817cb47e")}catch{}})();function bf(e){let t=[],n=e[0]?.op==="history_compact_baseline",r=n?1:void 0,o=!1;for(let[i,s]of e.entries())s.op==="delete"&&(o=!0),s.op==="create"&&(r!==void 0&&t.push({prior_genesis_index:r,repeated_create_index:i+1,sequence:o?"delete_then_create":n?"checkpoint_then_create":"multiple_creates"}),r??=i+1,o=!1);return t}import vf from"node:path";import{link as uE,mkdir as fE,mkdtemp as mE,rm as pE,writeFile as _E}from"node:fs/promises";import Ea 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]="71c2fed9-81e1-5723-8e34-e6327c07a130")}catch{}})();async function wf(e,t){let n=Ea.dirname(e);await fE(n,{recursive:!0});let r=await mE(Ea.join(n,".pm-seed-")),o=Ea.join(r,"value");try{await _E(o,t,"utf8");try{return await uE(o,e),!0}catch(i){if(i.code==="EEXIST")return!1;throw i}}finally{await pE(r,{recursive:!0,force:!0})}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2075887b-6d4b-582f-9da2-bab13198f9a5")}catch{}})();var yE=2e3,qo=new Map;function Ze(e){if(typeof e!="string")return"";let t=qo.get(e);if(t!==void 0)return t;let n=e.trim().toLowerCase().replaceAll(/[\s-]+/g,"_");return qo.size>=yE&&wo(qo),qo.set(e,n),n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6e07b1b6-1757-54dd-8833-9d3f984ccf79")}catch{}})();var ie=Object.freeze({types:"schema/types.json",statuses:"schema/statuses.json",fields:"schema/fields.json",workflows:"schema/workflows.json"}),Sf=Xd,Sa=Yd,hE=["create","update"],gE=new Set(so),bE=new Set(cn),wE=new Set(ao),vE=new Set(co),EE=new Set(["string","number","boolean","array","object"]),kE=16;function Of(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var SE=[e=>e.type===void 0||typeof e.type=="string"&&EE.has(e.type),e=>!Object.hasOwn(e,"const")||Bo(e.const),e=>e.enum===void 0||Array.isArray(e.enum)&&e.enum.every(t=>Bo(t)),e=>e.min_length===void 0||Number.isInteger(e.min_length)&&e.min_length>=0,e=>e.min_items===void 0||Number.isInteger(e.min_items)&&e.min_items>=0,e=>e.format===void 0||e.format==="date-time",e=>e.required===void 0||Array.isArray(e.required)&&e.required.every(t=>typeof t=="string"&&t.length>0),e=>e.additional_properties===void 0||typeof e.additional_properties=="boolean",e=>e.properties===void 0||Of(e.properties),e=>e.one_of===void 0||Array.isArray(e.one_of)&&e.one_of.length>0];function Bo(e,t=new Set){if(e===null||typeof e=="string"||typeof e=="boolean")return!0;if(typeof e=="number")return Number.isFinite(e);if(typeof e!="object"||t.has(e))return!1;t.add(e);let n=Array.isArray(e)?e.every(r=>Bo(r,t)):Object.values(e).every(r=>Bo(r,t));return t.delete(e),n}function Vo(e,t=0,n=new Set){if(!Of(e)||t>kE||n.has(e))return;n.add(e);let r=e,o=r.type,i=r.enum,s=r.one_of,a=r.properties,c=r.items,d=r.required,l=r.min_length,u=r.min_items,f=r.format,m=r.additional_properties;if(!SE.every(v=>v(r))){n.delete(e);return}let _=a===void 0?void 0:Object.fromEntries(Object.entries(a).map(([v,T])=>[v,Vo(T,t+1,n)])),y=c===void 0?void 0:Vo(c,t+1,n),b=s===void 0?void 0:s.map(v=>Vo(v,t+1,n));if([...Object.values(_??{}),...c===void 0?[]:[y],...b??[]].some(v=>v===void 0)){n.delete(e);return}return n.delete(e),Object.fromEntries(Object.entries({type:o,const:Object.hasOwn(r,"const")?r.const:void 0,enum:i,min_length:l,min_items:u,format:f,properties:_,required:d===void 0?void 0:[...new Set(d)],additional_properties:m,items:y,one_of:b}).filter(([,v])=>v!==void 0))}function br(e){let t=Array.isArray(e)?e:[];return[...new Set(t.map(n=>typeof n=="string"?n.trim():"").filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r))}function ye(e){if(typeof e!="string"||e.length===0)return;let t=Ze(e);return t.length>0?t:void 0}function OE(e){return e.startsWith("--")?e.slice(2):e}function Ef(e){return typeof e=="string"?OE(e.trim().toLowerCase().replaceAll(/[\s_]+/g,"-")):""}function Af(e){return e.replaceAll("_","-")}function AE(e){let t=e.replaceAll(/[^A-Za-z0-9]+/g," ").trim().split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function ka(e,t){let n=ye(e.id);if(!n)return null;let r=[...new Set(br(e.aliases).map(Ze).filter(a=>a.length>0))].sort((a,c)=>a.localeCompare(c)),o=br(e.roles).filter(a=>gE.has(a)),i=e.description?.trim(),s=typeof e.order=="number"&&Number.isFinite(e.order)?e.order:t;return{id:n,aliases:r,roles:o,description:i&&i.length>0?i:void 0,order:s}}function IE(e){return{draft_status:ye(e?.draft_status),open_status:ye(e?.open_status),in_progress_status:ye(e?.in_progress_status),blocked_status:ye(e?.blocked_status),close_status:ye(e?.close_status),canceled_status:ye(e?.canceled_status)}}function If(e,t){if(!Array.isArray(t)||t.length!==2)return;let n=Ze(t[0]),r=Ze(t[1]);n.length===0||r.length===0||e.pairs.some(o=>o[0]===n&&o[1]===r)||e.pairs.push([n,r])}function TE(e){let t=typeof e?.type=="string"?e.type.trim():"";if(t.length===0||!Array.isArray(e?.allowed_transitions))return null;let n={type:t,pairs:[],denyAll:e.allowed_transitions.length===0};for(let r of e.allowed_transitions)If(n,r);return{typeKey:t.toLowerCase(),record:n}}function CE(e){if(!Array.isArray(e)||e.length===0)return;let t=new Map;for(let r of e){let o=TE(r);if(o===null)continue;let i=t.get(o.typeKey)??o.record;i.denyAll||=o.record.denyAll;for(let s of o.record.pairs)If(i,s);t.set(o.typeKey,i)}let n=[];for(let r of t.values())(r.pairs.length>0||r.denyAll)&&n.push({type:r.type,allowed_transitions:r.pairs});return n.sort((r,o)=>r.type.localeCompare(o.type)),n.length>0?n:void 0}function Tf(e){let t=Ze(e.key??"");if(!t)return null;let n=Ze(e.metadata_key??e.front_matter_key??t),r=Ef(e.cli_flag??Af(t));if(!r)return null;let o=br(e.cli_aliases).map(u=>Ef(u)).filter(u=>u.length>0&&u!==r),i=typeof e.type=="string"?e.type.trim().toLowerCase():"string",s=bE.has(i)?i:"string",a=(()=>{let u=br(e.commands).filter(f=>wE.has(f));return u.length>0?u:[...hE]})(),c=e.description?.trim(),d=br(e.required_types),l=e.value_schema===void 0?void 0:Vo(e.value_schema);return e.value_schema!==void 0&&l===void 0?null:{key:t,metadata_key:n,cli_flag:r,cli_aliases:o,description:c&&c.length>0?c:void 0,type:s,commands:a,repeatable:[e.repeatable===!0,s==="string_array"].includes(!0),required:e.required===!0,required_on_create:e.required_on_create===!0,required_types:d,allow_unset:e.allow_unset!==!1,value_schema:l}}function RE(e){let t=new Map;for(let[r,o]of e.entries()){let i=ka(o,r);i&&t.set(i.id,i)}let n=kf([...t.values()]);return n.length>0?n:kf(Sa.map((r,o)=>ka(r,o)).filter(r=>r!==null))}function kf(e){return e.sort((t,n)=>t.order===n.order?t.id.localeCompare(n.id):t.order-n.order)}function xE(e){let t=new Map;for(let n of e??[]){let r=Tf(n);r&&t.set(r.key,r)}return[...t.values()].sort((n,r)=>n.key.localeCompare(r.key))}function NE(e){return{id:e.id,aliases:e.aliases.length>0?[...e.aliases]:void 0,roles:e.roles.length>0?[...e.roles]:void 0,description:e.description,order:e.order}}function DE(e){return{key:e.key,metadata_key:e.metadata_key!==e.key?e.metadata_key:void 0,cli_flag:e.cli_flag!==Af(e.key)?e.cli_flag:void 0,cli_aliases:e.cli_aliases.length>0?[...e.cli_aliases]:void 0,description:e.description,type:e.type,commands:[...e.commands],repeatable:e.repeatable===!0?!0:void 0,required:e.required===!0?!0:void 0,required_on_create:e.required_on_create===!0?!0:void 0,required_types:e.required_types.length>0?[...e.required_types]:void 0,allow_unset:e.allow_unset===!1?!1:void 0,value_schema:e.value_schema}}function PE(e){let t=typeof e=="string"?e.trim().toLowerCase():"allow";return vE.has(t)?t:"allow"}function Ce(e){let t={...ie,...e?.files},n=e?.statuses&&e.statuses.length>0?e.statuses:Sa,r=RE(n),o=xE(e?.fields);return{version:typeof e?.version=="number"&&Number.isFinite(e.version)?Math.floor(e.version):1,files:t,statuses:r.map(NE),fields:o.map(DE),workflow:{...Sf,...IE(e?.workflow)},type_workflows:CE(e?.type_workflows),unknown_field_policy:PE(e?.unknown_field_policy)}}function ME(e,t,n){try{return JSON.parse(e)}catch{n.push(t);return}}function $E(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.definitions))return t.definitions;if(typeof t.item_types=="object"&&t.item_types!==null){let n=t.item_types;if(Array.isArray(n.definitions))return n.definitions}}function jE(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.statuses))return t.statuses;if(Array.isArray(t.definitions))return t.definitions}function LE(e){if(Array.isArray(e))return e;if(typeof e!="object"||e===null)return;let t=e;if(Array.isArray(t.fields))return t.fields;if(Array.isArray(t.definitions))return t.definitions}function FE(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;return typeof t.workflow=="object"&&t.workflow!==null&&!Array.isArray(t.workflow)?t.workflow:typeof t.workflows=="object"&&t.workflows!==null&&!Array.isArray(t.workflows)?t.workflows:t}function UE(e){if(typeof e!="object"||e===null||Array.isArray(e))return;let t=e;if(Array.isArray(t.type_workflows))return t.type_workflows}function ue(e,t,n){let r=t?.trim()||n;return vf.isAbsolute(r)?r:vf.join(e,r)}function bM(e,t){return ue(e,t.files.types,ie.types)}async function wM(e,t){let n=Ce(t),r=[{path:ue(e,n.files.types,ie.types),seed:{definitions:[]}},{path:ue(e,n.files.statuses,ie.statuses),seed:{statuses:Sa}},{path:ue(e,n.files.fields,ie.fields),seed:{fields:[]}},{path:ue(e,n.files.workflows,ie.workflows),seed:{workflow:Sf}}],o=[];for(let i of r)await gt(i.path)||await wf(i.path,`${JSON.stringify(i.seed,null,2)}
3
+ `)&&o.push(i.path);return{created_paths:o}}async function Cf(e,t){let n=Ce(t),r=[],o=ue(e,n.files.types,ie.types),i=ue(e,n.files.statuses,ie.statuses),s=ue(e,n.files.fields,ie.fields),a=ue(e,n.files.workflows,ie.workflows),c,d,l,u,f,m=async(T,G)=>{let ce=await Ae(T);if(ce!==null)return ME(ce,G,r)},_=await m(o,"runtime_schema_types_invalid_json");_!==void 0&&(c=$E(_),c===void 0&&r.push("runtime_schema_types_invalid_shape"));let y=await m(i,"runtime_schema_statuses_invalid_json");y!==void 0&&(d=jE(y),d===void 0&&r.push("runtime_schema_statuses_invalid_shape"));let b=await m(s,"runtime_schema_fields_invalid_json");b!==void 0&&(l=LE(b),l===void 0&&r.push("runtime_schema_fields_invalid_shape"));let v=await m(a,"runtime_schema_workflows_invalid_json");return v!==void 0&&(u=FE(v),u===void 0&&r.push("runtime_schema_workflows_invalid_shape"),f=UE(v)),{schema:Ce({...n,statuses:[...n.statuses,...d??[]],fields:[...n.fields,...l??[]],workflow:{...n.workflow,...u},type_workflows:[...n.type_workflows??[],...f??[]]}),type_definitions_from_file:c,warnings:r,created_paths:[]}}function gr(e,t,n,r=!1){let o=n.map(s=>ye(s)).filter(s=>typeof s=="string").find(s=>e.some(a=>a.id===s));if(r&&o!==void 0)return o;let i=e.find(s=>s.roles.includes(t));return i!==void 0?i.id:o??e[0]?.id}function zE(e){let t=new Map,n=new Map;for(let r of e){n.set(r.id,r),t.set(r.id,r.id),t.set(r.id.replaceAll("_","-"),r.id),t.set(r.id.replaceAll("_"," "),r.id);for(let o of r.aliases)t.set(o,r.id),t.set(o.replaceAll("_","-"),r.id),t.set(o.replaceAll("_"," "),r.id)}return{aliasToId:t,byId:n}}function HE(e){let t={activeStatuses:new Set,blockedStatuses:new Set,draftStatuses:new Set,terminalCanceledStatuses:new Set,terminalDoneStatuses:new Set,terminalStatuses:new Set};for(let n of e){let r=new Set(n.roles);(r.has("terminal")||r.has("terminal_done")||r.has("terminal_canceled"))&&t.terminalStatuses.add(n.id),r.has("terminal_done")&&t.terminalDoneStatuses.add(n.id),r.has("terminal_canceled")&&t.terminalCanceledStatuses.add(n.id),r.has("active")&&t.activeStatuses.add(n.id),r.has("blocked")&&t.blockedStatuses.add(n.id),r.has("draft")&&t.draftStatuses.add(n.id)}return t}function Rf(e){let t=Ce(e),n=t.statuses.map((v,T)=>ka(v,T)).filter(v=>v!==null),{aliasToId:r,byId:o}=zE(n),{activeStatuses:i,blockedStatuses:s,draftStatuses:a,terminalCanceledStatuses:c,terminalDoneStatuses:d,terminalStatuses:l}=HE(n),u=t.workflow,f=ye(u.open_status)??gr(n,"default_open",["open","in_progress",an[0]]),m=ye(u.in_progress_status)??gr(n,"active",["in_progress","in-progress",f],!0),_=ye(u.blocked_status)??gr(n,"blocked",["blocked"]),y=ye(u.close_status)??gr(n,"default_close",["closed","done","complete"]),b=ye(u.canceled_status)??gr(n,"default_cancel",["canceled","cancelled"]);return{definitions:n,by_id:o,alias_to_id:r,terminal_statuses:l,terminal_done_statuses:d,terminal_canceled_statuses:c,active_statuses:i,blocked_statuses:s,draft_statuses:a,open_status:f,in_progress_status:m,blocked_status:_,close_status:y,canceled_status:b}}function Oa(e,t){let n=Ze(e);if(n)return t.alias_to_id.get(n)}function xf(e){let t=Ce(e),n=new Map,r=t.fields.map(c=>Tf(c)).filter(c=>c!==null);for(let c of r)n.set(c.key,c);let o=[...n.values()].sort((c,d)=>c.key.localeCompare(d.key)),i=new Map,s=new Map,a=new Map;for(let c of o){i.set(c.key,c),s.set(c.cli_flag,c);for(let d of c.cli_aliases)s.set(d,c);for(let d of c.commands){let l=a.get(d)??[];l.push(c),a.set(d,l)}}for(let[c,d]of a.entries())d.sort((l,u)=>l.key.localeCompare(u.key)),a.set(c,d);return{definitions:o,by_key:i,by_cli_token:s,command_to_fields:a}}function Nf(e){return AE(e.key)}function vM(e,t){let n=Oa(e,t);return n?t.terminal_statuses.has(n):!1}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d1e62e3f-c165-5713-a074-070806d85b32")}catch{}})();var qE=16;function Wo(e){let t=e.trim().replaceAll(/[^A-Za-z0-9]+/g," ").split(/\s+/).filter(o=>o.length>0).map(o=>o.toLowerCase());if(t.length===0)return e;let[n,...r]=t;return`${n}${r.map(o=>`${o.slice(0,1).toUpperCase()}${o.slice(1)}`).join("")}`}function CM(e,t,n=new Set,r){if($f(e,t,r))return;let o=jf(e,t,n,r),i=Go(e);return[Wo(e.cli_flag),...i].find(s=>!o.has(s)&&Mf(s,i,o))}function Mf(e,t,n){for(let r of t){if(r===e)break;if(n.has(r))return!1}return!0}function $f(e,t,n){return t.definitions.some(r=>r!==e&&r.metadata_key===e.metadata_key&&(n===void 0||r.commands.includes(n)))}function jf(e,t,n,r){return new Set([...n,...t.definitions.filter(o=>o!==e&&(r===void 0||o.commands.includes(r))).flatMap(o=>Go(o))])}function Lf(e){return e.replace(/^-+/u,"").startsWith("no-")}function VE(e){return e.startsWith("-")?e:`--${e}`}function RM(e,t,n,r){if($f(e,t,r))return;let o=jf(e,t,n.options,r),i=Go(e);return[e.cli_flag,...e.cli_aliases].find(s=>{let a=Ff(s);return Lf(s)||n.flags.has(VE(s))||o.has(a)?!1:Mf(a,i,o)})}function Ff(e){return e.replace(/^-+/u,"").replace(/^no-/u,"").split("-").reduce((t,n)=>`${t}${n.charAt(0).toUpperCase()}${n.slice(1)}`)}function Go(e){return[...new Set([Nf(e),Wo(e.key),Wo(e.cli_flag),...e.cli_aliases.map(t=>Wo(t)),...[e.cli_flag,...e.cli_aliases].filter(t=>!Lf(t)).map(t=>Ff(t))])]}function Uf(e,t){for(let n of Go(t)){if(!Object.hasOwn(e,n))continue;let r=e[n];if(r!==void 0)return r}}function zf(e){return Array.isArray(e)?e.flatMap(t=>zf(t)).map(t=>t.trim()).filter(t=>t.length>0):typeof e=="string"?e.split(/[,\n|]/).map(t=>t.trim()).filter(t=>t.length>0):e==null?[]:[String(e).trim()].filter(t=>t.length>0)}function Df(e,t){if(typeof e=="boolean")return e;if(typeof e=="number"){if(e===1)return!0;if(e===0)return!1}if(typeof e=="string"){let n=e.trim().toLowerCase();if(n==="true"||n==="1"||n==="yes")return!0;if(n==="false"||n==="0"||n==="no")return!1}throw new g(`${t} must be one of true|false|1|0|yes|no`,h.USAGE)}function Pf(e,t){if(typeof e=="number"&&Number.isFinite(e))return e;let n=typeof e=="string"?e.trim():String(e),r=Number(n);if(!Number.isFinite(r))throw new g(`${t} must be a number`,h.USAGE);return r}function BE(e,t,n){let r=typeof e=="string"?(()=>{try{return JSON.parse(e)}catch{return}})():e;if(n==="array"&&Array.isArray(r)||n==="object"&&typeof r=="object"&&r!==null&&!Array.isArray(r))return r;throw new g(`${t} must be valid JSON ${n}`,h.USAGE)}function WE(e,t){return t===void 0?!0:t==="array"?Array.isArray(e):t==="object"?typeof e=="object"&&e!==null&&!Array.isArray(e):typeof e===t}function GE(e,t,n){if(t.const!==void 0&&R(e)!==R(t.const))return`${n} must equal ${R(t.const)}`;if(t.enum!==void 0&&!t.enum.some(r=>R(r)===R(e)))return`${n} must be one of ${t.enum.map(r=>R(r)).join("|")}`;if(!WE(e,t.type))return`${n} must match configured type ${String(t.type)}`;if(typeof e=="string"){if(t.min_length!==void 0&&e.length<t.min_length)return`${n} must contain at least ${t.min_length} characters`;if(t.format==="date-time"&&!Qn(e))return`${n} must be an RFC 3339 date-time`}}function KE(e,t,n,r){if(Array.isArray(e)){if(t.min_items!==void 0&&e.length<t.min_items)return`${n} must contain at least ${t.min_items} items`;if(t.items)for(let[o,i]of e.entries()){let s=Ko(i,t.items,`${n}[${o}]`,r+1);if(s)return s}}}function YE(e,t,n,r){if(typeof e!="object"||e===null||Array.isArray(e))return;let o=e;for(let i of t.required??[])if(!Object.hasOwn(o,i))return`${n}.${i} is required`;for(let[i,s]of Object.entries(o)){let a=t.properties?.[i];if(!a){if(t.additional_properties===!1)return`${n}.${i} is not allowed`;continue}let c=Ko(s,a,`${n}.${i}`,r+1);if(c)return c}}function Ko(e,t,n,r=0){if(r>qE)return`${n} value schema exceeds maximum depth`;let o=GE(e,t,n);if(o)return o;let i=KE(e,t,n,r);if(i)return i;let s=YE(e,t,n,r);if(s)return s;if(!t.one_of)return;let a=0;for(let c of t.one_of)if(Ko(e,c,n,r+1)===void 0&&(a+=1,a>1))break;return a===1?void 0:`${n} must match exactly one configured schema variant`}function Ct(e,t,n){if(!e.value_schema||t===void 0)return t;let r=Ko(t,e.value_schema,n);if(r)throw new g(r,h.USAGE);return t}function XE(e,t,n,r){let o=r==="option"&&Array.isArray(t)?t[t.length-1]:t;if(o!==void 0)return Ct(e,BE(o,n,e.type),n)}function wr(e,t,n,r="option"){let o=n??`--${e.cli_flag}`;if(e.type==="array"||e.type==="object")return XE(e,t,o,r);if(e.repeatable||e.type==="string_array"){let s=zf(t);return e.type==="number"?Ct(e,s.map(a=>Pf(a,o)),o):e.type==="boolean"?Ct(e,s.map(a=>Df(a,o)),o):Ct(e,s,o)}let i=Array.isArray(t)?t[t.length-1]:t;if(i!==void 0)return e.type==="number"?Ct(e,Pf(i,o),o):e.type==="boolean"?Ct(e,Df(i,o),o):Ct(e,typeof i=="string"?i:String(i),o)}function JE(e,t){return!e.required&&!e.required_on_create?!1:e.required_types.length===0?!0:t?e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function xM(e,t,n){let r={},o=[];for(let i of t.command_to_fields.get("create")??[]){let s=Uf(e,i);if(s===void 0){JE(i,n)&&o.push(`--${i.cli_flag}`);continue}r[i.metadata_key]=wr(i,s)}return{values:r,missing_required_flags:[...new Set(o)].sort((i,s)=>i.localeCompare(s))}}function NM(e,t,n=["update"]){let r={},o=(n??["update"]).flatMap(s=>t.command_to_fields.get(s)??[]),i=new Set;for(let s of o){let a=Uf(e,s);a!==void 0&&(i.has(s.metadata_key)||(i.add(s.metadata_key),r[s.metadata_key]=wr(s,a)))}return Cl(r),r}(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]="c35d4830-d7d1-5ee4-99bc-ab52cc3e4e09")}catch{}})();var Aa=1,Ia=2;function PM(e){return Math.max(Ta(e),e.tests?.some(t=>t.updated_by!==void 0||t.updated_at!==void 0)?2:1)}function Ta(e){let t=e.pm_format_version;return typeof t=="number"&&Number.isInteger(t)&&t>=1?t:1}function Hf(e){if(!(typeof e!="number"||!Number.isInteger(e)||e<=1))return e}function ZE(e,t=2,n=t){return e<n?"outdated":e>t?"ahead":"current"}function MM(e,t=2,n=t){let r=[],o=[];for(let i of e){let s=ZE(i.version,t,n);s==="outdated"?r.push(i.ref):s==="ahead"&&o.push(i.ref)}return{outdated:r.sort((i,s)=>i.localeCompare(s)),ahead:o.sort((i,s)=>i.localeCompare(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]="515840b7-cf86-5d71-8ac1-beac7fd7c8a8")}catch{}})();var QE={"in-progress":"in_progress",cancelled:"canceled"};function Yo(e,t){if(t){let o=Oa(e,t);if(o)return o}if(typeof e!="string")return;let n=e.trim().toLowerCase();if(!n)return;let r=QE[n]??n;if(an.includes(r))return r}function e0(e,t){return Yo(e,t)??e}function FM(e,t){return t.terminal_statuses.has(e0(e,t))}import{encode as o0}from"@toon-format/toon";import{isDeepStrictEqual as qf}from"node:util";import{decode as t0}from"@toon-format/toon";(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]="aaa2be03-9478-5fbe-82e6-e4fc86e3735b")}catch{}})();function Ca(e){return{value:t0(e),usedScalarBracketEscape:!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]="79626299-17a8-573a-9b66-ce37c65e2f5d")}catch{}})();var n0=/^\s*(<<<<<<<|=======|>>>>>>>)(?:\s.*)?$/;function r0(e){if(e.length===0)return[];let t=e.split(/\r?\n/),n=[];for(let r=0;r<t.length;r+=1){let o=t[r]??"",i=o.match(n0);if(!i)continue;let s=i[1];n.push({line:r+1,marker:s,text:o})}return n}function Xo(e){return r0(e)[0]}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="d371559f-ff71-590b-ac84-ad820852d18c")}catch{}})();var Da=new Set(["schema","tracker","auto","none"]),Kf=new Set(["source","isolated","snapshot"]),i0=new Set(["legacy","local_mutation","local_source_ref","acknowledged","invalid_provenance","foreign_source_ref"]),s0=new Set(["passed","failed","stopped","canceled"]),a0=new Set(dl);function Sn(e){return e.replaceAll("\\","/")}function Yf(e){for(let t of e)if(t!==0)return t;return 0}function Zo(e){for(let[t,n]of Object.entries(e))n===void 0&&delete e[t]}var Xf=["id","title","description","created_at","updated_at"],c0=new Set(Ve);function Jf(e){if(e?.schema)return{statusRegistry:Rf(e.schema),fieldRegistry:xf(e.schema),unknownFieldPolicy:e.schema.unknown_field_policy??"allow",extensionFieldNames:new Set(e.extensionFieldNames??[]),onWarning:e.onWarning}}function d0(e,t){return e.required?e.required_types.length===0?!0:e.required_types.map(n=>n.toLowerCase()).includes(t.trim().toLowerCase()):!1}function Qe(e){let t=e.match(/^([a-z_][\w.]*)\s/u)?.[1];throw new g(`Invalid item metadata: ${e}`,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:e.includes("required")?"missing_required_field":"schema_validation_error",...t?{field:t}:{},required:"Provide an item document whose metadata satisfies the active runtime schema.",why:e})}function kr(e,t){throw new g(t,h.GENERIC_FAILURE,{code:"item_document_invalid",reason:"syntax_error",format:e,required:`Provide a syntactically valid ${e==="toon"?"TOON":"JSON Markdown"} item document.`,why:"The document could not be decoded far enough to validate item metadata."})}function Zf(e,t){if(!t||typeof e!="object"||e===null)return;let n=Ta(e);if(!(n<=Ia))throw new g(`Stored item uses format version ${n}; this runtime supports up to ${Ia}. Upgrade pm before reading or changing this item.`,h.CONFLICT,{code:"item_format_version_unsupported",format_version:n,required:"Upgrade to a pm runtime supporting the stored item format.",nextSteps:["Preserve the original item and history; do not lower pm_format_version to bypass compatibility checks."]})}function Qf(e){let t=new Set(c0);for(let n of e.fieldRegistry?.definitions??[])t.add(n.metadata_key);for(let n of e.extensionFieldNames)t.add(n);return t}function O(e,t){e||Qe(t)}function Sr(e,t){return(typeof e!="object"||e===null||Array.isArray(e))&&Qe(t),e}function Ra(e,t){let n=e[t];O(typeof n=="string",`${t} must be a string`),O(Le(n),`${t} must be a valid ISO timestamp`)}function Vf(e,t,n){let r=e[t];r!==void 0&&O(typeof r=="number"&&Number.isInteger(r)&&r>=1,`${n} must be an integer >= 1`)}function Pa(e,t,n){let r=e[t];r!==void 0&&(O(typeof r=="string",`${n} must be a string`),O(Le(r),`${n} must be a valid ISO timestamp`))}function l0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_weekday must be an array");for(let t of e){O(typeof t=="string","event.recurrence.by_weekday entries must be strings");let n=t.trim().toLowerCase();O(Yn.includes(n),`event.recurrence.by_weekday entries must be one of: ${Yn.join(", ")}`)}}}function u0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.by_month_day must be an array");for(let t of e)O(typeof t=="number"&&Number.isInteger(t)&&t>=1&&t<=31,"event.recurrence.by_month_day entries must be integers 1..31")}}function f0(e){if(e!==void 0){O(Array.isArray(e),"event.recurrence.exdates must be an array");for(let t of e)O(typeof t=="string","event.recurrence.exdates entries must be strings"),O(Le(t),"event.recurrence.exdates entries must be valid ISO timestamps")}}function m0(e){let t=Sr(e,"event.recurrence must be an object");O(typeof t.freq=="string","event.recurrence.freq must be a string");let n=t.freq.trim().toLowerCase();O(fo.includes(n),`event.recurrence.freq must be one of: ${fo.join(", ")}`),Vf(t,"interval","event.recurrence.interval"),Vf(t,"count","event.recurrence.count"),Pa(t,"until","event.recurrence.until"),l0(t.by_weekday),u0(t.by_month_day),f0(t.exdates)}function p0(e){for(let r of Xf)O(typeof e[r]=="string",`${r} is required and must be a string`);let t=e.type;O(typeof t=="string"&&t.trim().length>0,"type must be a non-empty string");let n=e.pm_format_version;return n!==void 0&&O(typeof n=="number"&&Number.isInteger(n)&&n>=Aa,`pm_format_version must be an integer >= ${Aa}`),t}function _0(e,t){let n=e.status;O(typeof n=="string"&&n.trim().length>0,"status must be a non-empty string");let r=t?.statusRegistry,o=Yo(n,r),i=r?r.definitions.map(s=>s.id):[...an];O(o!==void 0,`status must be one of: ${i.join(", ")}`)}function y0(e){let t=e.priority;O(typeof t=="number"&&Number.isInteger(t)&&[0,1,2,3,4].includes(t),"priority must be an integer 0..4");let n=e.tags;O(Array.isArray(n),"tags must be an array");for(let r of n)O(typeof r=="string","tags entries must be strings")}function h0(e){let t=e.confidence;if(t!==void 0){if(typeof t=="number"){O(Number.isInteger(t)&&t>=0&&t<=100,"confidence number value must be an integer 0..100");return}if(typeof t=="string"){let n=t.trim().toLowerCase(),r=n==="med"||uo.includes(n);O(r,`confidence string value must be one of: ${[...uo,"med"].join(", ")}`);return}O(!1,"confidence must be a number or string")}}function g0(e){let t=e.severity;if(t===void 0)return;typeof t!="string"&&Qe("severity must be a string");let n=t.trim().toLowerCase(),r=n==="med"||lo.includes(n);O(r,`severity value must be one of: ${[...lo,"med"].join(", ")}`)}function b0(e){e.regression!==void 0&&typeof e.regression!="boolean"&&Qe("regression must be a boolean")}function w0(e){let t=e.reminders;if(t!==void 0){O(Array.isArray(t),"reminders must be an array");for(let n of t){let r=Sr(n,"reminders entries must be objects");O(typeof r.at=="string","reminder.at must be a string"),O(Le(r.at),"reminder.at must be a valid ISO timestamp"),O(typeof r.text=="string","reminder.text must be a string"),O(r.text.trim().length>0,"reminder.text must not be empty")}}}function v0(e){for(let t of["title","description","location","timezone"])e[t]!==void 0&&(O(typeof e[t]=="string",`event.${t} must be a string`),O(e[t].trim().length>0,`event.${t} must not be empty`))}function E0(e){e.recurrence!==void 0&&(m0(e.recurrence),e.recurrence.until!==void 0&&O(re(e.recurrence.until,e.start_at)>=0,"event.recurrence.until must be at or after event.start_at"))}function k0(e){let t=Sr(e,"events entries must be objects");O(typeof t.start_at=="string","event.start_at must be a string"),O(Le(t.start_at),"event.start_at must be a valid ISO timestamp"),t.end_at!==void 0&&(O(typeof t.end_at=="string","event.end_at must be a string"),O(Le(t.end_at),"event.end_at must be a valid ISO timestamp"),O(re(t.end_at,t.start_at)>0,"event.end_at must be after event.start_at")),v0(t),t.all_day!==void 0&&O(typeof t.all_day=="boolean","event.all_day must be a boolean"),E0(t)}function S0(e){let t=e.events;if(t!==void 0){O(Array.isArray(t),"events must be an array");for(let n of t)k0(n)}}function O0(e){for(let t of["source_type","source_owner","design","external_ref"]){let n=e[t];n!==void 0&&O(typeof n=="string",`${t} must be a string`)}}function A0(e){let t=e.type_options;if(t===void 0)return;let n=Sr(t,"type_options must be an object");for(let[r,o]of Object.entries(n))O(r.trim().length>0,"type_options keys must be non-empty"),O(typeof o=="string","type_options values must be strings"),O(o.trim().length>0,"type_options values must be non-empty strings")}function I0(e,t,n){if(n?.fieldRegistry)for(let r of n.fieldRegistry.definitions){let o=e[r.metadata_key];if(o===void 0){d0(r,t)&&Qe(`missing required schema field: ${r.metadata_key}`);continue}try{e[r.metadata_key]=wr(r,o,`metadata field "${r.metadata_key}"`,"metadata")}catch(i){Qe(String(i?.message).replace(/^Invalid\s+/u,""))}}}function T0(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Qf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length!==0&&(t.unknownFieldPolicy==="reject"?Qe(`unknown schema fields are not allowed: ${r.join(", ")}`):t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`))}function Ma(e,t){let n=Sr(e,"item metadata must be an object"),r=p0(n);_0(n,t),y0(n),h0(n),g0(n),b0(n),Ra(n,"created_at"),Ra(n,"updated_at"),n.deadline!==void 0&&Ra(n,"deadline"),w0(n),S0(n),Pa(n,"closed_at","closed_at"),Pa(n,"completed_at","completed_at"),O0(n),A0(n),I0(n,r,t),T0(n,t)}function C0(e){if(!(!e||e.length===0))return[...e].map((t,n)=>(O(t.created_at===void 0||typeof t.created_at=="string"&&Qn(t.created_at),`dependencies.${n}.created_at requires a valid timestamp; restore the dependency timestamp from its source record`),{id:t.id.trim(),kind:t.kind,created_at:t.created_at,author:t.author?.trim()||void 0,source_kind:t.source_kind?.trim()||void 0,author_source:t.author_source})).sort((t,n)=>{let r=re(t.created_at??"",n.created_at??"");if(r!==0)return r;let o=t.id.localeCompare(n.id);if(o!==0)return o;let i=t.kind.localeCompare(n.kind);return i!==0?i:(t.source_kind??"").localeCompare(n.source_kind??"")})}var o$=new Set(["comments","notes","learnings"]),R0="[unconvertible]";function vn(e,t){try{return String(e?.[t])}catch{return R0}}function x0(e,t){let n=re(vn(e,"created_at"),vn(t,"created_at"));if(n!==0)return n;let r=vn(e,"text").localeCompare(vn(t,"text"));return r!==0?r:vn(e,"author").localeCompare(vn(t,"author"))}function xa(e){if(!(!e||e.length===0))return[...e].sort(x0)}function N0(e){if(!e||e.length===0)return;let t=[...e].map(n=>({at:n.at,text:n.text.trim()})).filter(n=>n.text.length>0).sort((n,r)=>{let o=re(n.at,r.at);return o!==0?o:n.text.localeCompare(r.text)});return t.length===0?void 0:t}function D0(e){if(!e)return;let t=e.freq.trim().toLowerCase();if(!fo.includes(t))return;let n=Array.from(new Set((e.by_weekday??[]).map(s=>s.trim().toLowerCase()).filter(s=>Yn.includes(s)))).sort((s,a)=>bs(s)-bs(a)),r=Array.from(new Set((e.by_month_day??[]).filter(s=>Number.isInteger(s)&&s>=1&&s<=31).map(s=>s))).sort((s,a)=>s-a),o=Array.from(new Set((e.exdates??[]).map(s=>s.trim()).filter(s=>Le(s)))).sort((s,a)=>re(s,a)),i={freq:t,interval:e.interval!==void 0&&e.interval>1?e.interval:void 0,count:e.count,until:e.until?.trim()||void 0,by_weekday:n.length>0?n:void 0,by_month_day:r.length>0?r:void 0,exdates:o.length>0?o:void 0};for(let[s,a]of Object.entries(i))a===void 0&&delete i[s];return i}function P0(e){return!Array.isArray(e)||e.length===0?void 0:[...e].map(M0).sort($0)}function M0(e){let t={start_at:e.start_at,end_at:e.end_at||void 0,title:e.title?.trim()||void 0,description:e.description?.trim()||void 0,location:e.location?.trim()||void 0,all_day:e.all_day,timezone:e.timezone?.trim()||void 0,recurrence:D0(e.recurrence)};return Zo(t),t}function $0(e,t){return Yf([re(e.start_at,t.start_at),(e.end_at??"").localeCompare(t.end_at??""),(e.title??"").localeCompare(t.title??""),+!!e.all_day-+!!t.all_day,(e.timezone??"").localeCompare(t.timezone??""),(e.location??"").localeCompare(t.location??""),(e.description??"").localeCompare(t.description??""),JSON.stringify(e.recurrence??{}).localeCompare(JSON.stringify(t.recurrence??{}))])}function j0(e){if(!(!e||e.length===0))return e.map(t=>({path:Sn(t.path),scope:t.scope,note:t.note?.trim()||void 0}))}function L0(e){if(!e||e.length===0)return;let t=e.map(H0).filter(n=>n.run_id.length>0&&n.started_at.length>0&&n.finished_at.length>0&&n.recorded_at.length>0).sort((n,r)=>Yf([re(n.recorded_at,r.recorded_at),n.run_id.localeCompare(r.run_id),n.kind.localeCompare(r.kind)]));return t.length>0?t:void 0}function En(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0?Math.floor(e):void 0}function F0(e){return typeof e=="number"&&Number.isFinite(e)&&e>=1?Math.floor(e):void 0}function Na(e){return typeof e=="string"?e:""}function U0(e){if(!Array.isArray(e))return;let t=e.filter(r=>r!==null&&typeof r=="object"&&typeof r.name=="string"&&r.name.trim().length>0&&typeof r.value=="number"&&Number.isFinite(r.value)&&typeof r.recorded_at=="string"&&r.recorded_at.trim().length>0).map(r=>({name:r.name.trim(),value:r.value,unit:typeof r.unit=="string"&&r.unit.trim()||void 0,threshold:typeof r.threshold=="number"&&Number.isFinite(r.threshold)?r.threshold:void 0,recorded_at:r.recorded_at.trim()})),n=[...new Map(t.map(r=>[r.name,r])).values()].sort((r,o)=>r.name.localeCompare(o.name)).slice(0,32);return n.length>0?n:void 0}function Jo(e,t){return typeof e=="string"&&t.has(e)?e:void 0}function z0(e){if(!Array.isArray(e))return;let t=e.filter(n=>n&&typeof n.command=="string"&&n.command.trim().length>0).slice(0,32).map(n=>({command:n.command.trim(),requested_pm_context_mode:Jo(n.requested_pm_context_mode,Da),pm_context_mode:Jo(n.pm_context_mode,Da),workspace_context_mode:Jo(n.workspace_context_mode,Kf),trust_reason:Jo(n.trust_reason,i0)}));return t.length>0?t:void 0}function H0(e){let t=typeof e.run_id=="string"?e.run_id.trim():"",n=e.kind==="test"||e.kind==="test-all"?e.kind:"test",r=s0.has(e.status)?e.status:"failed",o={run_id:t,kind:n,status:r,started_at:Na(e.started_at),finished_at:Na(e.finished_at),recorded_at:Na(e.recorded_at),attempt:F0(e.attempt),resumed_from:e.resumed_from?.trim()||void 0,passed:En(e.passed)??0,failed:En(e.failed)??0,skipped:En(e.skipped)??0,items:En(e.items),linked_tests:En(e.linked_tests),fail_on_skipped_triggered:e.fail_on_skipped_triggered===!0?!0:void 0,measurements:U0(e.measurements),executions:z0(e.executions)};return Zo(o),o}function q0(e){if(!(!Array.isArray(e)||e.length===0))return e.map(K0)}function vr(e){if(!Array.isArray(e))return;let t=[...new Set(e.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0))].sort((n,r)=>n.localeCompare(r));return t.length>0?t:void 0}function Fa(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function Ua(e){return e==="__proto__"||e==="constructor"||e==="prototype"}function Bf(e){if(!Fa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),String(r).trim()]).filter(([n,r])=>n.length>0&&!Ua(n)&&r.length>0).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function V0(e){if(!Fa(e))return;let t=Object.entries(e).map(([n,r])=>[n.trim(),Number(r)]).filter(([n,r])=>n.length>0&&!Ua(n)&&Number.isFinite(r)).sort(([n],[r])=>n.localeCompare(r));return t.length>0?Object.fromEntries(t):void 0}function B0(e){let t=e?.trim().toLowerCase();if(!(!t||!Da.has(t)))return t}function W0(e){let t=e?.trim().toLowerCase();if(!(!t||!Kf.has(t)))return t}function G0(e,t){if(t===!0)return{provenance_invalid:!0};if(e===void 0)return{};if(!Fa(e))return{provenance_invalid:!0};let n=E(e.author),r=E(e.created_at),o=e.source_kind;return!n||!r||!Le(r)||o!=="local_mutation"&&o!=="merge_union"?{provenance_invalid:!0}:{provenance:{author:n,created_at:r,source_kind:o,source_ref:E(e.source_ref)}}}function K0(e){let t={command:e.command?.trim()||void 0,path:e.path?Sn(e.path):void 0,scope:e.scope,timeout_seconds:typeof e.timeout_seconds=="number"&&Number.isFinite(e.timeout_seconds)&&e.timeout_seconds>0?e.timeout_seconds:void 0,pm_context_mode:B0(e.pm_context_mode),workspace_context_mode:W0(e.workspace_context_mode),...G0(e.provenance,e.provenance_invalid),updated_by:E(e.updated_by),updated_at:E(e.updated_at),env_set:Bf(e.env_set),env_clear:vr(e.env_clear),shared_host_safe:e.shared_host_safe===!0?!0:void 0,assert_stdout_contains:vr(e.assert_stdout_contains),assert_stdout_regex:vr(e.assert_stdout_regex),assert_stderr_contains:vr(e.assert_stderr_contains),assert_stderr_regex:vr(e.assert_stderr_regex),assert_stdout_min_lines:En(e.assert_stdout_min_lines),assert_json_field_equals:Bf(e.assert_json_field_equals),assert_json_field_gte:V0(e.assert_json_field_gte),note:e.note?.trim()||void 0};return Zo(t),t}function Y0(e){if(!(!e||e.length===0))return[...e].map(t=>({path:Sn(t.path),scope:t.scope,note:t.note?.trim()||void 0})).sort((t,n)=>{let r=t.scope.localeCompare(n.scope);if(r!==0)return r;let o=t.path.localeCompare(n.path);return o!==0?o:(t.note??"").localeCompare(n.note??"")})}function E(e){if(typeof e!="string")return;let t=e.trim();return t.length>0?t:void 0}function X0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.id),i=E(r.kind);if(!o||!i)continue;let s={id:o,kind:i},a=E(r.note);a&&(s.note=a),r.required_before_step===!0&&(s.required_before_step=!0),t.push(s)}return t.length>0?t:void 0}function J0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:Sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function Z0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.command),i=E(r.path);if(!o&&!i)continue;let s={};o&&(s.command=o),i&&(s.path=Sn(i));let a=E(r.note);a&&(s.note=a),t.push(s)}return t.length>0?t:void 0}function Q0(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.path);if(!o)continue;let i={path:Sn(o)};(r.scope==="project"||r.scope==="global")&&(i.scope=r.scope);let s=E(r.note);s&&(i.note=s),t.push(i)}return t.length>0?t:void 0}function ek(e){if(e===null||typeof e!="object")return;let t=e,n=E(t.id),r=E(t.title),o=E(t.status),i=o&&a0.has(o)?o:void 0,s=bo(t.order)??Number.NaN,a=typeof t.created_at=="string"?t.created_at:"",c=typeof t.updated_at=="string"?t.updated_at:"";if(!n||!r||!i||!Number.isFinite(s)||!a||!c)return;let d={id:n,order:s,title:r,status:i,created_at:a,updated_at:c};return tk(d,t),d}function tk(e,t){let n=[["body","body"],["owner","owner"],["evidence","evidence"],["blocked_reason","blocked_reason"],["superseded_by","superseded_by"]];for(let[i,s]of n){let a=E(t[s]);a&&(e[i]=a)}let r=typeof t.completed_at=="string"?t.completed_at:void 0;r&&r.length>0&&(e.completed_at=r);let o=[["linked_items","linked_items",X0],["files","files",J0],["tests","tests",Z0],["docs","docs",Q0]];for(let[i,s,a]of o){let c=a(t[s]);c&&(e[i]=c)}}function nk(e){if(!Array.isArray(e))return;let t=e.flatMap(n=>{let r=ek(n);return r?[r]:[]});return t.sort((n,r)=>n.order-r.order),t.length>0?t:void 0}function rk(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.decision);if(!o||!i||!s)continue;let a={ts:o,author:i,decision:s},c=E(r.rationale);c&&(a.rationale=c);let d=E(r.evidence);d&&(a.evidence=d);let l=E(r.step_id);l&&(a.step_id=l),t.push(a)}return t.length>0?t:void 0}function ok(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=typeof r.ts=="string"?r.ts:"",i=typeof r.author=="string"?r.author:"",s=E(r.text);if(!o||!i||!s)continue;let a={ts:o,author:i,text:s},c=E(r.step_id);c&&(a.step_id=c),t.push(a)}return t.length>0?t:void 0}function ik(e){if(!Array.isArray(e))return;let t=[];for(let n of e){if(n===null||typeof n!="object")continue;let r=n,o=E(r.text);if(!o)continue;let i={text:o},s=E(r.command);s&&(i.command=s);let a=E(r.expected);a&&(i.expected=a),t.push(i)}return t.length>0?t:void 0}function sk(e){if(!e)return;let t=Object.entries(e).map(([n,r])=>[n.trim(),r.trim()]).filter(([n,r])=>n.length>0&&r.length>0).sort((n,r)=>n[0].localeCompare(r[0]));if(t.length!==0)return Object.fromEntries(t)}function kn(e){let t=0;for(;t<e.length&&e[t]===`
4
+ `;)t+=1;return e.slice(t).trimEnd()}function ak(e){if(e===void 0)return;if(typeof e=="number")return e;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(uo.includes(t))return t}function ck(e){if(e===void 0)return;let t=e.trim().toLowerCase();if(t==="med")return"medium";if(lo.includes(t))return t}function Er(e){return e||void 0}function dk(e,t){let n=e,r=t;for(let[o,i]of Object.entries(r))Ua(o)||Object.prototype.hasOwnProperty.call(n,o)||i===void 0||(n[o]=i)}function lk(e,t){if(!t?.fieldRegistry)return;let n=e;for(let r of t.fieldRegistry.definitions){let o=n[r.metadata_key];o!==void 0&&(n[r.metadata_key]=wr(r,o,`metadata field "${r.metadata_key}"`,"metadata"))}}function uk(e,t){if(!t||t.unknownFieldPolicy==="allow")return;let n=Qf(t),r=Object.keys(e).filter(o=>!n.has(o)).sort((o,i)=>o.localeCompare(i));r.length>0&&t.unknownFieldPolicy==="reject"&&Qe(`unknown schema fields are not allowed: ${r.join(", ")}`),r.length>0&&t.onWarning?.(`item_unknown_schema_fields:${r.join(",")}`)}function Qo(e,t={}){let n=Jf(t),r=Yo(e.status,n?.statusRegistry)??e.status,o=Array.from(new Set((Array.isArray(e.tags)?e.tags:[]).filter(s=>typeof s=="string").map(s=>s.trim().toLowerCase()).filter(Boolean))).sort((s,a)=>s.localeCompare(a)),i={id:e.id,title:e.title,description:e.description,type:e.type,pm_format_version:Hf(e.pm_format_version),source_type:E(e.source_type),type_options:sk(e.type_options),status:r,priority:e.priority,tags:o,created_at:e.created_at,updated_at:e.updated_at,dependencies:C0(e.dependencies),comments:xa(e.comments),notes:xa(e.notes),learnings:xa(e.learnings),files:j0(e.files),tests:q0(e.tests),test_runs:L0(e.test_runs),docs:Y0(e.docs),deadline:Er(e.deadline),reminders:N0(e.reminders),events:P0(e.events),closed_at:Er(e.closed_at),completed_at:Er(e.completed_at),assignee:E(e.assignee),claim_principal:E(e.claim_principal),source_owner:E(e.source_owner),author:Er(e.author),estimated_minutes:e.estimated_minutes,acceptance_criteria:e.acceptance_criteria??void 0,design:e.design??void 0,external_ref:e.external_ref??void 0,definition_of_ready:E(e.definition_of_ready),order:e.order,goal:E(e.goal),objective:E(e.objective),value:E(e.value),impact:E(e.impact),outcome:E(e.outcome),why_now:E(e.why_now),parent:E(e.parent),reviewer:E(e.reviewer),risk:e.risk??void 0,confidence:ak(e.confidence),sprint:E(e.sprint),release:E(e.release),blocked_by:E(e.blocked_by),blocked_reason:E(e.blocked_reason),unblock_note:E(e.unblock_note),reporter:E(e.reporter),severity:ck(e.severity),environment:E(e.environment),repro_steps:E(e.repro_steps),resolution:E(e.resolution),expected_result:E(e.expected_result),actual_result:E(e.actual_result),affected_version:E(e.affected_version),fixed_version:E(e.fixed_version),component:E(e.component),regression:e.regression,customer_impact:E(e.customer_impact),close_reason:Er(e.close_reason),plan_mode:E(e.plan_mode),plan_scope:E(e.plan_scope),plan_harness:E(e.plan_harness),plan_resume_context:E(e.plan_resume_context),plan_steps:nk(e.plan_steps),plan_decisions:rk(e.plan_decisions),plan_discoveries:ok(e.plan_discoveries),plan_validation:ik(e.plan_validation)};return dk(i,e),lk(i,n),uk(i,n),Zo(i),i}function em(e){return A(e,Ve)}function fk(e){let t=0,n=!1,r=!1;for(let o=0;o<e.length;o+=1){let i=e[o];if(n){if(r){r=!1;continue}if(i==="\\"){r=!0;continue}i==='"'&&(n=!1);continue}if(i==='"'){n=!0;continue}if(i==="{"){t+=1;continue}if(i==="}"&&(t-=1,t===0))return o}return-1}function mk(e){if(!e.startsWith("{"))return{frontMatter:"",body:e};let t=fk(e);if(t<0)return{frontMatter:"",body:e};let n=e.slice(0,t+1),r=e.slice(t+1).replace(/^\r?\n+/,"");return{frontMatter:n,body:r}}function pk(e){let t=e.charCodeAt(0)===65279?e.slice(1):e,n=t.match(/^[ \t]*---[ \t]*(?:\r?\n|$)/);if(!n)return{content:t,stripped:!1};let r=n[0].length;for(;r<t.length;){let o=t.indexOf(`
5
+ `,r),i=o===-1?t.length:o,s=t.slice(r,i).replace(/\r$/,""),a=o===-1?i:i+1;if(s.trim()==="---")return{content:t.slice(a).replace(/^\s+/,""),stripped:!0};r=a}return{content:t,stripped:!1}}function $a(e,t){return Qo(e,{...t,onWarning:void 0})}function _k(e,t,n={}){let r=pk(e);r.stripped&&n.onWarning?.("json_markdown_leading_yaml_frontmatter_ignored");let{frontMatter:o,body:i}=mk(r.content);o||(e.trimStart().startsWith("{")&&kr("json_markdown","JSON front matter is not valid JSON"),kr("json_markdown","JSON Markdown item document is missing JSON front matter"));let s;try{s=JSON.parse(o)}catch{kr("json_markdown","JSON front matter is not valid JSON")}return Zf(s,n.requireSupportedFormat),Ma(s,t),{metadata:$a(s,n),body:kn(i)}}function yk(e,t,n={}){let r;try{r=Ca(e).value}catch{kr("toon","TOON item document is not valid TOON")}O(typeof r=="object"&&r!==null&&!Array.isArray(r),"TOON item document must be an object");let o=r;if(Zf(Object.prototype.hasOwnProperty.call(o,"front_matter")?o.front_matter:o,n.requireSupportedFormat),!Xf.some(a=>Object.prototype.hasOwnProperty.call(o,a))&&!Object.prototype.hasOwnProperty.call(o,"front_matter")&&kr("toon","TOON input does not have the shape of an item document"),Object.prototype.hasOwnProperty.call(o,"front_matter"))return Ma(o.front_matter,t),O(o.body===void 0||typeof o.body=="string","TOON item document body must be a string"),{metadata:$a(o.front_matter,n),body:kn(typeof o.body=="string"?o.body:"")};let{body:i,...s}=o;return O(i===void 0||typeof i=="string","TOON item document body must be a string"),Ma(s,t),{metadata:$a(s,n),body:kn(typeof i=="string"?i:"")}}function hk(e,t={}){let n=Qo(e.metadata,t),r=em(n),o=kn(e.body??"");La(JSON.parse(JSON.stringify(r))),La({body:o});let i=JSON.stringify(r,null,2);return o?`${i}
6
6
 
7
7
  ${o}
8
8
  `:`${i}
9
- `}var dk=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function Da(e,t){return typeof e=="string"?zf(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Hf(e.map((n,r)=>()=>Da(n,`${t}[${r}]`))):Hf(Object.entries(e).map(([n,r])=>()=>{let o=t?`${t}.${n}`:n;return zf(n,`${o} (key)`)??Da(r,o)}))}function zf(e,t){let n=e.search(dk);return n<0?null:{path:t,index:n}}function Hf(e){for(let t of e){let n=t();if(n!==null)return n}return null}function Pa(e){let t=Da(e,"");if(t!==null)throw new g(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function lk(e,t={}){let n=Qo(e.metadata,t),r=Yf(n),o=En(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));Pa(s);let a=YE(s),c;try{c=Oa(a).value}catch(d){throw new g("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:d instanceof Error?d.message:String(d)})}if(!Lf(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!Lf(s[u],d[u]))??"document";throw new g(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:l,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
10
- `}function VM(e,t={}){let n=Yo(e);if(n)throw new g(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Wf(t);return r==="toon"?ak(e,o,t):sk(e,o,t)}function BM(e,t={}){return(t.format??"toon")==="toon"?lk(e,t):ck(e,t)}function Sn(e,t={}){return{metadata:Qo(e.metadata,t),body:En(e.body??"")}}(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]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();function Xf(e){return e}(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]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();var Jf=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],Qf=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default","transaction_abandon"],$a={"init:type-preset":"init:type_preset"},Zf=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],KM={version:1,item:Jf,workspace:Qf,aliases:$a,patterns:Zf,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},uk=new Set([...Jf,...Qf]),fk=Zf.map(e=>new RegExp(e,"u"));function em(e){return Object.hasOwn($a,e)?$a[e]:e}function YM(e){let t=em(e);if(uk.has(t)||fk.some(n=>n.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function tm(e){let t=em(e),n=t.indexOf(":"),r=n<0?t:t.slice(0,n),o=n<0||n<t.length-1&&!/[\s\p{C}]/u.test(t.slice(n+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(r)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{AsyncLocalStorage as mk}from"node:async_hooks";(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]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var La=new mk,nm=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function Zo(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Rt(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=Zo(n.id,128),o=Zo(n.parent_id,128);if(r===void 0||!nm.test(r)||o!==void 0&&!nm.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=Zo(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function On(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=Zo(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function pk(e,t,n){let r=La.getStore(),o=On({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Rt(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...On(r?.provenance),...o,...On(e?.provenance)},a=Rt(e?.episode,!1)??Rt(n,!1)??i??Rt(r?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function Fa(e,t){return pk(e.session_context,t,e.client_info?.episode)??{}}function QM(e,t){let n=La.getStore(),r=Rt(e.episode,!0),o=Rt(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...On(n?.provenance),...On(e.provenance)};return La.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function ZM(e){let t=On(e.provenance),n=Rt(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{constants as bk}from"node:fs";import te from"node:fs/promises";import Se from"node:path";import{createHash as wk,randomUUID as ii}from"node:crypto";import ei from"node:fs/promises";import ke 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]="f1eb25ad-08b8-5826-9ec1-7b0a7a22d277")}catch{}})();var om="lock_path_unsafe";function _k(e,t){return ke.relative(e,t).split(ke.sep).join("/")}function yk(e,t){return e==="lock_entry_symlink"?`Remove the symlinked lock entry ${t} (pm neither follows nor deletes it), then retry the same operation.`:e==="lock_directory_replaced"?`Restore ${t} as a real directory inside the tracker, then retry the same operation. The lock file created while it was replaced stays where the replacement pointed, because pm never deletes outside the tracker; remove it there if it is not wanted.`:"Replace the symlinked or replaced lock directory with a real directory inside the tracker (for example: remove the link, then let pm recreate locks/), then retry the same operation."}function Sr(e){let t=e.component??ke.dirname(e.lockPath),n=_k(e.pmRoot,t);return new g(`Refused to acquire lock ${e.id}: ${n} is not a real directory inside the tracker (${e.reason}). Locks are never created through a symlinked or replaced lock directory.`,h.CONFLICT,{code:"lock_path_unsafe",item_id:e.id,reason:e.reason,lock_component:n,required:yk(e.reason,n)})}function rm(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ti(e,t,n,r=!0){let o=ke.resolve(e),i=ke.dirname(ke.resolve(t)),s=ke.relative(o,i);if(s===".."||s.startsWith(`..${ke.sep}`)||ke.isAbsolute(s))throw Sr({pmRoot:o,lockPath:t,id:n,reason:"lock_path_outside_tracker",component:i});let a=o,c=null;for(let l of s===""?[]:s.split(ke.sep)){a=ke.join(a,l);let u;try{u=await ei.lstat(a,{bigint:!0})}catch(f){if(r&&Z(f))return null;throw f}if(u.isSymbolicLink())throw Sr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_symlink",component:a});if(!u.isDirectory())throw Sr({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_not_directory",component:a});c={dev:u.dev,ino:u.ino}}if(c!==null)return c;let d=await ei.stat(o,{bigint:!0});return{dev:d.dev,ino:d.ino}}async function im(e,t,n){let r;try{r=await ei.lstat(t)}catch{return}if(r.isSymbolicLink())throw Sr({pmRoot:e,lockPath:t,id:n,reason:"lock_entry_symlink",component:t})}async function sm(e){let t=await e.handle.stat({bigint:!0}),n={dev:t.dev,ino:t.ino},r=!1;try{let o=await ti(e.pmRoot,e.lockPath,e.id,!1);if(rm(e.directory,o)){let i=await ei.lstat(e.lockPath,{bigint:!0});r=!i.isSymbolicLink()&&rm(n,i)}}catch{r=!1}if(!r)throw Sr({pmRoot:e.pmRoot,lockPath:e.lockPath,id:e.id,reason:"lock_directory_replaced"})}import Ua from"node:fs/promises";import{createHash as hk}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]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();function am(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function gk(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!am(t,"ESRCH")}}function cm(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function An(e){try{return cm(await Ua.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function Or(e=process.pid){let t=await An(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function Ar(e,t,n){if(!gk(e.pid))return!1;let r=await An(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function dm(){try{let[e,t]=await Promise.all([Ua.readFile("/proc/sys/kernel/random/boot_id","utf8"),Ua.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:hk("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function za(){let[e,t]=await Promise.all([dm(),An(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function ni(e){if(!e||typeof e.pid!="number"||!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host_identity!="string"||typeof e.process_start_identity!="string"||!/^\d+$/u.test(e.process_start_identity))return"unknown";let t=await dm();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(r){return am(r,"ESRCH")?"dead":"unknown"}let n=await An(e.pid);return n===null?"unknown":n===e.process_start_identity?"alive":"dead"}(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]="54aee8ec-9ef4-54d4-92fa-f4104b3ec4cc")}catch{}})();function vk(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:n.host_identity,process_start_identity:n.process_start_identity},warnings:[]}}async function xt(e,t=!0){try{let n=await te.readFile(e,"utf8");return t&&await gn({path:e,scope:"project"}),vk(n)}catch(n){return Z(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function Ek(e,t,n=process.platform){if(et(e,"EEXIST"))return!0;if(!et(e,"EPERM")&&!et(e,"EACCES")&&!et(e,"EBUSY"))return!1;try{return await te.lstat(t),!0}catch(r){if(n!=="win32"||!Z(r)&&!et(r,"EPERM")&&!et(r,"EACCES")&&!et(r,"EBUSY"))return!1}try{return await te.access(Se.dirname(t),bk.W_OK),!0}catch{return!1}}async function pm(e,t){await zo({path:e,scope:"project",op:t})}async function kk(e,t,n,r=ii()){return{...await za(),id:e,pid:process.pid,owner:t,token:r,created_at:Te(),ttl_seconds:n}}async function Sk(e,t,n,r,o,i,s){let a=await ti(e,t,n);s&&a===null&&await te.mkdir(Se.dirname(t),{recursive:!0});let c=await di(t,n);if(c===null)throw await te.access(Se.dirname(t)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let d;try{let l=await ti(e,t,n,!1),u=await te.open(t,"wx");try{await sm({pmRoot:e,lockPath:t,id:n,handle:u,directory:l})}catch(f){throw await u.close(),f}try{try{let f=await kk(n,r,o,i);d=f.created_at,await u.writeFile(`${JSON.stringify(f,null,2)}
11
- `,"utf8")}finally{await u.close()}}catch(f){throw await Va(t,"lock:release"),f}}finally{await c()}return await pm(t,"lock:create"),d}async function Va(e,t){try{return await te.unlink(e),await pm(e,t),!0}catch{return!1}}async function Ok(e,t,n,r){let o=performance.now(),i=si;for(;;){let s=await di(e,t);if(s!==null){try{let d=await xt(e,!1);Ha(d.info,t,n,r)&&await Va(e,"lock:release")}finally{await s()}return}let a=await xt(e,!1);if(!Ha(a.info,t,n,r))return;let c=performance.now()-o;if(c>=ri)return;await ci(Math.min(i,ri-c)),i=Math.min(i*2,ai)}}function Ha(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function _m(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}async function ym(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await ni(e)==="dead"}async function hm(e,t){return _m(e,t)||await ym(e)}async function gm(e,t,n){let{info:r}=await xt(Ss(e,t),!1);return r!==null&&r.owner.startsWith(n)&&!await hm(r,r.ttl_seconds)}function Ak(e){return e?.owner?` (owner ${e.owner})`:""}var si=25,ai=200,bm=250,Ik=12e4,Tk=3,Ck=".stale-cleanup",wm="owner.json",vm=1e4,ri=vm+ai;function qa(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function Rk(e){let t=process.env.PM_LOCK_WAIT_MS,n=qa(t);if(n!==void 0)return n;let r=qa(e);return r!==void 0?r:0}function xk(e,t){return Math.min(Rk(e),t??1/0)}function ci(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}async function Em(e,t,n,r=0){n=Math.floor(n);let o=await ni(t),i=r>0?` across ${r} owner handoff(s)`:"",s=n>0?` after waiting ${n}ms${i}`:"";return new g(`Item ${e} is locked${Ak(t)} (owner process ${o})${s}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:bm,...n>0?{waited_ms:n,owner_handoffs:r}:{}}})}function Nk(e,t){let n=performance.now(),r=n,o,i=0;return{startedAtMs:n,observe(s){let a=performance.now(),c=Pk(s);o!==void 0&&c!==o&&(i+=1,r=a),o=c;let d=a-n,l=a-r;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function Dk(e,t,n){return n!=="progress"||t!==void 0?e:Math.max(e,Ik)}function Pk(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function Mk(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function jk(e,t,n,r){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(r==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=n===null?"the lock no longer exists":`it is now held by ${n.owner} since ${n.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function lm(e,t,n,r){let{summary:o,required:i}=jk(e,t,n,r);return new g(`${o} Nothing was written.`,h.CONFLICT,{code:"lock_lost",item_id:e,reason:r,lease:Mk(t),current_owner:n===null?null:{owner:n.owner,pid:n.pid,created_at:n.created_at,ttl_seconds:n.ttl_seconds},required:i,recovery:{retry_after_ms:bm}})}async function $k(e,t){let n=performance.now(),r=si;for(;;){let o=await di(e,t);if(o!==null)return o;let i=performance.now()-n;if(i>=ri)return null;await ci(Math.min(r,ri-i)),r=Math.min(r*2,ai)}}async function Lk(e,t,n,r){let o=await $k(e,t);if(o===null){let i=await xt(e,!1);throw lm(t,n,i.info,"fence_gate_unavailable")}try{let i=await xt(e,!1);if(!Ha(i.info,t,n.owner,n.token))throw lm(t,n,i.info,i.info===null?"lease_released":"lease_taken_over");return await r()}finally{await o()}}function Fk(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function Uk(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new g(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function zk(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,host_identity:n.host_identity,...typeof i=="string"?{process_start_identity:i}:{}}}async function oi(e){try{return zk(await te.readFile(Se.join(e,wm),"utf8"))}catch(t){return Z(t)?null:void 0}}async function Ba(e){try{return await te.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function um(e,t){let n=await oi(e);for(let r=0;n===void 0&&r<3;r+=1)await ci(si),n=await oi(e);!n||n.token!==t||await Ba(e)}async function fm(e){try{await te.mkdir(e)}catch(n){return et(n,"EEXIST"),null}let t={...await Or(),host_identity:(await za()).host_identity,token:ii()};try{await te.writeFile(Se.join(e,wm),`${JSON.stringify(t)}
12
- `,"utf8")}catch{return await Ba(e),null}return t}async function mm(e,t){let n=Se.join(Se.dirname(e),"recoveries"),r=wk("sha256").update(t).digest("hex");try{return await te.mkdir(n,{recursive:!0}),(await oi(e))?.token!==t?!1:(await te.rename(e,Se.join(n,`gate-${r}`)),!0)}catch{return!1}}async function Hk(e){let t;try{let r=await te.stat(e);t=Date.now()-r.mtimeMs}catch(r){return Z(r)}let n=await oi(e);if(n===void 0)return!1;if(n!==null){if(await ni(n)==="dead")return mm(e,n.token);if(n.host_identity!==void 0)return!1}return t<=vm||n!==null&&await Ar(n,t,Number.POSITIVE_INFINITY)?!1:n!==null?mm(e,n.token):Ba(e)}async function di(e,t){let n=`${e}${Ck}`,r=await fm(n);if(r!==null)return async()=>um(n,r.token);if(!await Hk(n))return null;let o=await fm(n);return o===null?null:async()=>um(n,o.token)}async function qk(e,t){let n=Se.join(Se.dirname(e),"recoveries");await te.mkdir(n,{recursive:!0}),await te.writeFile(Se.join(n,`${ii()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Te(),lock:JSON.parse(t)})}
13
- `,{encoding:"utf8",flag:"wx",mode:384})}async function Vk(e){let t=await di(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await xt(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};let r=await ym(n.info);if(!_m(n.info,e.ttlSeconds)&&!r)return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Uk(e.id,n,e.force||r,e.forceRequiredForStaleLock),e.staleRemovals>=Tk)throw await Em(e.id,n.info,performance.now()-e.startedAtMs);return r&&await qk(e.lockPath,JSON.stringify(n.info)),{lockInfo:n,shouldRetryCreate:await Va(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function Bk(e,t,n,r){if(e instanceof g&&e.code===om)throw e;if(!await Ek(e,n))throw new g(`Failed to acquire lock for ${r}: ${Dl(e)}`,h.GENERIC_FAILURE);await im(t,n,r)}async function fe(e,t,n,r,o=!1,i=!0,s,a={}){return(await Wk(e,t,n,r,o,i,s,a)).release}async function Wk(e,t,n,r,o=!1,i=!0,s,a={}){let c=qa(a.maxWaitMs),d=await bn("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let T=Fk(d.result);if(T)return{release:async()=>{await Promise.resolve(T()),await bn("lock_release",{pm_root:e,id:t,owner:r})},fence:G=>G()}}let l=Ss(e,t),u=xk(s,c),f=Dk(u,c,a.waitPolicy),m=Nk(u,f),_=m.startedAtMs,y=0,b=si,v=ii();for(;;)try{let T=await Sk(e,l,t,r,n,v,a.createParentDirectories!==!1),G={owner:r,token:v,acquiredAt:T,ttlSeconds:n};return{release:async()=>{await Ok(l,t,r,v),await bn("lock_release",{pm_root:e,id:t,owner:r})},fence:ce=>Lk(l,t,G,ce)}}catch(T){await Bk(T,e,l,t);let G=await xt(l);if(await hm(G.info,n)){let de=await Vk({lockPath:l,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:y,waitBudgetMs:u,startedAtMs:_,fallbackLockInfo:G});if(G=de.lockInfo,de.staleRemovalCounted&&(y+=1),de.shouldRetryCreate)continue}let ce=m.observe(G.info);if(ce.exhausted)throw await Em(t,G.info,u===0?0:ce.elapsedMs,ce.ownerHandoffs);await ci(Math.min(b,ce.remainingMs)),b=Math.min(b*2,ai)}}import{createHash as km}from"node:crypto";import{existsSync as Wa,promises as Sm,readFileSync as Gk}from"node:fs";import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();var Kk="session.json";function Ga(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Om(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Ga(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Ga(c,128)),a=t.focused_item_id===void 0||Ga(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function Yk(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=Om(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Ka(e){return Re.join(Os(e),Kk)}async function Am(e){try{let t=await Sm.readFile(Ka(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=Yk(r.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function Ya(e,t){let n=await fe(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let r=await Am(e);t(r);let o=Ka(e);await Sm.mkdir(Re.dirname(o),{recursive:!0}),await bt(o,JSON.stringify(r))}finally{await n()}}function Xa(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${km("sha256").update(e).digest("hex").slice(0,24)}`}function Ja(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function Qa(e){let t=[...new Set(e)].sort((r,o)=>r.localeCompare(o));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${km("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function Za(e,t,n){await Ya(e,r=>{let o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete r.semantic_attribution:r.semantic_attribution=o})}async function Nj(e){let t=Xa(e.principal);await Za(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??Qa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Ja([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function Dj(e){let t=Xa(e.principal);await Za(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??Qa(r),confidence:o?"high":"medium",evidence:Ja([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function Pj(e){let t=Xa(e.principal);await Za(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??Qa(r),confidence:o?"high":"medium",rule_version:"v2",evidence:Ja([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function Xk(e,t){let n=t.PM_PATH?.trim();if(n){let o=Re.resolve(e,n);if(Wa(Re.join(o,"settings.json")))return o;let i=Re.join(o,".agents","pm");if(Wa(Re.join(i,"settings.json")))return i}let r=Re.resolve(e);for(let o=0;o<32;o+=1){let i=Re.join(r,".agents","pm");if(Wa(Re.join(i,"settings.json")))return i;let s=Re.dirname(r);if(s===r)break;r=s}}function Im(e){if(!e.key)return;let t=Xk(e.cwd,e.env);if(t)try{let n=JSON.parse(Gk(Ka(t),"utf8"));return Om(n.semantic_attribution?.[e.key])}catch{return}}async function Mj(e){return(await Am(e)).focused_item}async function jj(e,t){await Ya(e,n=>{n.focused_item=t})}async function $j(e){await Ya(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as oc}from"node:async_hooks";import{createHash as Jk}from"node:crypto";import me from"node:fs";import xm from"node:os";import Pt 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]="a69b86e2-6633-5abc-81b7-6a54a592d36c")}catch{}})();var ic=["model","effort","role","topic","version"],fi=new oc,Nm=new oc,mi=new oc,sc=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Dm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),Qk=Object.freeze({...Dm,max_bytes:4194304}),ec=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function Zk(e){let t=nt(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?Qk:Dm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var Pm=Object.freeze(sc.filter(e=>e.harness!=="ci").map(Zk).sort((e,t)=>e.harness.localeCompare(t.harness))),Dt=new Map,In=new Map;function q(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function tt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function nt(e){let t=e.harness.trim().toLowerCase();if(!ec.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:tt(e.environment_keys),model_environment_keys:tt(e.model_environment_keys),session_environment_keys:tt(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),tt(r)]).filter(([n])=>ec.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&ec.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:tt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:tt(e.argv_markers).map(n=>n.toLowerCase()),client_names:tt(e.client_names).map(n=>n.toLowerCase())}}var Mm=sc.map(nt);function eS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function ui(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(n=>n.length>0).includes(t)||e.trim().toLowerCase()===t}function ac(e=[]){let t=new Map(sc.filter(o=>o.harness!=="ci").map(o=>[o.harness,nt(o)]));for(let{adapter:o}of Dt.values())t.set(o.harness,nt(o.descriptor));let n=[...t.values(),...Mm.filter(o=>o.harness==="ci"),...[...In.values()].map(o=>o.descriptor),...mi.getStore()?.descriptors??[],...e.map(nt)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function cc(e,t){for(let n of t??[]){let r=q(e[n]);if(r)return r.slice(0,256)}}function tS(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function jm(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return q(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return q(i.slice(s.length+1))?.slice(0,256)}}var nS=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Nt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return nS.has(n)?n:void 0}function tc(e,t){return q(e?.[t])?.slice(0,256)}var rS=1048576,rc=4194304,li=new Map,Tm=Object.freeze({}),nc=new Map,Cm=Object.freeze({});function Rm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function oS(e){let t;try{t=JSON.parse(e)}catch{return Cm}let n=Rm(t);if(!n)return Cm;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=q(a.value.model)?.slice(0,256),s??=q(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Rm(c);d&&r.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function $m(e){try{return me.lstatSync(e).isFile()?"available":"missing"}catch(t){return be(t)?"missing":"failed"}}function iS(e,t){let n;try{n=me.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Pt.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:$m(i)}})}catch(o){return{status:be(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function Lm(e,t){let n=q(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let r=Pt.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Pt.join(e.home_dir??xm.homedir(),".claude","projects"),i=Pt.join(o,r,`${n}.jsonl`),s=q(e.session_file),a=s&&Pt.basename(s)===`${n}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=$m(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return iS(o,n)}function sS(e,t,n){let r=Lm(t,n);if(r.status==="available")try{let o=me.openSync(r.path,me.constants.O_RDONLY|me.constants.O_NOFOLLOW);try{let i=me.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=nc.get(s);if(a)return a[e];let c=Math.min(i.size,rS),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);me.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&me.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
9
+ `}var gk=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u;function ja(e,t){return typeof e=="string"?Wf(e,t):e===null||typeof e!="object"?null:Array.isArray(e)?Gf(e.map((n,r)=>()=>ja(n,`${t}[${r}]`))):Gf(Object.entries(e).map(([n,r])=>()=>{let o=t?`${t}.${n}`:n;return Wf(n,`${o} (key)`)??ja(r,o)}))}function Wf(e,t){let n=e.search(gk);return n<0?null:{path:t,index:n}}function Gf(e){for(let t of e){let n=t();if(n!==null)return n}return null}function La(e){let t=ja(e,"");if(t!==null)throw new g(`Item field ${t.path} contains an unpaired surrogate code unit at index ${t.index}; persisted item text requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:t.path,required:"Provide well-formed UTF-16 text: keep emoji and other astral characters whole and avoid lone \\uD800-\\uDFFF JSON escapes.",why:"Persisted item text must remain well-formed in every supported format; a lone surrogate can cause an unclassified encoder fault.",nextSteps:[`Repair the ${t.path} value (for example String.prototype.toWellFormed() or re-truncate on a character boundary) and retry.`,"Run pm <command> --help --json to review the text fields the command accepts."]})}function bk(e,t={}){let n=Qo(e.metadata,t),r=em(n),o=kn(e.body??""),i={...r,body:o},s=JSON.parse(JSON.stringify(i));La(s);let a=o0(s),c;try{c=Ca(a).value}catch(d){throw new g("Refusing to persist a TOON item document that the configured decoder cannot read back.",h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_error",format:"toon",required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:d instanceof Error?d.message:String(d)})}if(!qf(c,s)){let d=typeof c=="object"&&c!==null&&!Array.isArray(c)?c:{},l=Object.keys(s).find(u=>!qf(s[u],d[u]))??"document";throw new g(`Refusing to persist a lossy TOON item document; round-trip mismatch at field "${l}".`,h.GENERIC_FAILURE,{code:"item_document_roundtrip_failed",reason:"encode_decode_mismatch",format:"toon",field:l,required:"Upgrade or repair the TOON codec before retrying the mutation; no item bytes were written.",why:"The encoded document decoded to a value different from the canonical item payload."})}return`${a}
10
+ `}function i$(e,t={}){let n=Xo(e);if(n)throw new g(`Merge conflict markers detected in item document at line ${n.line} (${n.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"merge_conflict_markers_detected",reason:"merge_conflict",required:"Resolve merge-conflict markers in the item file before parsing or mutation commands.",why:"Partially merged documents can corrupt item metadata and history integrity.",examples:["git status","git add <resolved-file> && git commit"],nextSteps:["Resolve conflicts, save the file, then rerun the pm command."]});let r=t.format??"toon",o=Jf(t);return r==="toon"?yk(e,o,t):_k(e,o,t)}function s$(e,t={}){return(t.format??"toon")==="toon"?bk(e,t):hk(e,t)}function On(e,t={}){return{metadata:Qo(e.metadata,t),body:kn(e.body??"")}}(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]="82c79093-2a40-5b4c-8d41-637b0ae03c4f")}catch{}})();function tm(e){return e}(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]="7e894d1f-fe1a-53f2-9a29-4e9846a9f986")}catch{}})();var nm=["append","cancel","claim","close","comment_add","comment_edit","comment_delete","create","delete","docs_add","docs_remove","files_add","files_remove","files_discover","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","import","improvement_observe","learning_add","learning_edit","learning_delete","normalize","note_add","note_edit","note_delete","plan_create_metadata","plan_create_initial_step","plan_add_step","plan_reorder_step","plan_remove_step","plan_link_step","plan_unlink_step","plan_append_decision","plan_append_discovery","plan_append_validation","plan_resume","plan_approve","plan_materialize","plan_update_step","plan_complete_step","plan_block_step","policy_approve","policy_refused","release","reopen","restore","schema_migration","schema_migration_reference","test_run_track","tests_add","tests_remove","tests_update","update","update_audit","update_ownership_bypass","workspace_snapshot_restore","extension_migrations_apply","merge_reconcile"],rm=["history:author-acknowledge","settings:write","init:type_preset","templates:save","profile:apply-types","profile:apply-statuses","profile:apply-fields","profile:apply-config","schema:add-type","schema:remove-type","schema:add-status","schema:remove-status","schema:add-field","schema:remove-field","schema:apply-preset","schema:infer-types","schema:policy-put","schema:policy-remove","schema:policy-mode","assurance:bundle:apply","assurance:gate:verdict","telemetry:install_id","telemetry:first_run_prompt","telemetry:clear","item_format:auto_select_default","transaction_abandon"],za={"init:type-preset":"init:type_preset"},om=["^config:(?:set|unset):[a-z][a-z0-9_.:-]*$","^assurance:(?:measurement|invariant|gate):(?:put|remove)$","^schema_(?:rename_type|rename_status|remap_status|rename_field|remove_type|remove_status|remove_field)(?:_compensate)?$","^extension:[a-z][a-z0-9_-]*:[a-z][a-z0-9_]*$"],d$={version:1,item:nm,workspace:rm,aliases:za,patterns:om,read_policy:"preserve_original_operation",custom_operation_grammar:"extension:<package_name>:<snake_case_operation>",legacy_custom_operation_grammar:"lowercase segments separated by underscore, hyphen, colon, or dot; optional opaque colon-suffixed retry key",excluded_surfaces:["json_patch","on_write_hook","telemetry_span"]},wk=new Set([...nm,...rm]),vk=om.map(e=>new RegExp(e,"u"));function im(e){return Object.hasOwn(za,e)?za[e]:e}function l$(e){let t=im(e);if(wk.has(t)||vk.some(n=>n.test(t)))return t;throw new TypeError("Undeclared history operation; use a native contract identity or extension:<package_name>:<snake_case_operation>.")}function sm(e){let t=im(e),n=t.indexOf(":"),r=n<0?t:t.slice(0,n),o=n<0||n<t.length-1&&!/[\s\p{C}]/u.test(t.slice(n+1));if(/^[a-z][a-z0-9]*(?:[_.-][a-z0-9]+)*$/u.test(r)&&o)return t;throw new TypeError("History operation must use lowercase alphanumeric segments with an optional non-whitespace colon-suffixed retry key.")}import{AsyncLocalStorage as Ek}from"node:async_hooks";(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]="1fbb183b-c6d8-5834-b4cb-e4fb515572b9")}catch{}})();var Ha=new Ek,am=/^[A-Za-z0-9](?:[A-Za-z0-9._:-]{0,127})$/u;function ei(e,t){let n=typeof e=="string"?e.trim():"";return n.length>0?n.slice(0,t):void 0}function Rt(e,t){if(e===void 0)return;let n=typeof e=="object"&&e!==null?e:{},r=ei(n.id,128),o=ei(n.parent_id,128);if(r===void 0||!am.test(r)||o!==void 0&&!am.test(o)){if(t)throw new Error("Agent episode ids must be 1-128 letters, digits, dots, underscores, colons, or hyphens.");return}let i=ei(n.label,256);return{id:r,...i===void 0?{}:{label:i},...o===void 0?{}:{parent_id:o}}}function An(e){let t={};for(let[n,r]of Object.entries(e??{}).slice(0,32)){let o=n.trim().toLowerCase().slice(0,64),i=ei(r,256);/^[a-z][a-z0-9_-]{0,63}$/u.test(o)&&i!==void 0&&(t[o]=i)}return t}function kk(e,t,n){let r=Ha.getStore(),o=An({role:t.PM_AGENT_SESSION_ROLE,topic:t.PM_AGENT_SESSION_TOPIC}),i=Rt(t.PM_AGENT_EPISODE_ID===void 0?void 0:{id:t.PM_AGENT_EPISODE_ID,label:t.PM_AGENT_EPISODE_LABEL,parent_id:t.PM_AGENT_EPISODE_PARENT_ID},!1),s={...An(r?.provenance),...o,...An(e?.provenance)},a=Rt(e?.episode,!1)??Rt(n,!1)??i??Rt(r?.episode,!1);return Object.keys(s).length===0&&a===void 0?void 0:{...Object.keys(s).length===0?{}:{provenance:s},...a===void 0?{}:{episode:a}}}function qa(e,t){return kk(e.session_context,t,e.client_info?.episode)??{}}function m$(e,t){let n=Ha.getStore(),r=Rt(e.episode,!0),o=Rt(n?.episode,!1),i=r!==void 0&&r.parent_id===void 0&&o!==void 0?{...r,parent_id:o.id}:r,s={...An(n?.provenance),...An(e.provenance)};return Ha.run({...Object.keys(s).length===0?{}:{provenance:s},...i===void 0?o===void 0?{}:{episode:o}:{episode:i}},t)}function p$(e){let t=An(e.provenance),n=Rt(e.episode,!0);return{...n===void 0?{}:{PM_AGENT_EPISODE_ID:n.id,...n.label===void 0?{}:{PM_AGENT_EPISODE_LABEL:n.label},...n.parent_id===void 0?{}:{PM_AGENT_EPISODE_PARENT_ID:n.parent_id}},...t.role===void 0?{}:{PM_AGENT_SESSION_ROLE:t.role},...t.topic===void 0?{}:{PM_AGENT_SESSION_TOPIC:t.topic}}}import{constants as Tk}from"node:fs";import te from"node:fs/promises";import Se from"node:path";import{createHash as Ck,randomUUID as si}from"node:crypto";import ti from"node:fs/promises";import ke 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]="f1eb25ad-08b8-5826-9ec1-7b0a7a22d277")}catch{}})();var dm="lock_path_unsafe";function Sk(e,t){return ke.relative(e,t).split(ke.sep).join("/")}function Ok(e,t){return e==="lock_entry_symlink"?`Remove the symlinked lock entry ${t} (pm neither follows nor deletes it), then retry the same operation.`:e==="lock_directory_replaced"?`Restore ${t} as a real directory inside the tracker, then retry the same operation. The lock file created while it was replaced stays where the replacement pointed, because pm never deletes outside the tracker; remove it there if it is not wanted.`:"Replace the symlinked or replaced lock directory with a real directory inside the tracker (for example: remove the link, then let pm recreate locks/), then retry the same operation."}function Or(e){let t=e.component??ke.dirname(e.lockPath),n=Sk(e.pmRoot,t);return new g(`Refused to acquire lock ${e.id}: ${n} is not a real directory inside the tracker (${e.reason}). Locks are never created through a symlinked or replaced lock directory.`,h.CONFLICT,{code:"lock_path_unsafe",item_id:e.id,reason:e.reason,lock_component:n,required:Ok(e.reason,n)})}function cm(e,t){return e.dev===t.dev&&e.ino===t.ino}async function ni(e,t,n,r=!0){let o=ke.resolve(e),i=ke.dirname(ke.resolve(t)),s=ke.relative(o,i);if(s===".."||s.startsWith(`..${ke.sep}`)||ke.isAbsolute(s))throw Or({pmRoot:o,lockPath:t,id:n,reason:"lock_path_outside_tracker",component:i});let a=o,c=null;for(let l of s===""?[]:s.split(ke.sep)){a=ke.join(a,l);let u;try{u=await ti.lstat(a,{bigint:!0})}catch(f){if(r&&Q(f))return null;throw f}if(u.isSymbolicLink())throw Or({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_symlink",component:a});if(!u.isDirectory())throw Or({pmRoot:o,lockPath:t,id:n,reason:"lock_directory_not_directory",component:a});c={dev:u.dev,ino:u.ino}}if(c!==null)return c;let d=await ti.stat(o,{bigint:!0});return{dev:d.dev,ino:d.ino}}async function lm(e,t,n){let r;try{r=await ti.lstat(t)}catch{return}if(r.isSymbolicLink())throw Or({pmRoot:e,lockPath:t,id:n,reason:"lock_entry_symlink",component:t})}async function um(e){let t=await e.handle.stat({bigint:!0}),n={dev:t.dev,ino:t.ino},r=!1;try{let o=await ni(e.pmRoot,e.lockPath,e.id,!1);if(cm(e.directory,o)){let i=await ti.lstat(e.lockPath,{bigint:!0});r=!i.isSymbolicLink()&&cm(n,i)}}catch{r=!1}if(!r)throw Or({pmRoot:e.pmRoot,lockPath:e.lockPath,id:e.id,reason:"lock_directory_replaced"})}import Va from"node:fs/promises";import{createHash as Ak}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]="d1f829a5-70d6-5096-86f7-717440dd67d5")}catch{}})();function fm(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function Ik(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!fm(t,"ESRCH")}}function mm(e){let t=e.lastIndexOf(")");if(t<0)return null;let n=e.slice(t+2).trim().split(/\s+/u)[19];return n!==void 0&&/^\d+$/u.test(n)?n:null}async function In(e){try{return mm(await Va.readFile(`/proc/${e}/stat`,"utf8"))}catch{return null}}async function Ar(e=process.pid){let t=await In(e);return{pid:e,...t===null?{}:{process_start_identity:t}}}async function Ir(e,t,n){if(!Ik(e.pid))return!1;let r=await In(e.pid);return e.process_start_identity!==void 0&&r!==null?r===e.process_start_identity:t<=n}async function pm(){try{let[e,t]=await Promise.all([Va.readFile("/proc/sys/kernel/random/boot_id","utf8"),Va.readlink("/proc/self/ns/pid")]);return!/^[a-f0-9-]{36}\s*$/u.test(e)||!/^pid:\[\d+\]$/u.test(t)?null:Ak("sha256").update(`${e.trim()}:${t}`).digest("hex")}catch{return null}}async function Ba(){let[e,t]=await Promise.all([pm(),In(process.pid)]);return e!==null&&t!==null?{host_identity:e,process_start_identity:t}:{}}async function ri(e){if(!e||typeof e.pid!="number"||!Number.isSafeInteger(e.pid)||e.pid<=0||typeof e.host_identity!="string"||typeof e.process_start_identity!="string"||!/^\d+$/u.test(e.process_start_identity))return"unknown";let t=await pm();if(t===null||t!==e.host_identity)return"unknown";try{process.kill(e.pid,0)}catch(r){return fm(r,"ESRCH")?"dead":"unknown"}let n=await In(e.pid);return n===null?"unknown":n===e.process_start_identity?"alive":"dead"}(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]="54aee8ec-9ef4-54d4-92fa-f4104b3ec4cc")}catch{}})();function Rk(e){let t;try{t=JSON.parse(e)}catch{return{info:null,warnings:["lock_info_invalid_json"]}}if(typeof t!="object"||t===null||Array.isArray(t))return{info:null,warnings:["lock_info_invalid_shape"]};let n=t,r=n.id,o=n.pid,i=n.owner,s=n.token,a=n.created_at,c=n.ttl_seconds;return typeof r!="string"||typeof o!="number"||!Number.isFinite(o)||typeof i!="string"||s!==void 0&&(typeof s!="string"||s.trim().length===0)||typeof a!="string"||typeof c!="number"||!Number.isFinite(c)?{info:null,warnings:["lock_info_invalid_shape"]}:{info:{id:r,pid:o,owner:i,...typeof s=="string"?{token:s}:{},created_at:a,ttl_seconds:c,host_identity:n.host_identity,process_start_identity:n.process_start_identity},warnings:[]}}async function xt(e,t=!0){try{let n=await te.readFile(e,"utf8");return t&&await bn({path:e,scope:"project"}),Rk(n)}catch(n){return Q(n)?{info:null,warnings:[]}:{info:null,warnings:["lock_info_read_failed"]}}}function et(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}async function xk(e,t,n=process.platform){if(et(e,"EEXIST"))return!0;if(!et(e,"EPERM")&&!et(e,"EACCES")&&!et(e,"EBUSY"))return!1;try{return await te.lstat(t),!0}catch(r){if(n!=="win32"||!Q(r)&&!et(r,"EPERM")&&!et(r,"EACCES")&&!et(r,"EBUSY"))return!1}try{return await te.access(Se.dirname(t),Tk.W_OK),!0}catch{return!1}}async function bm(e,t){await Ho({path:e,scope:"project",op:t})}async function Nk(e,t,n,r=si()){return{...await Ba(),id:e,pid:process.pid,owner:t,token:r,created_at:Te(),ttl_seconds:n}}async function Dk(e,t,n,r,o,i,s){let a=await ni(e,t,n);s&&a===null&&await te.mkdir(Se.dirname(t),{recursive:!0});let c=await li(t,n);if(c===null)throw await te.access(Se.dirname(t)),Object.assign(new Error("Lock initialization is contended"),{code:"EEXIST"});let d;try{let l=await ni(e,t,n,!1),u=await te.open(t,"wx");try{await um({pmRoot:e,lockPath:t,id:n,handle:u,directory:l})}catch(f){throw await u.close(),f}try{try{let f=await Nk(n,r,o,i);d=f.created_at,await u.writeFile(`${JSON.stringify(f,null,2)}
11
+ `,"utf8")}finally{await u.close()}}catch(f){throw await Ka(t,"lock:release"),f}}finally{await c()}return await bm(t,"lock:create"),d}async function Ka(e,t){try{return await te.unlink(e),await bm(e,t),!0}catch{return!1}}async function Pk(e,t,n,r){let o=performance.now(),i=ai;for(;;){let s=await li(e,t);if(s!==null){try{let d=await xt(e,!1);Wa(d.info,t,n,r)&&await Ka(e,"lock:release")}finally{await s()}return}let a=await xt(e,!1);if(!Wa(a.info,t,n,r))return;let c=performance.now()-o;if(c>=oi)return;await di(Math.min(i,oi-c)),i=Math.min(i*2,ci)}}function Wa(e,t,n,r){return e?.id===t&&e.pid===process.pid&&e.owner===n&&e.token===r}function wm(e,t){let n=e?.created_at?Date.parse(e.created_at):Number.NaN;return(Number.isFinite(n)?Date.now()-n:Number.POSITIVE_INFINITY)>t*1e3}async function vm(e){return e!==null&&Number.isFinite(Date.parse(e.created_at))&&await ri(e)==="dead"}async function Em(e,t){return wm(e,t)||await vm(e)}async function km(e,t,n){let{info:r}=await xt(Os(e,t),!1);return r!==null&&r.owner.startsWith(n)&&!await Em(r,r.ttl_seconds)}function Mk(e){return e?.owner?` (owner ${e.owner})`:""}var ai=25,ci=200,Sm=250,$k=12e4,jk=3,Lk=".stale-cleanup",Om="owner.json",Am=1e4,oi=Am+ci;function Ga(e){if(typeof e=="string"){let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}if(typeof e=="number"&&Number.isFinite(e)&&e>=0)return Math.trunc(e)}function Fk(e){let t=process.env.PM_LOCK_WAIT_MS,n=Ga(t);if(n!==void 0)return n;let r=Ga(e);return r!==void 0?r:0}function Uk(e,t){return Math.min(Fk(e),t??1/0)}function di(e){let t=Math.max(1,Math.round(e*(.5+Math.random())));return new Promise(n=>setTimeout(n,t))}async function Im(e,t,n,r=0){n=Math.floor(n);let o=await ri(t),i=r>0?` across ${r} owner handoff(s)`:"",s=n>0?` after waiting ${n}ms${i}`:"";return new g(`Item ${e} is locked${Mk(t)} (owner process ${o})${s}`,h.CONFLICT,{code:"lock_conflict",item_id:e,reason:`lock_owner_${o}`,required:"Wait for the owner to release the lock, then retry the same operation. Set PM_LOCK_WAIT_MS to a larger bounded millisecond budget when contention is expected. Inspect stale receipts with pm gc --scope locks --dry-run.",recovery:{retry_after_ms:Sm,...n>0?{waited_ms:n,owner_handoffs:r}:{}}})}function zk(e,t){let n=performance.now(),r=n,o,i=0;return{startedAtMs:n,observe(s){let a=performance.now(),c=qk(s);o!==void 0&&c!==o&&(i+=1,r=a),o=c;let d=a-n,l=a-r;return{exhausted:e===0||l>=e||d>=t,elapsedMs:d,remainingMs:Math.min(e-l,t-d),ownerHandoffs:i}}}}function Hk(e,t,n){return n!=="progress"||t!==void 0?e:Math.max(e,$k)}function qk(e){return e===null?"released":e.token??`${e.pid}:${e.owner}:${e.created_at}`}function Vk(e){let t=Date.parse(e.acquiredAt)+e.ttlSeconds*1e3;return{owner:e.owner,acquired_at:e.acquiredAt,ttl_seconds:e.ttlSeconds,expires_at:new Date(t).toISOString()}}function Bk(e,t,n,r){let o=`the lease acquired at ${t.acquiredAt} (ttl ${t.ttlSeconds}s)`;if(r==="fence_gate_unavailable")return{summary:`Lock for ${e} could not be verified before commit: ${o} could not enter its commit fence because the stale-cleanup gate stayed held.`,required:"Retry the same operation; this writer's change was not committed. Inspect pm gc --scope locks --dry-run if the stale-cleanup gate stays held."};let i=n===null?"the lock no longer exists":`it is now held by ${n.owner} since ${n.created_at}`;return{summary:`Lock for ${e} was lost before commit: ${o} is no longer owned by this writer, and ${i}.`,required:"Re-read the item and apply the mutation again; this writer's change was not committed and the newer value was kept. Keep mutation work shorter than locks.ttl_seconds, or raise locks.ttl_seconds for long-running callbacks."}}function _m(e,t,n,r){let{summary:o,required:i}=Bk(e,t,n,r);return new g(`${o} Nothing was written.`,h.CONFLICT,{code:"lock_lost",item_id:e,reason:r,lease:Vk(t),current_owner:n===null?null:{owner:n.owner,pid:n.pid,created_at:n.created_at,ttl_seconds:n.ttl_seconds},required:i,recovery:{retry_after_ms:Sm}})}async function Wk(e,t){let n=performance.now(),r=ai;for(;;){let o=await li(e,t);if(o!==null)return o;let i=performance.now()-n;if(i>=oi)return null;await di(Math.min(r,oi-i)),r=Math.min(r*2,ci)}}async function Gk(e,t,n,r){let o=await Wk(e,t);if(o===null){let i=await xt(e,!1);throw _m(t,n,i.info,"fence_gate_unavailable")}try{let i=await xt(e,!1);if(!Wa(i.info,t,n.owner,n.token))throw _m(t,n,i.info,i.info===null?"lease_released":"lease_taken_over");return await r()}finally{await o()}}function Kk(e){if(typeof e=="function")return e;if(typeof e=="object"&&e!==null&&"release"in e){let t=e.release;return typeof t=="function"?t:null}return null}function Yk(e,t,n,r){if(!n&&r){let o=t.warnings.length>0?` (${t.warnings.join(",")})`:"";throw new g(`Item ${e} lock is stale${o}; rerun with --force when supported for this command`,h.CONFLICT)}}function Xk(e){let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t,r=n.pid,o=n.token,i=n.process_start_identity;return typeof r!="number"||!Number.isInteger(r)||r<=0||typeof o!="string"||o.length===0||i!==void 0&&(typeof i!="string"||!/^\d+$/u.test(i))?null:{pid:r,token:o,host_identity:n.host_identity,...typeof i=="string"?{process_start_identity:i}:{}}}async function ii(e){try{return Xk(await te.readFile(Se.join(e,Om),"utf8"))}catch(t){return Q(t)?null:void 0}}async function Ya(e){try{return await te.rm(e,{recursive:!0,force:!0}),!0}catch{return!1}}async function ym(e,t){let n=await ii(e);for(let r=0;n===void 0&&r<3;r+=1)await di(ai),n=await ii(e);!n||n.token!==t||await Ya(e)}async function hm(e){try{await te.mkdir(e)}catch(n){return et(n,"EEXIST"),null}let t={...await Ar(),host_identity:(await Ba()).host_identity,token:si()};try{await te.writeFile(Se.join(e,Om),`${JSON.stringify(t)}
12
+ `,"utf8")}catch{return await Ya(e),null}return t}async function gm(e,t){let n=Se.join(Se.dirname(e),"recoveries"),r=Ck("sha256").update(t).digest("hex");try{return await te.mkdir(n,{recursive:!0}),(await ii(e))?.token!==t?!1:(await te.rename(e,Se.join(n,`gate-${r}`)),!0)}catch{return!1}}async function Jk(e){let t;try{let r=await te.stat(e);t=Date.now()-r.mtimeMs}catch(r){return Q(r)}let n=await ii(e);if(n===void 0)return!1;if(n!==null){if(await ri(n)==="dead")return gm(e,n.token);if(n.host_identity!==void 0)return!1}return t<=Am||n!==null&&await Ir(n,t,Number.POSITIVE_INFINITY)?!1:n!==null?gm(e,n.token):Ya(e)}async function li(e,t){let n=`${e}${Lk}`,r=await hm(n);if(r!==null)return async()=>ym(n,r.token);if(!await Jk(n))return null;let o=await hm(n);return o===null?null:async()=>ym(n,o.token)}async function Zk(e,t){let n=Se.join(Se.dirname(e),"recoveries");await te.mkdir(n,{recursive:!0}),await te.writeFile(Se.join(n,`${si()}.json`),`${JSON.stringify({event:"owner_dead_recovery_attempt",recorded_at:Te(),lock:JSON.parse(t)})}
13
+ `,{encoding:"utf8",flag:"wx",mode:384})}async function Qk(e){let t=await li(e.lockPath,e.id);if(t===null)return{lockInfo:e.fallbackLockInfo,shouldRetryCreate:!1,staleRemovalCounted:!1};try{let n=await xt(e.lockPath);if(n.info===null&&n.warnings.length===0)return{lockInfo:n,shouldRetryCreate:!0,staleRemovalCounted:!1};let r=await vm(n.info);if(!wm(n.info,e.ttlSeconds)&&!r)return{lockInfo:n,shouldRetryCreate:!1,staleRemovalCounted:!1};if(Yk(e.id,n,e.force||r,e.forceRequiredForStaleLock),e.staleRemovals>=jk)throw await Im(e.id,n.info,performance.now()-e.startedAtMs);return r&&await Zk(e.lockPath,JSON.stringify(n.info)),{lockInfo:n,shouldRetryCreate:await Ka(e.lockPath,"lock:stale_remove"),staleRemovalCounted:!0}}finally{await t()}}async function eS(e,t,n,r){if(e instanceof g&&e.code===dm)throw e;if(!await xk(e,n))throw new g(`Failed to acquire lock for ${r}: ${Ll(e)}`,h.GENERIC_FAILURE);await lm(t,n,r)}async function fe(e,t,n,r,o=!1,i=!0,s,a={}){return(await tS(e,t,n,r,o,i,s,a)).release}async function tS(e,t,n,r,o=!1,i=!0,s,a={}){let c=Ga(a.maxWaitMs),d=await wn("lock_acquire",{pm_root:e,id:t,ttl_seconds:n,owner:r,force:o,force_required_for_stale_lock:i,...c===void 0?{}:{max_wait_ms:c}});if(d.handled){let T=Kk(d.result);if(T)return{release:async()=>{await Promise.resolve(T()),await wn("lock_release",{pm_root:e,id:t,owner:r})},fence:G=>G()}}let l=Os(e,t),u=Uk(s,c),f=Hk(u,c,a.waitPolicy),m=zk(u,f),_=m.startedAtMs,y=0,b=ai,v=si();for(;;)try{let T=await Dk(e,l,t,r,n,v,a.createParentDirectories!==!1),G={owner:r,token:v,acquiredAt:T,ttlSeconds:n};return{release:async()=>{await Pk(l,t,r,v),await wn("lock_release",{pm_root:e,id:t,owner:r})},fence:ce=>Gk(l,t,G,ce)}}catch(T){await eS(T,e,l,t);let G=await xt(l);if(await Em(G.info,n)){let de=await Qk({lockPath:l,id:t,ttlSeconds:n,force:o,forceRequiredForStaleLock:i,staleRemovals:y,waitBudgetMs:u,startedAtMs:_,fallbackLockInfo:G});if(G=de.lockInfo,de.staleRemovalCounted&&(y+=1),de.shouldRetryCreate)continue}let ce=m.observe(G.info);if(ce.exhausted)throw await Im(t,G.info,u===0?0:ce.elapsedMs,ce.ownerHandoffs);await di(Math.min(b,ce.remainingMs)),b=Math.min(b*2,ci)}}import{createHash as Tm}from"node:crypto";import{existsSync as Xa,promises as Cm,readFileSync as nS}from"node:fs";import Re from"node:path";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="06c9f6f4-c2f0-549c-9a0f-4f4269cc5f49")}catch{}})();var rS="session.json";function Ja(e,t){return typeof e=="string"&&e.length>0&&e.length<=t}function Rm(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=e,n=["implementer","planner","release-operator"].includes(String(t.role)),r=["high","medium"].includes(String(t.confidence)),o=Ja(t.topic,256),i=Array.isArray(t.evidence)&&t.evidence.length<=32&&t.evidence.every(c=>typeof c=="string"&&c.length<=128),s=Array.isArray(t.active_item_ids)&&t.active_item_ids.length<=64&&t.active_item_ids.every(c=>Ja(c,128)),a=t.focused_item_id===void 0||Ja(t.focused_item_id,128);if([n,r,o,i,s,a,t.rule_version==="v2"].every(Boolean))return t}function oS(e){if(e===null||typeof e!="object"||Array.isArray(e))return;let t=Object.entries(e).slice(0,128).flatMap(([n,r])=>{let o=Rm(r);return o&&n.length<=128?[[n,o]]:[]});return t.length>0?Object.fromEntries(t):void 0}function Za(e){return Re.join(As(e),rS)}async function xm(e){try{let t=await Cm.readFile(Za(e),"utf8"),n=JSON.parse(t);if(n===null||typeof n!="object"||Array.isArray(n))return{};let r=n,o=r.focused_item,i=oS(r.semantic_attribution);return typeof o=="string"&&o.trim().length>0?{focused_item:o,...i?{semantic_attribution:i}:{}}:i?{semantic_attribution:i}:{}}catch{return{}}}async function Qa(e,t){let n=await fe(e,"session-state",S.locks.ttl_seconds,"session-state",!1,!0,S.locks.wait_ms);try{let r=await xm(e);t(r);let o=Za(e);await Cm.mkdir(Re.dirname(o),{recursive:!0}),await bt(o,JSON.stringify(r))}finally{await n()}}function ec(e){return/#([a-f0-9]{24})$/u.exec(e.trim())?.[1]??`author-${Tm("sha256").update(e).digest("hex").slice(0,24)}`}function tc(e){return[...new Set(e.map(t=>t.trim()).filter(Boolean))].slice(0,32).map(t=>t.slice(0,128))}function nc(e){let t=[...new Set(e)].sort((r,o)=>r.localeCompare(o));if(t.length===1)return t[0];let n=`workset:${t.join("+")}`;return n.length<=256?n:`workset:${t.join("+").slice(0,230)}+${Tm("sha256").update(t.join("\0")).digest("hex").slice(0,12)}`}async function rc(e,t,n){await Qa(e,r=>{let o={...r.semantic_attribution},i=n(o[t]);i===void 0?delete o[t]:o[t]=i,Object.keys(o).length===0?delete r.semantic_attribution:r.semantic_attribution=o})}async function G$(e){let t=ec(e.principal);await rc(e.pmRoot,t,n=>{let r=[...new Set([...n?.active_item_ids??[],e.itemId])].slice(-64).sort((i,s)=>i.localeCompare(s)),o=n?.focused_item_id;return{role:"implementer",topic:o??nc(r),confidence:o?"high":"medium",rule_version:"v2",evidence:tc([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}async function K$(e){let t=ec(e.principal);await rc(e.pmRoot,t,n=>{if(!n)return;let r=n.active_item_ids.filter(i=>i!==e.itemId);if(r.length===0&&!n.focused_item_id)return;let o=n.focused_item_id;return{...n,role:"release-operator",topic:o??nc(r),confidence:o?"high":"medium",evidence:tc([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],`release:${e.itemId}`]),active_item_ids:r}})}async function Y$(e){let t=ec(e.principal);await rc(e.pmRoot,t,n=>{let r=n?.active_item_ids??[];if(!e.itemId&&r.length===0)return;let o=e.itemId;return{role:o?"planner":n.role,topic:o??nc(r),confidence:o?"high":"medium",rule_version:"v2",evidence:tc([...r.map(i=>`claim:${i}`),...o?[`focus:${o}`]:[],...(e.lineageIds??[]).map(i=>`lineage:${i}`)]),active_item_ids:r,...o?{focused_item_id:o}:{}}})}function iS(e,t){let n=t.PM_PATH?.trim();if(n){let o=Re.resolve(e,n);if(Xa(Re.join(o,"settings.json")))return o;let i=Re.join(o,".agents","pm");if(Xa(Re.join(i,"settings.json")))return i}let r=Re.resolve(e);for(let o=0;o<32;o+=1){let i=Re.join(r,".agents","pm");if(Xa(Re.join(i,"settings.json")))return i;let s=Re.dirname(r);if(s===r)break;r=s}}function Nm(e){if(!e.key)return;let t=iS(e.cwd,e.env);if(t)try{let n=JSON.parse(nS(Za(t),"utf8"));return Rm(n.semantic_attribution?.[e.key])}catch{return}}async function X$(e){return(await xm(e)).focused_item}async function J$(e,t){await Qa(e,n=>{n.focused_item=t})}async function Z$(e){await Qa(e,t=>{delete t.focused_item})}import{AsyncLocalStorage as cc}from"node:async_hooks";import{createHash as sS}from"node:crypto";import me from"node:fs";import $m from"node:os";import Pt 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]="1ea9ada3-1c97-5787-9b6c-08aeaf825394")}catch{}})();var dc=["model","effort","role","topic","version"],mi=new cc,jm=new cc,pi=new cc,lc=[{harness:"claude-code",environment_keys:["CLAUDE_CODE","CLAUDECODE"],model_environment_keys:["ANTHROPIC_MODEL","CLAUDE_MODEL"],session_environment_keys:["CLAUDE_CODE_SESSION_ID"],provenance_environment_keys:{effort:["CLAUDE_EFFORT"]},provenance_resolvers:{model:"claude_session_file",version:"claude_session_file"},provenance_unavailable_dimensions:["role","topic"],argv_markers:["claude","claude-code"],client_names:["claude","claude-code","claude code"]},{harness:"codex",environment_keys:["CODEX_HOME","CODEX_CI","CODEX_THREAD_ID"],model_environment_keys:["CODEX_MODEL"],session_environment_keys:["CODEX_THREAD_ID"],provenance_environment_keys:{effort:["CODEX_REASONING_EFFORT","CODEX_EFFORT"],role:["CODEX_SESSION_ROLE"]},provenance_resolvers:{model:"codex_session_file",effort:"codex_session_file",version:"ai_agent_version"},provenance_unavailable_dimensions:["topic"],argv_markers:["codex"],client_names:["codex"]},{harness:"pi",environment_keys:["PI_AGENT","PI_CODING_AGENT"],model_environment_keys:["PI_MODEL"],session_environment_keys:["PI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["pi"],client_names:["pi"]},{harness:"opencode",environment_keys:["OPENCODE","OPENCODE_SESSION_ID"],model_environment_keys:["OPENCODE_MODEL"],session_environment_keys:["OPENCODE_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["opencode"],client_names:["opencode"]},{harness:"cursor",environment_keys:["CURSOR_AGENT","CURSOR_TRACE_ID"],model_environment_keys:["CURSOR_MODEL"],session_environment_keys:["CURSOR_TRACE_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["cursor"],client_names:["cursor"]},{harness:"aider",environment_keys:["AIDER","AIDER_MODEL"],model_environment_keys:["AIDER_MODEL"],session_environment_keys:["AIDER_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["aider"],client_names:["aider"]},{harness:"gemini-cli",environment_keys:["GEMINI_CLI","GEMINI_CLI_HOME"],model_environment_keys:["GEMINI_MODEL"],session_environment_keys:["GEMINI_CLI_SESSION_ID"],provenance_unavailable_dimensions:["effort","role","topic"],argv_markers:["gemini","gemini-cli"],client_names:["gemini","gemini-cli","gemini cli"]},{harness:"ci",environment_keys:["CI","GITHUB_ACTIONS","BUILDKITE","GITLAB_CI"],provenance_unavailable_dimensions:["model","effort","role","topic"],argv_markers:[],client_names:[]}],Lm=Object.freeze({max_bytes:1048576,max_lines:4096,network_access:!1,subprocess_access:!1}),aS=Object.freeze({...Lm,max_bytes:4194304}),oc=/^[a-z0-9]+(?:-[a-z0-9]+)*$/u;function cS(e){let t=nt(e).provenance_unavailable_dimensions,n=new Set(["model","version",...Object.keys(e.provenance_environment_keys??{}),...Object.keys(e.provenance_resolvers??{})]);return Object.freeze({contract_version:1,adapter_version:"v1",priority:0,harness:e.harness,descriptor:e,supported_dimensions:Object.freeze([...n].sort()),native_sources:Object.freeze(["environment","argv","mcp_client",...Object.values(e.provenance_resolvers??{}).some(r=>r?.endsWith("session_file"))?["session_file"]:[]]),probe_policy:e.harness==="codex"?aS:Lm,normalization:Object.freeze({model_family:"v1",effort:"v1",preserve_raw:!0}),confidence:"high",waivers:Object.freeze(Object.fromEntries(t.map(r=>[r,"Harness does not expose this dimension."])))})}var Fm=Object.freeze(lc.filter(e=>e.harness!=="ci").map(cS).sort((e,t)=>e.harness.localeCompare(t.harness))),Dt=new Map,Tn=new Map;function q(e){let t=typeof e=="string"?e.trim():void 0;return t&&t.length>0?t:void 0}function tt(e){return[...new Set((e??[]).slice(0,64).map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.slice(0,128)))]}function nt(e){let t=e.harness.trim().toLowerCase();if(!oc.test(t))throw new Error(`Invalid harness signal descriptor namespace: ${e.harness}`);return{harness:t,environment_keys:tt(e.environment_keys),model_environment_keys:tt(e.model_environment_keys),session_environment_keys:tt(e.session_environment_keys),provenance_environment_keys:Object.fromEntries(Object.entries(e.provenance_environment_keys??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),tt(r)]).filter(([n])=>oc.test(n))),provenance_resolvers:Object.fromEntries(Object.entries(e.provenance_resolvers??{}).slice(0,32).map(([n,r])=>[n.trim().toLowerCase().slice(0,64),r]).filter(n=>typeof n[0]=="string"&&oc.test(n[0])&&(n[1]==="ai_agent_version"||n[1]==="claude_session_file"||n[1]==="codex_session_file"))),provenance_unavailable_dimensions:tt(e.provenance_unavailable_dimensions).map(n=>n.toLowerCase()),argv_markers:tt(e.argv_markers).map(n=>n.toLowerCase()),client_names:tt(e.client_names).map(n=>n.toLowerCase())}}var Um=lc.map(nt);function dS(e,t){return JSON.stringify(e)===JSON.stringify(t)}function fi(e,t){return e.toLowerCase().slice(0,512).split(/[/\\\s:=]+/u).filter(n=>n.length>0).includes(t)||e.trim().toLowerCase()===t}function uc(e=[]){let t=new Map(lc.filter(o=>o.harness!=="ci").map(o=>[o.harness,nt(o)]));for(let{adapter:o}of Dt.values())t.set(o.harness,nt(o.descriptor));let n=[...t.values(),...Um.filter(o=>o.harness==="ci"),...[...Tn.values()].map(o=>o.descriptor),...pi.getStore()?.descriptors??[],...e.map(nt)],r=new Set;for(let o of n){if(r.has(o.harness))throw new Error(`Harness signal descriptor collision for "${o.harness}"`);r.add(o.harness)}return n}function fc(e,t){for(let n of t??[]){let r=q(e[n]);if(r)return r.slice(0,256)}}function lS(e,t){if(t==="role"){let n=e.slice(0,8).map(r=>r.trim().toLowerCase()).find(r=>["claim","create","update","close","release","review"].includes(r));if(n==="review")return"reviewer";if(n)return"implementer"}}function zm(e,t){let n=t==="model"?["--model","--agent-model"]:[`--agent-${t}`],r=e.slice(0,8);for(let o=0;o<r.length;o+=1){let i=r[o].slice(0,512);if(n.includes(i))return q(r[o+1])?.slice(0,256);let s=n.find(a=>i.startsWith(`${a}=`));if(s)return q(i.slice(s.length+1))?.slice(0,256)}}var uS=new Set(["implementation","implementer","investigator","orchestrator","planner","release-operator","reviewer"]);function Nt(e,t){if(e!=="role"||t===void 0)return t;let n=t.trim().toLowerCase().replaceAll(/[_\s]+/gu,"-");return uS.has(n)?n:void 0}function ic(e,t){return q(e?.[t])?.slice(0,256)}var fS=1048576,ac=4194304,ui=new Map,Dm=Object.freeze({}),sc=new Map,Pm=Object.freeze({});function Mm(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function mS(e){let t;try{t=JSON.parse(e)}catch{return Pm}let n=Mm(t);if(!n)return Pm;let r=[{value:n,depth:0}],o=0,i,s;for(;r.length>0&&o<64;){let a=r.shift();if(o+=1,i??=q(a.value.model)?.slice(0,256),s??=q(a.value.version)?.slice(0,256),i&&s)break;if(!(a.depth>=4))for(let c of Object.values(a.value)){let d=Mm(c);d&&r.push({value:d,depth:a.depth+1})}}return Object.freeze({model:i,version:s})}function Hm(e){try{return me.lstatSync(e).isFile()?"available":"missing"}catch(t){return be(t)?"missing":"failed"}}function pS(e,t){let n;try{n=me.readdirSync(e,{withFileTypes:!0}).filter(o=>o.isDirectory()).sort((o,i)=>o.name.localeCompare(i.name)).slice(0,512).map(o=>{let i=Pt.join(e,o.name,`${t}.jsonl`);return{candidate:i,status:Hm(i)}})}catch(o){return{status:be(o)?"missing":"failed"}}let r=n.filter(({status:o})=>o==="available").map(({candidate:o})=>o);return r.length===0?{status:n.some(({status:o})=>o==="failed")?"failed":"missing"}:r.length>1?{status:"ambiguous"}:{status:"available",path:r[0]}}function qm(e,t){let n=q(t.CLAUDE_CODE_SESSION_ID);if(!n||!/^[A-Za-z0-9_-]{1,128}$/u.test(n))return{status:"unavailable"};let r=Pt.resolve(e.cwd??process.cwd()).replaceAll(/[^A-Za-z0-9-]/gu,"-"),o=Pt.join(e.home_dir??$m.homedir(),".claude","projects"),i=Pt.join(o,r,`${n}.jsonl`),s=q(e.session_file),a=s&&Pt.basename(s)===`${n}.jsonl`?s:void 0;for(let c of[a,i]){if(!c)continue;let d=Hm(c);if(d==="available")return{status:d,path:c};if(d==="failed")return{status:d}}return pS(o,n)}function _S(e,t,n){let r=qm(t,n);if(r.status==="available")try{let o=me.openSync(r.path,me.constants.O_RDONLY|me.constants.O_NOFOLLOW);try{let i=me.fstatSync(o),s=`${r.path}\0${i.size}\0${i.mtimeMs}`,a=sc.get(s);if(a)return a[e];let c=Math.min(i.size,fS),d=Math.min(c,Math.ceil(c/2)),l=Math.min(c-d,i.size-d),u=Buffer.alloc(d);me.readSync(o,u,0,d,0);let f=Buffer.alloc(l);l>0&&me.readSync(o,f,0,l,i.size-l);let m={},_=i.size<=c?Buffer.concat([u,f]).toString("utf8").split(`
14
14
  `):[...u.toString("utf8").split(`
15
15
  `).slice(0,4096),...f.toString("utf8").split(`
16
- `).slice(-4096)];for(let b of _){if(b.length===0||b.length>262144)continue;let v=oS(b);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return nc.clear(),nc.set(s,y),y[e]}finally{me.closeSync(o)}}catch{return}}function aS(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=me.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=Pt.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=r(c,i+1);if(d)return d}}};return r(e,0)}function cS(e){if(e<=rc)return[{offset:0,length:e}];let t=Math.floor(rc/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function dS(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=q(o?.model)?.slice(0,256),e.effort??=q(o?.effort)?.slice(0,256)}function lS(e,t){let n={},r=4096;for(let o of cS(t)){let i=Buffer.alloc(o.length);me.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
17
- `).reverse().slice(0,r);r-=s.length;for(let a of s)if(dS(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function uS(e,t,n){let r=q(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=Pt.join(t.home_dir??xm.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=li.get(i);if(s)return s[e];let a=aS(o,r);if(!a){li.set(i,Tm);return}try{let c=me.openSync(a,"r");try{let d=me.fstatSync(c).size,l=lS(c,d);return li.set(i,l),l[e]}finally{me.closeSync(c)}}catch{li.set(i,Tm);return}}function fS(e,t,n,r){let o=mi.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(q(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=r?.provenance_resolvers[e];if(i==="claude_session_file")return sS(e,t,n);if(i==="codex_session_file")return uS(e,t,n);if(i==="ai_agent_version"){let s=q(n.AI_AGENT);return!s||!r||!ui(s,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function mS(e,t,n,r){if(e==="ai_agent_version"){let o=q(r.AI_AGENT);return o!==void 0&&ui(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?q(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":Lm(n,r).status}function dc(e){return e||(Nm.getStore()??{env:process.env,argv:process.argv})}function pS(e,t,n,r){let o=e.environment_keys.some(a=>q(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return ui(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||ui(r,a));return o||i||s}function _S(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function yS(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function hS(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...ic,...Object.keys(r?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=Nt(e,q(n[s])?.slice(0,256)),l=Nt(e,jm(t.argv??[],e)),d=Nt(e,tS(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=tc(o?.provenance,e),_=Nt(e,cc(n,u[e])),y=Nt(e,tc(f,e)),b=Nt(e,tc(t.provenance,e)),v=fS(e,t,n,r);return yS([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[b,"host"],[v,"probe"]])??_S(e,i)??(d?{value:d,source:"argv"}:void 0)}function gS(e,t){if(!(!e||!t))return Jk("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function bS(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...ic,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let d=hS(c,e,t,n,r,o);d?a[c]=d:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function Gj(e){let t=e.map(nt),n=new Map(Mm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=In.get(i.harness);if(s&&!eS(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=In.get(i.harness);In.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=In.get(i.harness);!s||s.registrations<=1?In.delete(i.harness):s.registrations-=1}}}}function wS(e){let t=nt(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=q(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>rc||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(tt(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function Kj(){let e=new Map(Pm.map(t=>[t.harness,t]));for(let{adapter:t}of Dt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function Yj(e){let t=e.map(wS),n=new Map(Pm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=Dt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=Dt.get(i.harness);Dt.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Dt.get(i.harness);!s||s.registrations<=1?Dt.delete(i.harness):s.registrations-=1}}}}function Xj(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function Jj(e,t){return Nm.run(e,t)}function Qj(e,t,n={}){let r=e.map(nt);return ac(r),mi.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function lc(e){let t=dc(e),n=t.env??{},r=ac(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(_=>pS(_,n,o,i)),a=Fa(t,n),c=[cc(n,s?.session_environment_keys),q(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=gS(s?.harness,c),l=Im({cwd:t.cwd??process.cwd(),env:n,key:d}),u=bS(t,n,s,a,l),f=u.model,m=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",d],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(m.filter(_=>_[1]!==void 0))}function vS(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function ES(e,t,n,r,o,i,s){let a=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=mS(a,n,r,o);return{...vS(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function Fm(e){let t=dc(e),n=lc(t),r=ac(t.descriptors).find(d=>d.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&mi.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(q(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=Fa(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,cc(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,jm(t.argv??[],"role")].some(d=>{let l=q(d)?.slice(0,256);return l!==void 0&&Nt("role",l)===void 0}),c=Object.fromEntries(ic.map(d=>[d,ES(d,n,r,t,o,i,d==="role"&&a)]));return{...n,provenance_outcomes:c}}function Zj(){return process.env.PM_AUTHOR}function e$(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function t$(e){return lc(e).harness}function kS(e,t,n){let r=dc(n),o=lc(r);if(e!==void 0){let s=q(e);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=q(r.env.PM_AUTHOR);return s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=q(t);return i?{author:i,source:"configured",...o}:o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Um(e){let t=fi.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function zm(e){let t=fi.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function n$(e){let t=fi.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Hm(e,t){let n=kS(e,t);return fi.enterWith(n),n.author}import SS from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="58661057-fa80-5571-9be7-b949723c274b")}catch{}})();async function pi(e,t){let n=await SS.readFile(e).catch(s=>{if(be(s))return null;throw s}),r=n?.toString("utf8")??null;if(r===null)return{raw:r,raw_bytes:n,entries:[]};if(await gn({path:e,scope:"project"}),r.trim()==="")return{raw:r,raw_bytes:n,entries:[]};let o=Yo(r);if(o)throw new g(`History for ${t} contains merge conflict markers at line ${o.line} (${o.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let i=[];for(let[s,a]of r.split(/\r?\n/).entries()){let c=a.trim();if(c)try{i.push(JSON.parse(c))}catch{throw new g(`History for ${t} contains invalid JSON at line ${s+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw:r,raw_bytes:n,entries:i}}async function Mt(e,t){return(await pi(e,t)).entries}(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]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var u$=1,OS=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],AS=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],IS=new Set(OS),TS=new Set(AS),CS=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function RS(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function Tn(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:IS.has(e.op)?"maintenance":TS.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=RS(t);return n!==void 0&&CS.has(n)})?"maintenance":"substantive"}(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]="a65d6520-0e6f-5627-a4dd-bd455c2db0fa")}catch{}})();var Bm=new WeakMap;function _$(e,t){Bm.set(e,new Set(t))}var _i='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',xS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},NS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function y$(e,t,n){if(e&&t)throw new g(`${n} cannot be combined with --full`,h.USAGE)}function xe(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function h$(e,t){let n=NS.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return xe([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return xe(r)}var DS=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var PS=new Set([void 0,"tabular_when_uniform"]),MS=new Set(["collection","none"]),jS=new Set(["supported","unsupported"]);function qm(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function $S(e){return ne(e)&&typeof e.command=="string"&&e.command.trim().length>0&&MS.has(e.row_kind)&&qm(e.row_keys,!0)&&(e.continuation_row_keys===void 0||qm(e.continuation_row_keys,!1))&&jS.has(e.fields)&&PS.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var LS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},FS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function US(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=LS[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||ne(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:_i}:{},toon_encoding:"tabular_when_uniform"}}let o=xS[r],i=FS[r];return o===void 0||i===void 0||!i.some(s=>Object.hasOwn(t,s))?void 0:(()=>{let s=o.row_keys.filter(a=>{let c=a.split(".").reduce((d,l)=>ne(d)?d[l]:void 0,t);return Array.isArray(c)||ne(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:_i}:{},toon_encoding:"tabular_when_uniform"}})()}function zS(e){if(!ne(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>ne(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return xe(r,new Set(o))}function HS(e){if(!Array.isArray(e.sections_included))return;let t=xe(DS,new Set(e.sections_included.filter(n=>typeof n=="string")));return ne(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function qS(e,t,n){if(e==="dependency_provenance")return!1;let r=Wm(e);if(r!==void 0){let o=n[r.facet];return ne(o)&&Object.hasOwn(o,r.member)}return Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&ne(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&ne(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function Wm(e){let t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function VS(e){if(!ne(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=Bm.get(e),i=a=>n.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...n,...r.slice(1),...o?.has("dependency_provenance")?["dependency_provenance"]:[],...o?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[],...[...o??[]].filter(a=>Wm(a)!==void 0)].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:a==="blockers"?"--full":a==="dependency_provenance"?"--fields dependencies":`--fields ${a}`}));return xe(s,new Set(s.flatMap(({name:a})=>qS(a,i(a),e)?[a]:[])))}function Vm(e){if(ne(e.projection))return xe([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function BS(e){if(!ne(e.projection))return xe([]);if(typeof e.projection.mode=="string")return xe([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function WS(e){if(!(!ne(e.selected)||typeof e.selected.summary!="boolean"))return xe([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function GS(e,t){let n=zS(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return HS(t);if(r==="get")return VS(t);if(r==="list"||r.startsWith("list-"))return Vm(t);if(r==="search")return Vm(t)??xe([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return BS(t);if(r==="contracts")return WS(t)}function Gm(e,t){if(e===void 0||!ne(t))return t;let n=GS(e,t),r=t.row_contract,o=$S(r)?r:US(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return ne(i.omission_receipt)||n===void 0?i:{...i,omission_receipt:n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f539ecb5-2f49-5867-96c7-48eddb81a628")}catch{}})();var KS=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Km(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!J(n))return;n=n[r]}return n}function uc(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[s];if(Array.isArray(i)){let d=Number(a),l=[...i];return l[d]=o(i[d],s+1),l}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function fc(e,t,n,r){let o=Cn(e).find(a=>a.path===t);if(!o)return e;let i=Array.isArray(o.value)?o.value.slice(n,r):Object.fromEntries(Object.entries(o.value).slice(n,r)),s=uc(e,t,i);return J(s.summary)&&J(s.summary.focus_row_states)&&typeof s.summary.focus_row_states[t]=="string"&&(s.summary={...s.summary,focus_row_states:{...s.summary.focus_row_states,[t]:s.summary.focus_row_states[t].slice(n,r)}}),Cr(s),s}function hi(e){let t=e.row_contract;return J(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function YS(e){let t=e.row_contract;return J(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):hi(e)}function rt(e){return hi(e).flatMap(t=>{let n=Km(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function Cn(e){return YS(e).flatMap(t=>{let n=Km(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function Ir(e){let t=rt(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(J(o))for(let[s,a]of Object.entries(o))i.length===0&&KS.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function Rn(e){return rt(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function Tr(e,t){let n=e;for(let r of rt(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=uc(n,r.path,o)}return n}function Ym(e,t,n=()=>!1){let r=e,o=!1;for(let i of rt(r)){let s=Array.isArray(i.value)?i.value:Object.entries(i.value);if(s.length<=t)continue;o=!0;let a=n(i.path)?s.length-t:0,c=s.slice(a,a+t),d=Array.isArray(i.value)?c:Object.fromEntries(c);r=uc(r,i.path,d)}return{result:r,truncated:o}}var Xm=["high_level","low_level","blocked_fallback"];function yi(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function b$(e,t){if(!J(e.summary)||!J(e.summary.returned_focus))return;let n=new Map(t.map(r=>[r.id,r]));e.summary={...e.summary,focus_row_states:Object.fromEntries(Xm.map(r=>[r,Array.isArray(e[r])?e[r].filter(J).map(o=>yi(n.get(o.id)??o)).join(""):""]))}}function XS(e,t){if(e!==void 0){if(typeof e!="string"||e.length!==t||!/^[iIoO]*$/u.test(e))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return e}}function JS(e,t,n,r){let o=Array.isArray(t[n])?t[n].filter(J):[],i=XS(r[n],o.length)??o.map(yi).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[n])?e[n].filter(J):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??yi(d);return u!==yi(d)&&(c=!0),u}).join(""),needsStates:c}}function QS(e,t){typeof e.count=="number"&&(e.count_only===!0||t.count_only===!0?typeof t.count=="number"&&(e.count=t.count):Array.isArray(e.items)&&(e.count=e.items.length))}function Cr(e,t=e){if(QS(e,t),!J(e.summary)||!J(e.summary.returned_focus))return;let n={...e.summary},r=J(t.summary)&&J(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=Xm.map(c=>({key:c,...JS(e,t,c,r)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof n.high_level=="number"&&(n.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof n.low_level=="number"&&(n.low_level=Array.isArray(e.low_level)?e.low_level.length:0),n.returned_focus={active_items:a.length,in_progress:[...a].filter(c=>c.toLowerCase()==="i").length,open:[...a].filter(c=>c.toLowerCase()==="o").length,blocked:[...a].filter(c=>c===c.toUpperCase()).length},s?n.focus_row_states=i:delete n.focus_row_states,e.summary=n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2335ae7f-c7aa-5bdd-ac2e-e6d7a74be2e1")}catch{}})();var gi="changed_fields",ZS="changed_field_count",mc="rows",eO=new Set(["apply","rollback"]),ep=new Set(["deleted","would_delete"]),Jm=256,Qm={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function tO(e,t){if(!se(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let n=Object.hasOwn(Qm,e.action)?Qm[e.action]:void 0;if(!n||!n.every(i=>{let s=e[i];return se(s)&&se(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let r=e[n.at(-1)],o=np(r);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(n.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(n.map(i=>[i,Rr(e[i],t)]))}}function Zm(e){return typeof e!="string"||e.length<=Jm?e:`${Ee(e,Jm-1)}\u2026`}function nO(e){if(!se(e))return null;let t={...e};return t.reason=Zm(t.reason),se(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,Zm(r)]))),t}function se(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function tp(e){let t=e[gi];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==gi&&(n[r]=o);return n[ZS]=t.length,n}function rO(e){return"item"in e&&Array.isArray(e[gi])}function oO(e){return typeof e.mode=="string"&&eO.has(e.mode)&&Array.isArray(e[mc])}function iO(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[mc]=t,n}function np(e){if(!se(e))return null;let t=se(e.item)?e.item:se(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&ep.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function sO(e,t){if(!se(e))return null;if(se(e.plan)&&se(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!t||!se(e.item)||typeof e.item.id!="string")return null;let n=e[gi];if(!Array.isArray(n))return null;let r={id:e.item.id,...typeof e.outcome=="string"&&ep.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:n.length};return aO(e,e.item,r),r}function aO(e,t,n){let r=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;r!==void 0&&(n.close_reason=r);let o=nO(e.recurrence);o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion","start"])se(e[i])&&(n[i]=e[i]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(let i of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(e,i)&&(n[i]=e[i])}function cO(e){let t=oO(e)?e[mc]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!se(o))return o;let i=tp(o);return i?(n=!0,i):o});return n?{projected:iO(e,r),changed:!0}:{projected:e,changed:!1}}function Rr(e,t={}){let n=tO(e,t);if(n!==null)return n;if(t.idOnly===!0){let a=np(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=sO(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!se(e))return e;let r=!1,o=e,i=rO(e)?tp(e):null;i!==null&&(o=i,r=!0);let s=cO(o);return s.changed&&(o=s.projected,r=!0),r?o:e}import{AsyncLocalStorage as HA}from"node:async_hooks";(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]="1b67272d-8924-5b1b-97cd-74a6a10493be")}catch{}})();function pc(e){let t=e.trim().toLowerCase().startsWith("extension:"),n=e.trim().toLowerCase().replace(/^extension:/u,"");if(fn(n))return;let r=cf()?.commands??[],o=[...r].reverse().find(s=>s.command===n)?.command??(t?void 0:r.find(s=>s.action===n)?.command),i=[...r].reverse().find(s=>s.command===o);return i===void 0||fn(i.command)||fn(i.action)?void 0:i}function dO(e){let t=pc(e);return t?.read_output===void 0?void 0:t}function rp(e,t){let n=dO(e),r=n?.read_output;if(r===void 0)return t;if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Read-only extension commands must return a structured object.",h.USAGE,{code:"extension_read_output_invalid"});for(let o of r.row_keys){let i=t;for(let s of o.split("."))i=typeof i=="object"&&i!==null&&Object.hasOwn(i,s)?Reflect.get(i,s):void 0;if(i===null||typeof i!="object")throw new g(`Read-only extension result is missing declared row collection ${o}.`,h.USAGE,{code:"extension_read_output_invalid"})}return{...t,row_contract:{command:`extension:${n.command}`,row_kind:r.row_keys.length>0?"collection":"none",row_keys:[...r.row_keys],fields:"supported",...r.row_keys.length>0?{jq_selector:_i}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as SA}from"node:crypto";import{createHash as gA}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]="040fff2e-c66f-5091-9ea8-7dcdaf6e203b")}catch{}})();var _c={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},learnings:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},yc=new Set(["--collapse","--fields","--section"]),bi=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function wi(e){return e.slice(2).replaceAll("-","_")}function op(e,t={}){let n=e==="package catalog"||e==="packages catalog"||e==="package-catalog"||(e==="package"||e==="packages"||e==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":e==="package manage"||e==="package-manage"?"package-manage":e.split(" ")[0],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return Et.includes(r)?r:void 0}function hc(e){return new Map((_c[e]?.include??[]).filter(t=>!yc.has(t)&&bi[t]===void 0).map(t=>[wi(t),gc(t)]))}function gc(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}import{stripVTControlCharacters as lO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();var uO=["full","compact","brief","summary","counts"],M$=["mutation","read","discovery","governance"],sp=["error","warning","validation_summary","recovery_bundle"],fO=["full","omit_explanation","limit_collections","compact_recovery","action_only"],mO=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),pO=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),_O=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),yO={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},hO=3,gO=2,bO=192,wO={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},vO=sp.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:wO[e],minimum_max_estimated_tokens:bO,degradation_ladder:fO,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),EO=new Map(vO.map(e=>[e.diagnostic_class,e]));function kO(e){let[t=""]=Gn(e).split(/\s+/u);return mO.has(t)?"mutation":pO.has(t)?"discovery":_O.has(t)?"governance":"read"}function ap(e,t=kO(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=yO[t];return SO({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*hO/gO)},degradation_ladder:uO,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function SO(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var OO=oo.map(e=>ap(e)),AO=new Map(OO.map(e=>[e.command,e]));function cp(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=Gn(n).split(" "),o=AO.get(r);return o?{...o,command:n}:t.generateFallback?ap(n):null}function $t(e){return Math.ceil(Math.max(0,e)/4)}function dp(e){let t=EO.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${sp.join(", ")}`);return t}function ot(e){return $t(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function IO(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bc(e){if(!IO(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function TO(e,t){return typeof e!="string"||e.length<=t?e:`${Ee(e,Math.max(1,t-3))}...`}function jt(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function lp(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var CO=new Set(["limit_collections","compact_recovery","action_only"]),RO=new Set(["compact_recovery","action_only"]);function xO(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:TO(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=bc(e.recovery);return n!==void 0?t.recovery=n:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function NO(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),CO.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(RO.has(t)){let r=bc(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?lp(n):xO(n)}function xn(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=ot(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function DO(e,t,n){let r=xn(e,t);for(let i of["recovery","exit_code"])ot(r)<=n||e[i]===void 0||(delete e[i],r=xn(e,t));let o=40;for(;ot(r)>n&&o>4;)o-=4,e.code=jt(String(e.code),o),e.required=jt(String(e.required),o),r=xn(e,t);return r}function PO(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>jt(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=bc(e.recovery),c=a&&ot(a)<=48?a:void 0,d={code:jt(String(e.code),320),required:jt(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=xn(d,s);for(;ot(l)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,l=xn(d,s);return l=DO(d,s,t),l}function j$(e,t={}){let n=e,r=t.diagnosticClass??"error",o=dp(r),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=ot(n),c=Object.keys(n);if(a<=s)return lp(structuredClone(n));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=NO(n,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=xn(f,{diagnostic_class:r,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:l>0,degradation_steps:o.degradation_ladder.slice(0,l+1),omitted_fields:m});if(d=_,ot(_)<=s)break}return ot(d)>s&&(d=PO(d,s)),d}function ip(e){return lO(e).replace(/\r\n/gu,`
18
- `).replace(/[^\P{Cc}\n]/gu," ")}function $$(e,t,n={}){let r=n.diagnosticClass??"error",o=dp(r),i=n.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=ip(e),c=$t(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
16
+ `).slice(-4096)];for(let b of _){if(b.length===0||b.length>262144)continue;let v=mS(b);if(m.model??=v.model,m.version??=v.version,m.model&&m.version)break}let y=Object.freeze(m);return sc.clear(),sc.set(s,y),y[e]}finally{me.closeSync(o)}}catch{return}}function yS(e,t){let n=0,r=(o,i)=>{if(i>4||n>=512)return;let s;try{s=me.readdirSync(o,{withFileTypes:!0}).sort((a,c)=>c.name.localeCompare(a.name))}catch{return}for(let a of s){if(n+=1,n>512)return;let c=Pt.join(o,a.name);if(a.isFile()&&a.name.endsWith(`-${t}.jsonl`))return c;if(a.isDirectory()){let d=r(c,i+1);if(d)return d}}};return r(e,0)}function hS(e){if(e<=ac)return[{offset:0,length:e}];let t=Math.floor(ac/2);return[{offset:e-t,length:t},{offset:0,length:t}]}function gS(e,t){if(t.length===0||t.length>262144)return;let n;try{n=JSON.parse(t)}catch{return}if(typeof n!="object"||n===null||Array.isArray(n))return;let r=n;if(r.type!=="turn_context")return;let o=typeof r.payload=="object"&&r.payload!==null?r.payload:void 0;e.model??=q(o?.model)?.slice(0,256),e.effort??=q(o?.effort)?.slice(0,256)}function bS(e,t){let n={},r=4096;for(let o of hS(t)){let i=Buffer.alloc(o.length);me.readSync(e,i,0,o.length,o.offset);let s=i.toString("utf8").split(`
17
+ `).reverse().slice(0,r);r-=s.length;for(let a of s)if(gS(n,a),n.model&&n.effort)break;if(n.model&&n.effort||r<=0)break}return n}function wS(e,t,n){let r=q(n.CODEX_THREAD_ID);if(!r||!/^[A-Za-z0-9_-]{1,128}$/u.test(r))return;let o=Pt.join(t.home_dir??$m.homedir(),".codex","sessions"),i=`${o}\0${r}`,s=ui.get(i);if(s)return s[e];let a=yS(o,r);if(!a){ui.set(i,Dm);return}try{let c=me.openSync(a,"r");try{let d=me.fstatSync(c).size,l=bS(c,d);return ui.set(i,l),l[e]}finally{me.closeSync(c)}}catch{ui.set(i,Dm);return}}function vS(e,t,n,r){let o=pi.getStore();if(!(t.probes_enabled!==!1&&o?.probesEnabled!==!1&&!["0","false","off"].includes(q(n.PM_AGENT_PROBES)?.toLowerCase()??"")))return;let i=r?.provenance_resolvers[e];if(i==="claude_session_file")return _S(e,t,n);if(i==="codex_session_file")return wS(e,t,n);if(i==="ai_agent_version"){let s=q(n.AI_AGENT);return!s||!r||!fi(s,r.harness)?void 0:/(?:^|[@/\s])v?(\d+\.\d+(?:\.\d+)?(?:[-+][A-Za-z0-9.-]+)?)$/u.exec(s)?.[1]?.slice(0,256)}}function ES(e,t,n,r){if(e==="ai_agent_version"){let o=q(r.AI_AGENT);return o!==void 0&&fi(o,t.harness)?"available":"unavailable"}return e==="codex_session_file"?q(r.CODEX_THREAD_ID)!==void 0?"available":"unavailable":qm(n,r).status}function mc(e){return e||(jm.getStore()??{env:process.env,argv:process.argv})}function kS(e,t,n,r){let o=e.environment_keys.some(a=>q(t[a])!==void 0),i=e.argv_markers.some(a=>n.some(c=>{let d=c.replaceAll("\\","/");return fi(d.slice(d.lastIndexOf("/")+1),a)})),s=e.client_names.some(a=>r===a||fi(r,a));return o||i||s}function SS(e,t){if(!t)return;let n;if(e==="topic"&&(n=t.topic),e==="role"&&(n=t.role),!!n)return{value:n,source:"inferred",confidence:t.confidence,rule_version:t.rule_version,evidence:t.evidence}}function OS(e){let t=e.find(([n])=>n!==void 0);return t?.[0]?{value:t[0],source:t[1]}:void 0}function AS(e,t,n,r,o,i){let s=`PM_AGENT_${e.toUpperCase().replaceAll("-","_")}`,a=new Set([...dc,...Object.keys(r?.provenance_environment_keys??{})]),c,d,l;a.has(e)&&(c=Nt(e,q(n[s])?.slice(0,256)),l=Nt(e,zm(t.argv??[],e)),d=Nt(e,lS(t.argv??[],e)));let u={...r?.provenance_environment_keys,model:r?.model_environment_keys},f={...t.client_info?.provenance,model:t.client_info?.model},m=ic(o?.provenance,e),_=Nt(e,fc(n,u[e])),y=Nt(e,ic(f,e)),b=Nt(e,ic(t.provenance,e)),v=vS(e,t,n,r);return OS([[c,"override"],[m,"session"],[l,"argv"],[_,"environment"],[y,"mcp_client"],[b,"host"],[v,"probe"]])??SS(e,i)??(d?{value:d,source:"argv"}:void 0)}function IS(e,t){if(!(!e||!t))return sS("sha256").update(`pm-agent-instance:v1\0${e}\0${t}`).digest("hex").slice(0,24)}function TS(e,t,n,r,o){let i=Object.keys(n?.provenance_environment_keys??{}),s=new Set([...dc,...i,...Object.keys(n?.provenance_resolvers??{}),...Object.keys(e.provenance??{}),...Object.keys(e.client_info?.provenance??{}),...Object.keys(r?.provenance??{})]),a={};for(let c of s){let d=AS(c,e,t,n,r,o);d?a[c]=d:n&&(c!=="version"||n.provenance_unavailable_dimensions.includes(c))&&(a[c]=null)}return a}function dj(e){let t=e.map(nt),n=new Map(Um.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness)||n.has(i.harness))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);let s=Tn.get(i.harness);if(s&&!dS(s.descriptor,i))throw new Error(`Harness signal descriptor collision for "${i.harness}"`);r.add(i.harness)}for(let i of t){let s=Tn.get(i.harness);Tn.set(i.harness,{descriptor:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Tn.get(i.harness);!s||s.registrations<=1?Tn.delete(i.harness):s.registrations-=1}}}}function CS(e){let t=nt(e.descriptor),n=e.harness.trim().toLowerCase();if(e.contract_version!==1)throw new Error(`Unsupported provenance adapter contract for "${n}": ${e.contract_version}`);if(t.harness!==n)throw new Error(`Provenance adapter harness "${n}" does not match descriptor "${t.harness}".`);let r=q(e.adapter_version)?.slice(0,64);if(!r)throw new Error(`Provenance adapter "${n}" requires a version.`);if(!Number.isSafeInteger(e.priority))throw new Error(`Provenance adapter "${n}" requires an integer priority.`);if(e.probe_policy.network_access!==!1||e.probe_policy.subprocess_access!==!1||e.probe_policy.max_bytes>ac||e.probe_policy.max_lines>4096)throw new Error(`Provenance adapter "${n}" exceeds the bounded local probe policy.`);return Object.freeze({...e,adapter_version:r,harness:n,descriptor:t,supported_dimensions:Object.freeze(tt(e.supported_dimensions).map(o=>o.toLowerCase()).sort()),native_sources:Object.freeze([...new Set(e.native_sources)]),probe_policy:Object.freeze({...e.probe_policy}),normalization:Object.freeze({...e.normalization}),...e.waivers?{waivers:Object.freeze(Object.fromEntries(Object.entries(e.waivers).slice(0,32).map(([o,i])=>[o.slice(0,64),i.slice(0,256)])))}:{}})}function lj(){let e=new Map(Fm.map(t=>[t.harness,t]));for(let{adapter:t}of Dt.values())e.set(t.harness,t);return Object.freeze([...e.values()].sort((t,n)=>t.harness.localeCompare(n.harness)))}function uj(e){let t=e.map(CS),n=new Map(Fm.map(i=>[i.harness,i])),r=new Set;for(let i of t){if(r.has(i.harness))throw new Error(`Provenance adapter collision for "${i.harness}".`);let s=n.get(i.harness);if(s&&i.priority<=s.priority)throw new Error(`Provenance adapter override for "${i.harness}" requires priority greater than ${s.priority}.`);let a=Dt.get(i.harness);if(a&&JSON.stringify(a.adapter)!==JSON.stringify(i))throw new Error(`Provenance adapter collision for "${i.harness}".`);r.add(i.harness)}for(let i of t){let s=Dt.get(i.harness);Dt.set(i.harness,{adapter:i,registrations:(s?.registrations??0)+1})}let o=!0;return()=>{if(o){o=!1;for(let i of t){let s=Dt.get(i.harness);!s||s.registrations<=1?Dt.delete(i.harness):s.registrations-=1}}}}function fj(e,t){let n=t.trim().slice(0,256),r=n.toLowerCase();if(e==="model"){let o=/^(gpt-\d+(?:\.\d+)?)/u.exec(r)?.[1];o&&(r=o)}else r=r.replaceAll(/[_\s-]+/gu,""),r={minimal:"low",low:"low",medium:"medium",high:"high",xhigh:"xhigh",max:"max",ultra:"ultra"}[r]??r;return{raw:n,normalized:r,vocabulary:"v1"}}function mj(e,t){return jm.run(e,t)}function pj(e,t,n={}){let r=e.map(nt);return uc(r),pi.run({descriptors:r,probesEnabled:n.probesEnabled!==!1},t)}function pc(e){let t=mc(e),n=t.env??{},r=uc(t.descriptors),o=[...(t.argv??[]).slice(0,3),...t.process_labels??[]].slice(0,64).map(_=>_.slice(0,512)),i=t.client_info?.name.trim().toLowerCase()??"",s=r.find(_=>kS(_,n,o,i)),a=qa(t,n),c=[fc(n,s?.session_environment_keys),q(t.client_info?.session)?.slice(0,256)].find(_=>_!==void 0),d=IS(s?.harness,c),l=Nm({cwd:t.cwd??process.cwd(),env:n,key:d}),u=TS(t,n,s,a,l),f=u.model,m=[["harness",s?.harness],["model",f?.value],["model_source",f?.source],["session",c],["instance",d],["provenance",Object.keys(u).length>0?u:void 0],["episode",a.episode]];return Object.fromEntries(m.filter(_=>_[1]!==void 0))}function RS(e){return e==="unavailable"?{status:"unavailable",reason:"harness_unavailable"}:e==="missing"?{status:"unavailable",reason:"resolver_input_missing"}:{status:"failed",reason:"resolver_failed"}}function xS(e,t,n,r,o,i,s){let a=n?.provenance_resolvers[e];if(t.provenance?.[e])return{status:"resolved",...a?{resolver:a}:{},rule_version:"v1"};if(s)return{status:"unavailable",reason:"invalid_value",rule_version:"v1"};if(a){if(!i)return{status:"unavailable",reason:"probes_disabled",resolver:a,rule_version:"v1"};let c=ES(a,n,r,o);return{...RS(c),resolver:a,rule_version:"v1"}}return{status:n?.provenance_unavailable_dimensions.includes(e)?"unavailable":"not_configured",reason:n?.provenance_unavailable_dimensions.includes(e)?"harness_unavailable":"resolver_not_configured",rule_version:"v1"}}function Vm(e){let t=mc(e),n=pc(t),r=uc(t.descriptors).find(d=>d.harness===n.harness),o=t.env??{},i=t.probes_enabled!==!1&&pi.getStore()?.probesEnabled!==!1&&!["0","false","off"].includes(q(o.PM_AGENT_PROBES)?.toLowerCase()??""),s=qa(t,o),a=[o.PM_AGENT_ROLE,s.provenance?.role,fc(o,r?.provenance_environment_keys.role),t.client_info?.provenance?.role,t.provenance?.role,zm(t.argv??[],"role")].some(d=>{let l=q(d)?.slice(0,256);return l!==void 0&&Nt("role",l)===void 0}),c=Object.fromEntries(dc.map(d=>[d,xS(d,n,r,t,o,i,d==="role"&&a)]));return{...n,provenance_outcomes:c}}function _j(){return process.env.PM_AUTHOR}function yj(e){e===void 0?delete process.env.PM_AUTHOR:process.env.PM_AUTHOR=e}function hj(e){return pc(e).harness}function NS(e,t,n){let r=mc(n),o=pc(r);if(e!==void 0){let s=q(e);return ln(s,"--author"),s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}if(r.env?.PM_AUTHOR!==void 0){let s=q(r.env.PM_AUTHOR);return ln(s,"PM_AUTHOR"),s?{author:s,source:"asserted",...o}:{author:"unknown",source:"unknown",...o}}let i=q(t);return i?(ln(i,"default_author"),{author:i,source:"configured",...o}):o.harness?{author:`harness:${o.harness}`,source:"detected",...o}:{author:"unknown",source:"unknown",...o}}function Bm(e){let t=mi.getStore();return t?.author===e?t.source:e.startsWith("harness:")?"detected":e==="unknown"?"unknown":"asserted"}function Wm(e){let t=mi.getStore();return t?.author!==e?e.startsWith("harness:")?{harness:e.slice(8)}:{}:{...t.harness?{harness:t.harness}:{},...t.model?{model:t.model}:{},...t.model_source?{model_source:t.model_source}:{},...t.session?{session:t.session}:{},...t.instance?{instance:t.instance}:{},...t.provenance?{provenance:t.provenance}:{},...t.episode?{episode:t.episode}:{}}}function gj(e){let t=mi.getStore();return t?.author===e&&t.source==="detected"&&t.instance?`${e}#${t.instance}`:e}function Gm(e,t){let n=NS(e,t);return mi.enterWith(n),n.author}import DS from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="58661057-fa80-5571-9be7-b949723c274b")}catch{}})();async function _i(e,t){let n=await DS.readFile(e).catch(s=>{if(be(s))return null;throw s}),r=n?.toString("utf8")??null;if(r===null)return{raw:r,raw_bytes:n,entries:[]};if(await bn({path:e,scope:"project"}),r.trim()==="")return{raw:r,raw_bytes:n,entries:[]};let o=Xo(r);if(o)throw new g(`History for ${t} contains merge conflict markers at line ${o.line} (${o.marker}). Resolve <<<<<<< ======= >>>>>>> markers and retry.`,h.GENERIC_FAILURE,{code:"history_merge_conflict_markers_detected",required:"Repair the history stream by resolving merge-conflict markers.",why:"Conflict markers break JSONL parsing and invalidate deterministic audit history.",examples:[`pm history ${t}`,`pm restore ${t} <timestamp-or-version>`],nextSteps:["Resolve or restore the history file, then rerun the command."]});let i=[];for(let[s,a]of r.split(/\r?\n/).entries()){let c=a.trim();if(c)try{i.push(JSON.parse(c))}catch{throw new g(`History for ${t} contains invalid JSON at line ${s+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_json_invalid",nextSteps:[`Run pm history-repair ${t} --salvage-tail --dry-run to check whether only an invalid suffix is damaged.`]})}}return{raw:r,raw_bytes:n,entries:i}}async function Mt(e,t){return(await _i(e,t)).entries}(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]="3c2c29c0-0034-54d4-9dbd-2e9af047784e")}catch{}})();var Ij=1,PS=["docs_add","files_add","history:author-acknowledge","history_author_acknowledge","history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","normalize","release","test_run_track","tests_add","tests_remove","tests_update","update_audit","update_ownership_bypass"],MS=["append","cancel","claim","close","comment_add","create","learning_add","note_add","reopen"],$S=new Set(PS),jS=new Set(MS),LS=new Set(["actual_result","affected_version","assignee","blocked_by","blocked_reason","close_reason","confidence","customer_impact","definition_of_ready","dependencies","docs","environment","expected_result","files","fixed_version","goal","impact","learnings","notes","objective","order","outcome","parent","release","reminders","reporter","repro_steps","resolution","reviewer","severity","sprint","tests","test_runs","unblock_note","updated_at","value","why_now"]);function FS(e){let t=e.path.split("/").filter(Boolean);return t[0]==="metadata"||t[0]==="front_matter"?t[1]:t[0]==="body"?"body":void 0}function Cn(e){return e.event_class==="substantive"||e.event_class==="maintenance"?e.event_class:$S.has(e.op)?"maintenance":jS.has(e.op)||e.op!=="update"?"substantive":Array.isArray(e.patch)&&e.patch.length>0&&e.patch.every(t=>{let n=FS(t);return n!==void 0&&LS.has(n)})?"maintenance":"substantive"}(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]="a65d6520-0e6f-5627-a4dd-bd455c2db0fa")}catch{}})();var Xm=new WeakMap;function xj(e,t){Xm.set(e,new Set(t))}var yi='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',US={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},zS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function Nj(e,t,n){if(e&&t)throw new g(`${n} cannot be combined with --full`,h.USAGE)}function xe(e,t=new Set){let n=e.filter(r=>!t.has(r.name)).map(r=>({...r}));return{has_omissions:n.length>0,omitted_field_group_count:n.length,omitted_field_groups:n}}function Dj(e,t){let n=zS.find(o=>o.command===e);if(n===void 0)throw new TypeError(`Unknown mode-paired output command: ${e}`);if(t===n.complete_mode)return xe([]);let r=n.omissions_by_mode[t];if(r===void 0)throw new TypeError(`Unknown ${e} output mode: ${t}`);return xe(r)}var HS=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function ne(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var qS=new Set([void 0,"tabular_when_uniform"]),VS=new Set(["collection","none"]),BS=new Set(["supported","unsupported"]);function Km(e,t){return Array.isArray(e)&&(t||e.length>0)&&e.every(n=>typeof n=="string"&&n.length>0)&&new Set(e).size===e.length}function WS(e){return ne(e)&&typeof e.command=="string"&&e.command.trim().length>0&&VS.has(e.row_kind)&&Km(e.row_keys,!0)&&(e.continuation_row_keys===void 0||Km(e.continuation_row_keys,!1))&&BS.has(e.fields)&&qS.has(e.toon_encoding)&&(e.row_kind==="collection"?e.row_keys.length>0&&typeof e.jq_selector=="string"&&e.jq_selector.trim().length>0:e.row_keys.length===0&&e.jq_selector===void 0)}var GS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},KS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function YS(e,t){let n=e.trim().toLowerCase().split(/\s+/u,1)[0],r=n?.startsWith("list-")?"list":n;if(r==="graph"){let s=typeof t.subcommand=="string"?t.subcommand:"";if(s.length===0)return;let a=GS[s];if(a===void 0)return;let c=a.filter(d=>Array.isArray(t[d])||ne(t[d]));return{command:"graph",row_kind:c.length>0?"collection":"none",row_keys:c,fields:"unsupported",...c.length>0?{jq_selector:yi}:{},toon_encoding:"tabular_when_uniform"}}let o=US[r],i=KS[r];return o===void 0||i===void 0||!i.some(s=>Object.hasOwn(t,s))?void 0:(()=>{let s=o.row_keys.filter(a=>{let c=a.split(".").reduce((d,l)=>ne(d)?d[l]:void 0,t);return Array.isArray(c)||ne(c)});return{command:r,row_kind:s.length>0?"collection":"none",row_keys:s,fields:o.fields,...s.length>0?{jq_selector:yi}:{},toon_encoding:"tabular_when_uniform"}})()}function XS(e){if(!ne(e.projection)||typeof e.projection.mode!="string"||e.projection.mode.trim().length===0)return;let t=e.projection.declared_field_groups,n=e.projection.included_field_groups;if(!Array.isArray(t)||!Array.isArray(n))return;let r=t.filter(s=>ne(s)&&typeof s.name=="string"&&s.name.trim().length>0&&typeof s.restore_with=="string"&&s.restore_with.trim().length>0),o=n.filter(s=>typeof s=="string");if(r.length!==t.length||o.length!==n.length)return;let i=new Set(r.map(s=>s.name));if(!(i.size!==r.length||new Set(o).size!==o.length||o.some(s=>!i.has(s))))return xe(r,new Set(o))}function JS(e){if(!Array.isArray(e.sections_included))return;let t=xe(HS,new Set(e.sections_included.filter(n=>typeof n=="string")));return ne(e.summary)&&e.summary.scope==="matching_items"&&(t.summary_scope="matching_items"),t}function ZS(e,t,n){if(e==="dependency_provenance")return!1;let r=Jm(e);if(r!==void 0){let o=n[r.facet];return ne(o)&&Object.hasOwn(o,r.member)}return Object.hasOwn(t,e)||(e==="reminders"||e==="events")&&ne(n.schedule)&&Object.hasOwn(n.schedule,e)||["files","tests","docs"].includes(e)&&ne(n.linked)&&Array.isArray(n.linked[e])&&n.linked[e].length>0}function Jm(e){let t=e.indexOf(".");return t===-1?void 0:{facet:e.slice(0,t),member:e.slice(t+1)}}function QS(e){if(!ne(e.item))return;let t=e.item,n=["comments","notes","learnings","files","tests","docs","reminders","events"],r=["body","children","claim_state","linked","schedule"],o=Xm.get(e),i=a=>n.includes(a)||a==="body"||a==="dependency_provenance"?t:e,s=["body",...n,...r.slice(1),...o?.has("dependency_provenance")?["dependency_provenance"]:[],...o?.has("blockers")||Object.hasOwn(e,"blockers")?["blockers"]:[],...[...o??[]].filter(a=>Jm(a)!==void 0)].filter(a=>o===void 0||o.has(a)||Object.hasOwn(i(a),a)).map(a=>({name:a,restore_with:a==="blockers"?"--full":a==="dependency_provenance"?"--fields dependencies":`--fields ${a}`}));return xe(s,new Set(s.flatMap(({name:a})=>ZS(a,i(a),e)?[a]:[])))}function Ym(e){if(ne(e.projection))return xe([{name:"full_item_fields",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_item_fields"]:[]))}function eO(e){if(!ne(e.projection))return xe([]);if(typeof e.projection.mode=="string")return xe([{name:"full_check_details",restore_with:"--full"}],new Set(e.projection.mode==="full"?["full_check_details"]:[]))}function tO(e){if(!(!ne(e.selected)||typeof e.selected.summary!="boolean"))return xe([{name:"full_contract_catalog",restore_with:"--full"}],new Set(e.selected.summary?[]:["full_contract_catalog"]))}function nO(e,t){let n=XS(t);if(n!==void 0)return n;let[r]=e.split(/\s+/u,1);if(r==="context")return JS(t);if(r==="get")return QS(t);if(r==="list"||r.startsWith("list-"))return Ym(t);if(r==="search")return Ym(t)??xe([{name:"projection_metadata",restore_with:"--full"}]);if(r==="health")return eO(t);if(r==="contracts")return tO(t)}function Zm(e,t){if(e===void 0||!ne(t))return t;let n=nO(e,t),r=t.row_contract,o=WS(r)?r:YS(e,t),i=o!==void 0?{...t,row_contract:o}:Object.hasOwn(t,"row_contract")?Object.fromEntries(Object.entries(t).filter(([s])=>s!=="row_contract")):t;return ne(i.omission_receipt)||n===void 0?i:{...i,omission_receipt:n}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="f539ecb5-2f49-5867-96c7-48eddb81a628")}catch{}})();var rO=new Set(["applied_bound","completeness","budget_retention_policy","continuation_contract","continuation_kind","continuation_path","filters","omission_receipt","output_budget_truncation","projection","read_output","read_session","row_contract","sorting"]);function J(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qm(e,t){let n=e;for(let r of t.split("."))if(Array.isArray(n)){if(!/^\d+$/u.test(r))return;n=n[Number(r)]}else{if(!J(n))return;n=n[r]}return n}function _c(e,t,n){let r=t.split("."),o=(i,s)=>{if(s===r.length)return n;let a=r[s];if(Array.isArray(i)){let d=Number(a),l=[...i];return l[d]=o(i[d],s+1),l}let c=i;return{...c,[a]:o(c[a],s+1)}};return o(e,0)}function yc(e,t,n,r){let o=Rn(e).find(a=>a.path===t);if(!o)return e;let i=Array.isArray(o.value)?o.value.slice(n,r):Object.fromEntries(Object.entries(o.value).slice(n,r)),s=_c(e,t,i);return J(s.summary)&&J(s.summary.focus_row_states)&&typeof s.summary.focus_row_states[t]=="string"&&(s.summary={...s.summary,focus_row_states:{...s.summary.focus_row_states,[t]:s.summary.focus_row_states[t].slice(n,r)}}),Rr(s),s}function gi(e){let t=e.row_contract;return J(t)&&Array.isArray(t.row_keys)?t.row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):Object.entries(e).filter(([,n])=>Array.isArray(n)).map(([n])=>n)}function oO(e){let t=e.row_contract;return J(t)&&Array.isArray(t.continuation_row_keys)?t.continuation_row_keys.filter(n=>typeof n=="string"&&n.trim().length>0):gi(e)}function rt(e){return gi(e).flatMap(t=>{let n=Qm(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function Rn(e){return oO(e).flatMap(t=>{let n=Qm(e,t);return Array.isArray(n)||J(n)?[{path:t,value:n}]:[]})}function Tr(e){let t=rt(e),n=new Set(t.map(o=>o.path)),r=(o,i)=>{if(Array.isArray(o)){n.has(i)||t.push({path:i,value:o}),o.forEach((s,a)=>r(s,`${i}.${a}`));return}if(J(o))for(let[s,a]of Object.entries(o))i.length===0&&rO.has(s)||r(a,i.length===0?s:`${i}.${s}`)};return r(e,""),t}function xn(e){return rt(e).reduce((t,n)=>t+(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length),0)}function Cr(e,t){let n=e;for(let r of rt(n)){let o=Array.isArray(r.value)?r.value.map((i,s)=>t(i,r.path,s)):Object.fromEntries(Object.entries(r.value).map(([i,s],a)=>[i,t(s,r.path,a)]));n=_c(n,r.path,o)}return n}function ep(e,t,n=()=>!1){let r=e,o=!1;for(let i of rt(r)){let s=Array.isArray(i.value)?i.value:Object.entries(i.value);if(s.length<=t)continue;o=!0;let a=n(i.path)?s.length-t:0,c=s.slice(a,a+t),d=Array.isArray(i.value)?c:Object.fromEntries(c);r=_c(r,i.path,d)}return{result:r,truncated:o}}var tp=["high_level","low_level","blocked_fallback"];function hi(e){let t=e.status==="in_progress"?"i":"o";return e.blocked===!0?t.toUpperCase():t}function Mj(e,t){if(!J(e.summary)||!J(e.summary.returned_focus))return;let n=new Map(t.map(r=>[r.id,r]));e.summary={...e.summary,focus_row_states:Object.fromEntries(tp.map(r=>[r,Array.isArray(e[r])?e[r].filter(J).map(o=>hi(n.get(o.id)??o)).join(""):""]))}}function iO(e,t){if(e!==void 0){if(typeof e!="string"||e.length!==t||!/^[iIoO]*$/u.test(e))throw new TypeError("Context focus classification receipt must contain one i/I/o/O code per delivered record");return e}}function sO(e,t,n,r){let o=Array.isArray(t[n])?t[n].filter(J):[],i=iO(r[n],o.length)??o.map(hi).join(""),s=new Map(o.flatMap((d,l)=>d.id===void 0?[]:[[d.id,i[l]]])),a=Array.isArray(e[n])?e[n].filter(J):[],c=!1;return{states:a.map((d,l)=>{let u=s.get(d.id)??(d.id===void 0?i[l]:void 0)??hi(d);return u!==hi(d)&&(c=!0),u}).join(""),needsStates:c}}function aO(e,t){typeof e.count=="number"&&(e.count_only===!0||t.count_only===!0?typeof t.count=="number"&&(e.count=t.count):Array.isArray(e.items)&&(e.count=e.items.length))}function Rr(e,t=e){if(aO(e,t),!J(e.summary)||!J(e.summary.returned_focus))return;let n={...e.summary},r=J(t.summary)&&J(t.summary.focus_row_states)?t.summary.focus_row_states:{},o=tp.map(c=>({key:c,...sO(e,t,c,r)})),i=Object.fromEntries(o.map(({key:c,states:d})=>[c,d])),s=o.some(c=>c.needsStates),a=Object.values(i).join("");typeof n.high_level=="number"&&(n.high_level=Array.isArray(e.high_level)?e.high_level.length:0),typeof n.low_level=="number"&&(n.low_level=Array.isArray(e.low_level)?e.low_level.length:0),n.returned_focus={active_items:a.length,in_progress:[...a].filter(c=>c.toLowerCase()==="i").length,open:[...a].filter(c=>c.toLowerCase()==="o").length,blocked:[...a].filter(c=>c===c.toUpperCase()).length},s?n.focus_row_states=i:delete n.focus_row_states,e.summary=n}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="2335ae7f-c7aa-5bdd-ac2e-e6d7a74be2e1")}catch{}})();var bi="changed_fields",cO="changed_field_count",hc="rows",dO=new Set(["apply","rollback"]),ip=new Set(["deleted","would_delete"]),np=256,rp={start_task:["claim","update"],pause_task:["update","release"],close_task:["close","release"]};function lO(e,t){if(!se(e)||typeof e.action!="string"||typeof e.id!="string"||e.id.length===0)return null;let n=Object.hasOwn(rp,e.action)?rp[e.action]:void 0;if(!n||!n.every(i=>{let s=e[i];return se(s)&&se(s.item)&&s.item.id===e.id&&Array.isArray(s.changed_fields)&&s.changed_fields.every(a=>typeof a=="string")}))return null;let r=e[n.at(-1)],o=ap(r);return t.idOnly?o:!t.compactEnvelope&&t.changedFields!=="compact"?null:{...e,...t.compactEnvelope?{...o,changed_field_count:new Set(n.flatMap(i=>e[i].changed_fields)).size}:{},...Object.fromEntries(n.map(i=>[i,xr(e[i],t)]))}}function op(e){return typeof e!="string"||e.length<=np?e:`${Ee(e,np-1)}\u2026`}function uO(e){if(!se(e))return null;let t={...e};return t.reason=op(t.reason),se(t.previous_terminal)&&(t.previous_terminal=Object.fromEntries(Object.entries(t.previous_terminal).map(([n,r])=>[n,op(r)]))),t}function se(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function sp(e){let t=e[bi];if(!Array.isArray(t))return null;let n=Object.getPrototypeOf(e)===null?Object.create(null):{};for(let[r,o]of Object.entries(e))r!==bi&&(n[r]=o);return n[cO]=t.length,n}function fO(e){return"item"in e&&Array.isArray(e[bi])}function mO(e){return typeof e.mode=="string"&&dO.has(e.mode)&&Array.isArray(e[hc])}function pO(e,t){let n=Object.getPrototypeOf(e)===null?Object.create(null):{};return Object.assign(n,e),n[hc]=t,n}function ap(e){if(!se(e))return null;let t=se(e.item)?e.item:se(e.plan)?e.plan:null;if(t===null)return null;let n=typeof t.id=="string"?t.id:void 0,r=typeof e.outcome=="string"&&ip.has(e.outcome)?e.outcome:typeof t.status=="string"?t.status:void 0;return n?r?{id:n,status:r,...typeof e.deleted=="boolean"?{deleted:e.deleted}:{}}:{id:n}:null}function _O(e,t){if(!se(e))return null;if(se(e.plan)&&se(e.mutation_receipt)&&e.mutation_receipt.kind==="plan_mutation"&&e.mutation_receipt.id===e.plan.id&&e.mutation_receipt.action===e.action)return e.mutation_receipt;if(!t||!se(e.item)||typeof e.item.id!="string")return null;let n=e[bi];if(!Array.isArray(n))return null;let r={id:e.item.id,...typeof e.outcome=="string"&&ip.has(e.outcome)?{status:e.outcome}:typeof e.item.status=="string"?{status:e.item.status}:{},...typeof e.deleted=="boolean"?{deleted:e.deleted}:{},...typeof e.previous_status=="string"?{previous_status:e.previous_status}:{},changed_field_count:n.length};return yO(e,e.item,r),r}function yO(e,t,n){let r=typeof e.close_reason=="string"?e.close_reason:typeof t.close_reason=="string"?t.close_reason:void 0;r!==void 0&&(n.close_reason=r);let o=uO(e.recurrence);o!==null&&(n.recurrence=o),Array.isArray(e.warnings)&&e.warnings.length>0&&(n.warnings=e.warnings);for(let i of["recovery","follow_up","handoff","completion","start"])se(e[i])&&(n[i]=e[i]);if(typeof e.claimed_by=="string"||typeof e.released_by=="string")for(let i of["claimed_by","released_by","previous_assignee","forced","skipped","available","attempts","start_refused","suggestions"])Object.hasOwn(e,i)&&(n[i]=e[i])}function hO(e){let t=mO(e)?e[hc]:void 0;if(!Array.isArray(t))return{projected:e,changed:!1};let n=!1,r=t.map(o=>{if(!se(o))return o;let i=sp(o);return i?(n=!0,i):o});return n?{projected:pO(e,r),changed:!0}:{projected:e,changed:!1}}function xr(e,t={}){let n=lO(e,t);if(n!==null)return n;if(t.idOnly===!0){let a=ap(e);if(a!==null)return a}if(t.compactEnvelope===!0||t.changedFields==="compact"){let a=_O(e,t.compactEnvelope===!0);if(a!==null)return a}if((t.changedFields??"full")==="full"||!se(e))return e;let r=!1,o=e,i=fO(e)?sp(e):null;i!==null&&(o=i,r=!0);let s=hO(o);return s.changed&&(o=s.projected,r=!0),r?o:e}import{AsyncLocalStorage as JA}from"node:async_hooks";(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]="1b67272d-8924-5b1b-97cd-74a6a10493be")}catch{}})();function gc(e){let t=e.trim().toLowerCase().startsWith("extension:"),n=e.trim().toLowerCase().replace(/^extension:/u,"");if(mn(n))return;let r=mf()?.commands??[],o=[...r].reverse().find(s=>s.command===n)?.command??(t?void 0:r.find(s=>s.action===n)?.command),i=[...r].reverse().find(s=>s.command===o);return i===void 0||mn(i.command)||mn(i.action)?void 0:i}function gO(e){let t=gc(e);return t?.read_output===void 0?void 0:t}function cp(e,t){let n=gO(e),r=n?.read_output;if(r===void 0)return t;if(typeof t!="object"||t===null||Array.isArray(t))throw new g("Read-only extension commands must return a structured object.",h.USAGE,{code:"extension_read_output_invalid"});for(let o of r.row_keys){let i=t;for(let s of o.split("."))i=typeof i=="object"&&i!==null&&Object.hasOwn(i,s)?Reflect.get(i,s):void 0;if(i===null||typeof i!="object")throw new g(`Read-only extension result is missing declared row collection ${o}.`,h.USAGE,{code:"extension_read_output_invalid"})}return{...t,row_contract:{command:`extension:${n.command}`,row_kind:r.row_keys.length>0?"collection":"none",row_keys:[...r.row_keys],fields:"supported",...r.row_keys.length>0?{jq_selector:yi}:{},toon_encoding:"tabular_when_uniform"}}}import{createHash as DA}from"node:crypto";import{createHash as IA}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]="040fff2e-c66f-5091-9ea8-7dcdaf6e203b")}catch{}})();var bc={list:{include:["--brief","--compact","--fields","--full"],amount:["--after","--limit","--no-truncate"],cost:["--token-budget"],encoding:["--format","--stream"]},context:{include:["--fields","--section"],amount:["--after","--depth","--limit"],cost:["--token-budget"],encoding:["--format"]},search:{include:["--compact","--fields","--full"],amount:["--after","--limit"],cost:["--token-budget"],encoding:["--format"]},get:{include:["--fields","--full"],amount:["--depth"],cost:["--token-budget"],encoding:["--format"]},next:{amount:["--blocked-limit","--limit"],encoding:["--format"]},health:{include:["--brief","--check-only","--full","--summary"]},deps:{include:["--collapse","--full","--summary"],amount:["--edge-limit","--max-depth","--node-limit"],cost:["--token-budget"],encoding:["--format"]},graph:{include:["--full","--summary"],amount:["--after","--limit","--max-depth","--max-paths"]},history:{include:["--compact","--full"],amount:["--limit"],encoding:["--format"]},activity:{include:["--compact","--full"],amount:["--limit","--unbounded","--after"],encoding:["--stream"]},validate:{include:["--counts","--full"]},events:{include:["--full"],amount:["--limit"],encoding:["--follow"]},contracts:{include:["--full","--summary"]},comments:{amount:["--limit"]},notes:{amount:["--limit"]},learnings:{amount:["--limit"]},files:{amount:["--limit","--no-truncate","--offset"]},docs:{},stats:{},aggregate:{},duplicates:{amount:["--limit"]},"package-catalog":{},"package-manage":{},"comments-audit":{},assurance:{}},wc=new Set(["--collapse","--fields","--section"]),wi=Object.freeze({"--after":"--after retains cursor-position semantics; use --output-limit <n> separately to bound returned rows.","--check-only":"--check-only retains health side-effect semantics; --output-include does not suppress vector refresh.","--collapse":"--collapse retains dependency grouping semantics; --output-include does not replace it.","--depth":"--depth retains traversal or detail-depth semantics; --output-limit does not replace it.","--follow":"--follow retains event-tail semantics; --output-format does not enable following.","--max-depth":"--max-depth retains graph traversal-depth semantics; --output-limit does not replace it.","--max-paths":"--max-paths retains graph path-search semantics; use --output-limit separately to bound returned rows.","--no-truncate":"--no-truncate is a compatibility alias; prefer --output-limit unbounded --output-budget unbounded.","--offset":"--offset retains positional pagination semantics; use --output-limit separately to bound returned rows.","--stream":"--stream retains command streaming semantics; --output-format selects only static result encoding.","--unbounded":"--unbounded is a compatibility alias; prefer --output-limit unbounded."});function vi(e){return e.slice(2).replaceAll("-","_")}function dp(e,t={}){let n=e==="package catalog"||e==="packages catalog"||e==="package-catalog"||(e==="package"||e==="packages"||e==="extension")&&(t.catalog===!0||t.target==="catalog"||t.action==="catalog")?"package-catalog":e==="package manage"||e==="package-manage"?"package-manage":e.split(" ")[0],r=n.startsWith("list-")?"list":n==="ctx"?"context":n;return Et.includes(r)?r:void 0}function vc(e){return new Map((bc[e]?.include??[]).filter(t=>!wc.has(t)&&wi[t]===void 0).map(t=>[vi(t),Ec(t)]))}function Ec(e){return e.slice(2).replace(/-([a-z])/gu,(t,n)=>n.toUpperCase())}import{stripVTControlCharacters as bO}from"node:util";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="493a0675-0114-5b93-b3b4-5bd895ac691f")}catch{}})();var wO=["full","compact","brief","summary","counts"],Jj=["mutation","read","discovery","governance"],up=["error","warning","validation_summary","recovery_bundle"],vO=["full","omit_explanation","limit_collections","compact_recovery","action_only"],EO=new Set(["append","claim","close","close-many","close-task","comments","config","copy","create","delete","docs","event","files","focus","history-author-acknowledge","history-compact","history-redact","history-repair","init","item","learnings","meet","notes","pause-task","release","remind","restore","schema","start-task","update","update-many"]),kO=new Set(["contracts","extension","help","install","package","packages","profile","upgrade"]),SO=new Set(["gc","health","merge","stats","telemetry","test","test-all","validate"]),OO={mutation:2e3,read:4e3,discovery:3e3,governance:6e3},AO=3,IO=2,TO=192,CO={error:{text:768,json:2e3},warning:{text:768,json:2e3},validation_summary:{text:1500,json:3e3},recovery_bundle:{text:768,json:2e3}},RO=up.map(e=>({diagnostic_class:e,default_max_estimated_tokens_by_format:CO[e],minimum_max_estimated_tokens:TO,degradation_ladder:vO,corrective_action_paths:["required","recovery.suggested_retry","recovery.suggested_retry_args","recovery.next_best_command","next_steps[0]"],token_estimate:"ceil(utf8_bytes / 4)"})),xO=new Map(RO.map(e=>[e.diagnostic_class,e]));function NO(e){let[t=""]=Kn(e).split(/\s+/u);return EO.has(t)?"mutation":kO.has(t)?"discovery":SO.has(t)?"governance":"read"}function fp(e,t=NO(e)){let n=e.trim().replace(/\s+/gu," ");if(n.length===0)throw new TypeError("command must be a non-empty command path");let r=OO[t];return DO({command:n,budget_class:t,default_max_estimated_tokens:r,default_max_estimated_tokens_by_format:{toon:r,json:Math.ceil(r*AO/IO)},degradation_ladder:wO,allows_unbounded_opt_out:!0,token_estimate:"ceil(utf8_bytes / 4)"})}function DO(e){if(!Number.isSafeInteger(e.default_max_estimated_tokens)||e.default_max_estimated_tokens<=0)throw new RangeError("default_max_estimated_tokens must be a positive safe integer");for(let[t,n]of Object.entries(e.default_max_estimated_tokens_by_format))if(!Number.isSafeInteger(n)||n<=0)throw new RangeError(`default_max_estimated_tokens_by_format.${t} must be a positive safe integer`);return e}var PO=io.map(e=>fp(e)),MO=new Map(PO.map(e=>[e.command,e]));function mp(e,t={}){let n=e.trim().replace(/\s+/gu," "),[r]=Kn(n).split(" "),o=MO.get(r);return o?{...o,command:n}:t.generateFallback?fp(n):null}function jt(e){return Math.ceil(Math.max(0,e)/4)}function pp(e){let t=xO.get(e);if(t===void 0)throw new TypeError(`diagnosticClass must be one of: ${up.join(", ")}`);return t}function ot(e){return jt(Buffer.byteLength(JSON.stringify(e,null,2),"utf8"))}function $O(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function kc(e){if(!$O(e))return;let t={};for(let n of["suggested_retry","suggested_retry_args","next_best_command","allowed_values","candidate_commands","missing","missing_required_fields","option_scope","retry_after_ms","waited_ms","owner_handoffs"]){let r=e[n];Array.isArray(r)?t[n]=n==="suggested_retry_args"?r:r.slice(0,3):r!==void 0&&(t[n]=r)}return Object.keys(t).length>0?t:void 0}function jO(e,t){return typeof e!="string"||e.length<=t?e:`${Ee(e,Math.max(1,t-3))}...`}function $t(e,t){if(Buffer.byteLength(e,"utf8")<=t)return e;let n="...",r=Array.from(e),o=0,i=r.length;for(;o<i;){let s=Math.ceil((o+i)/2),a=`${r.slice(0,s).join("")}${n}`;Buffer.byteLength(a,"utf8")<=t?o=s:i=s-1}return`${r.slice(0,o).join("")}${n}`}function _p(e){let t={};for(let n of["code","required","recovery","next_steps","exit_code","type","title","detail","why","examples"])Object.hasOwn(e,n)&&e[n]!==void 0&&(t[n]=e[n]);for(let[n,r]of Object.entries(e))n!=="__proto__"&&!Object.hasOwn(t,n)&&(t[n]=r);return t}var LO=new Set(["limit_collections","compact_recovery","action_only"]),FO=new Set(["compact_recovery","action_only"]);function UO(e){let t={code:typeof e.code=="string"?e.code:"diagnostic",required:jO(e.required,160)??"Inspect the diagnostic code and retry with corrected input."},n=kc(e.recovery);return n!==void 0?t.recovery=n:Array.isArray(e.next_steps)&&(t.next_steps=e.next_steps.slice(0,1)),e.exit_code!==void 0&&(t.exit_code=e.exit_code),e.type!==void 0&&(t.type=e.type),t}function zO(e,t){let n=structuredClone(e);if(t!=="full"&&(delete n.why,delete n.examples),LO.has(t))for(let[r,o]of Object.entries(n))Array.isArray(o)&&(n[r]=o.slice(0,3));if(FO.has(t)){let r=kc(n.recovery);r?n.recovery=r:delete n.recovery}return t!=="action_only"?_p(n):UO(n)}function Nn(e,t){let n={...e,diagnostic_output:{...t,estimated_tokens:0}};for(let r=0;r<4;r+=1){let o=ot(n),i=n.diagnostic_output;if(i.estimated_tokens===o)break;i.estimated_tokens=o}return n}function HO(e,t,n){let r=Nn(e,t);for(let i of["recovery","exit_code"])ot(r)<=n||e[i]===void 0||(delete e[i],r=Nn(e,t));let o=40;for(;ot(r)>n&&o>4;)o-=4,e.code=$t(String(e.code),o),e.required=$t(String(e.required),o),r=Nn(e,t);return r}function qO(e,t){let n=e.diagnostic_output,{estimated_tokens:r,...o}=n,i=o.omitted_fields.slice(0,8).map(u=>$t(u,32)),s={...o,omitted_fields:i,...o.omitted_fields.length>i.length?{omitted_fields_overflow_count:o.omitted_fields.length-i.length}:{}},a=kc(e.recovery),c=a&&ot(a)<=48?a:void 0,d={code:$t(String(e.code),320),required:$t(String(e.required),320),...c?{recovery:c}:{},...e.exit_code!==void 0?{exit_code:e.exit_code}:{}},l=Nn(d,s);for(;ot(l)>t&&s.omitted_fields.length>0;)s.omitted_fields.pop(),s.omitted_fields_overflow_count=o.omitted_fields.length-s.omitted_fields.length,l=Nn(d,s);return l=HO(d,s,t),l}function Zj(e,t={}){let n=e,r=t.diagnosticClass??"error",o=pp(r),i=t.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.json,a=ot(n),c=Object.keys(n);if(a<=s)return _p(structuredClone(n));let d;for(let[l,u]of o.degradation_ladder.entries()){let f=zO(n,u),m=c.filter(y=>!Object.hasOwn(f,y)),_=Nn(f,{diagnostic_class:r,format:"json",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:a,truncated:l>0,degradation_steps:o.degradation_ladder.slice(0,l+1),omitted_fields:m});if(d=_,ot(_)<=s)break}return ot(d)>s&&(d=qO(d,s)),d}function lp(e){return bO(e).replace(/\r\n/gu,`
18
+ `).replace(/[^\P{Cc}\n]/gu," ")}function Qj(e,t,n={}){let r=n.diagnosticClass??"error",o=pp(r),i=n.maxEstimatedTokens;if(i!==void 0&&(!Number.isSafeInteger(i)||i<o.minimum_max_estimated_tokens))throw new RangeError(`maxEstimatedTokens must be a safe integer >= ${o.minimum_max_estimated_tokens}`);let s=i??o.default_max_estimated_tokens_by_format.text,a=lp(e),c=jt(Buffer.byteLength(a,"utf8")),d=c>s,l=`What is required:
19
19
  `,u=`
20
20
 
21
- ${jt(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
21
+ ${$t(a.trimStart().split(/\r?\n/u,1)[0].trim(),320)}
22
22
 
23
- Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=ip(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${jt(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:$t(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}var wc=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function L$(e){return e?.trim()===wc.required}function F$(e){let t=e?.trim();return t!==void 0&&wc.why.includes(t)}function U$(e){return(e??[]).filter(t=>!wc.examples.includes(t.trim()))}var z$=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function H$(e){if(!e)return;let{attempted_command:t,normalized_args:n,provided_fields:r,...o}=e;return Object.values(o).some(i=>i!==void 0)?o:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a351971-6cfb-55eb-a266-3fec0af9eaa4")}catch{}})();var ve=Object.freeze({comments:Object.freeze({paths:Object.freeze(["comments"]),total_key:"total_count"}),notes:Object.freeze({paths:Object.freeze(["notes"]),total_key:"total_count",delivered_row_counters:Object.freeze([Object.freeze({key:"structured_event_count",field:"format",equals:"json"})])}),learnings:Object.freeze({paths:Object.freeze(["learnings"]),total_key:"total_count"})});function Lt(e,t){return e===void 0?!1:(Object.hasOwn(ve,e)?ve[e]:void 0)?.paths.includes(t)===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function Y$(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var vc=256,Ec=1e4,MO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,up=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,jO=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),$O=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&MO.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=vc,reason:`token_budget must be a safe integer of at least ${vc}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=Ec&&e.seen_item_ids.every(t=>typeof t=="string"&&up.test(t)),reason:`seen_item_ids must contain at most ${Ec} portable item identifiers.`}];function Ei(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vi(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function ki(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{vi("must be a valid JSON object.")}Ei(t)||vi("must be a JSON object.");let n=Object.keys(t).filter(i=>!jO.has(i));n.length>0&&vi(`contains unknown field "${n.sort()[0]}".`);let r=$O.find(i=>!i.valid(t));r!==void 0&&vi(r.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function fp(e){if(Ei(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:Ei(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function LO(e){let t=new Set,n=0,r=rt(e),o=new Set(r.map(({path:s})=>s)),i=Object.entries(e).flatMap(([s,a])=>Array.isArray(a)&&!o.has(s)?[{path:s,value:a}]:[]);for(let s of[...r,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!Ei(c))continue;if(typeof c.context_ref=="string"){n+=1;continue}let d=fp(c);d!==void 0&&up.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:n}}function mp(e,t){let n=new Set(t.seen_item_ids);return Tr(e,r=>{let o=fp(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function kc(e,t,n){let{deliveredIds:r,suppressedRepeatCount:o}=LO(e),i=new Set(t.seen_item_ids),s=[...r].filter(y=>!i.has(y)).sort(),a=s.slice(0,Ec-t.seen_item_ids.length),c=[...t.seen_item_ids,...a].sort(),d=s.length-a.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:r.size,...d===0?{}:{seen_item_overflow_count:d},suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --depth brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:c}},u={...e,read_session:l},f=y=>{l.spent_this_call_tokens=y,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,y),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<vc,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let b=it(u,n);if(b===m)return u;_=Math.max(_,b),m=b}return f(_),u}function pp(e){return Math.max(0,e.token_budget-e.spent_tokens)}(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]="1cc0fcb7-2aaa-5233-bdfd-4b4d0fb3e9c1")}catch{}})();var xr=Symbol.for("pm.readOutputInvocationProvenance");function J$(e,t){return Reflect.set(e,xr,{canonical_include_modes:[...t],explicit_legacy_aliases:[],sdk_invocation_observed:!0}),e}(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]="2a596392-747a-5b55-854d-1e80964468d3")}catch{}})();var Ft=["include","amount","cost","encoding"],kp=["canonical","legacy","intent","default"],Pr=To,hL=Object.freeze(Ft.map(e=>Pr[e])),gL=Co;function FO(e,t){let n=bi[e];if(n!==void 0)return n;let r=t==="include"?yc.has(e)?"<csv>":wi(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Pr[t]} ${r}.`}function Sp(e){let t=_c[e]??{},n=Object.freeze(Object.fromEntries(Ft.map(r=>[r,Object.freeze({dimension:r,canonical_option:Pr[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:bi[o]===void 0?"replacement":"behavior_preserving",migration_hint:FO(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:kp,budget_retention_policy:e==="assurance"?"verdict_priority":Object.hasOwn(ve,e)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...hc(e).keys()])})}var UO=Object.freeze(Et.map(Sp)),zO=new Map(UO.map(e=>[e.command,e]));function at(e,t={}){let n=Gn(e.trim().toLowerCase()),r=pc(n);return r!==void 0?r.read_output===void 0?void 0:`extension:${r.command}`:op(n,t)}var HO=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],_p={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function qO(e){return HO.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var VO=[{keys:["outputInclude","output_include"],valid:e=>Nr(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||Dn(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||Dn(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(ki(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],bL="read_output_mutation_conflict",Op=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],wL=Op.map(({flag:e})=>e);function BO(e,t,n){let r=Op.filter(({keys:a})=>a.some(c=>t[c]!==void 0)),o=r.map(({flag:a})=>a),i=r.flatMap(({keys:a})=>a.filter(c=>t[c]!==void 0)),s=o.join(", ");return new g(`Universal output controls (${s}) cannot be combined with a ${e} mutation; nothing was written.`,h.USAGE,{code:"read_output_mutation_conflict",field:o[0],details:{surface:e,output_controls:o,output_option_keys:i,mutation_options:[...n]},required:`Retry the ${e} mutation without ${s}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...WO[e]]})}var WO={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]};function vL(e,t){let n=t.outputFormat??t.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!qO(t))return;let r=at(e,t);if(!r)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if(Object.hasOwn(_p,r)){let o=r,i=_p[o].filter(s=>t[s]!==void 0&&t[s]!==!1);if(i.length>0)throw BO(o,t,i)}for(let o of VO){let i=o.keys.map(s=>t[s]).find(s=>s!==void 0);if(i!==void 0&&!o.valid(i))throw new g(o.message,h.USAGE)}}function Ap(e){let t=at(e);return t?hc(t):new Map}function GO(e,t,n){let r=Nr(t)??[],o=Ap(e),i=[],s=[],a=n,c=a[xr],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of r){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;Oc(Sc(n,y))&&l.add(y),n[_]=!0,s.push(m),d.add(m)}let u=at(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...Nr(n.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[xr]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function EL(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=GO(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function Sc(e,t){let n=gc(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function Oc(e){return e!==void 0&&e!==!1&&e!==null}function Nr(e){let t=(Array.isArray(e)?e:[e]).flatMap(n=>typeof n=="string"?n.split(","):[]).map(n=>n.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function Dn(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function KO(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=Sc(t,o.flag),s={value:i,flag:o.flag};if(Oc(i)&&n(s))return s}}function yp(e,t){let n=Nr(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Nr(t.value)??[wi(t.flag)]}}function hp(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Dn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=Dn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function gp(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Dn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=Dn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function bp(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function Ip(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function YO(e,t,n,r){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||Oc(Sc(r,"--no-truncate"))&&!Ip(n,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function XO(e,t){return Ft.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[Pr[n]]:[])}function Tp(e,t){let n=at(e,t);if(!n)return;let r=zO.get(n)??Sp(n),o=t[xr],i={include:v=>yp(void 0,v),amount:v=>hp(void 0,v),cost:v=>gp(void 0,v),encoding:v=>bp(void 0,v)},s=Object.fromEntries(Ft.map(v=>[v,KO(r.dimensions[v],t,T=>i[v](T)!==void 0,T=>Ip(o,v,T))])),a=Ft.flatMap(v=>{let T=s[v];return T?[T.flag]:[]}),c=Ft.flatMap(v=>{let T=s[v];return T?[r.dimensions[v].legacy_aliases.find(G=>G.flag===T.flag).migration_hint]:[]}),d=bp(t.outputFormat??t.output_format,s.encoding),l=yp(t.outputInclude??t.output_include,s.include),u=hp(t.outputLimit??t.output_limit,s.amount),f=gp(t.outputBudget??t.output_budget,s.cost),m=YO(e,s,o,t),_=cp(e,{generateFallback:!0}),y=d?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",b=f??(m?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:n,include:l,amount:u,cost:b,encoding:d,canonical_options_used:XO({include:l,amount:u,cost:b,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:kp}}function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Ac=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),JO=["collection_counts","notes_count","tests_count"];function Cp(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function QO(e){let t=Y(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...JO.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Ac.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function ZO(e,t){let n=QO(e),r=t.filter(l=>!n.valid.includes(l));if(r.length>0)throw new g(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:n.itemFields.includes(l)?[l]:[]).filter((l,u,f)=>f.indexOf(l)===u);if(o&&i.length>0)throw new g("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",h.USAGE);let s=new Set(t.filter(l=>n.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>Ac.has(l)||s.has(l)));o?a.item=n.item:i.length>0&&(a.item=Cp(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...Y(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function wp(e){let t=0;return Tr({...e},n=>(Y(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function eA(e,t,n,r){if(wp(t)===0||wp(n)>0)return;let o=[...Ap(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new g(`Unknown --output-include selector(s) for ${e}: ${r.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function tA(e,t,n){if(e==="get")return ZO(t,n);let r=hi(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=Tr(s,d=>Y(d)?Cp(d,a):d);return eA(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||Ac.has(s)))}function nA(e,t,n,r){if(t==="unbounded")return e;let{result:o,truncated:i}=Ym(e,t,s=>Lt(n,s));if(!i)return o;if(o.has_more=!0,o.truncated=!0,Dp(o,n,[...r.entries()].flatMap(([s,a])=>a.rows>t?[{path:s,total_rows:a.totalRows}]:[])),typeof o.count=="number"){let s=Y(o.projection)?o.projection.row_key:void 0;o.count=typeof s=="string"&&Array.isArray(o[s])?o[s].length:Rn(o)}return typeof o.returned_count=="number"&&(o.returned_count=Rn(o)),o.applied_bound={kind:"output_limit",source:"explicit",value:t},o}function rA(e){return Ft.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(Pr[t]))}function Si(e,t,n,r){let o=kc(e,t,r);Nn(e,o);for(let i=0;i<8;i+=1){let s=n.estimated_tokens,a=o.read_session.spent_this_call_tokens;st(o,n,r);let c=o;o=kc(o,t,r),Nn(c,o);let d=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===s&&d===a)return o}return o}function Ic(e,t){if(!Y(e.read_output))return e;let n=Pn(t),r=e.read_output,o=ki(t.outputSession??t.output_session);return o===void 0?(st(e,r,n),e):Si(e,o,r,n)}function oA(e,t){if(e!=="validate")return t;let n=Y(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(l=>Y(l)&&l.name==="diagnostic_rows"))return t;let r=[...new Set(Ir(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=r.filter(l=>!r.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=Y(t.row_contract)?t.row_contract:{},s=Array.isArray(i.row_keys)?i.row_keys.filter(l=>typeof l=="string"):[],a=Array.isArray(i.continuation_row_keys)?i.continuation_row_keys.filter(l=>typeof l=="string"):[],c=s.length>0?s:o,d=[...new Set(o)];return JSON.stringify(c)===JSON.stringify(s)&&JSON.stringify(d)===JSON.stringify(a)?t:{...t,row_contract:{...i,row_keys:c,continuation_row_keys:d,jq_selector:typeof i.jq_selector=="string"?i.jq_selector:".checks[].details"}}}function iA(e,t){return e.include?.source==="canonical"&&!Ne(t)}function sA(e,t,n,r,o){let i={...e};if(iA(t,e)&&(i=tA(t.command,i,t.include.value)),t.command==="assurance"&&(i=Up(i)),Cr(i,e),i=zp(i,t.command,r),t.command==="history"&&r){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===r.path)),Y(i.projection)&&(i.projection={...i.projection,row_key:r.path}),Y(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[r.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[r.path]}:{}}}i.count=Object.keys(i[r.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=pA(i,e,t.command,r,o);return t.amount?.source==="canonical"&&(i=nA(i,t.amount.value,t.command,a.collectionsBeforeBudget),a.cursorContinuesExistingPage&&Mp(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),Cr(i,s),Pp(i,t.command,a),{projected:n===void 0?i:mp(i,n),continuationState:a}}function aA(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default"||e.command==="context"&&e.cost.source==="legacy")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:pp(t)}]].sort((n,r)=>n.tokens-r.tokens)[0]}function Rp(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function xp(e,t){return Y(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function cA(e,t,n){return e.command!=="next"||(t.tokenBudget??t.token_budget)===void 0?!1:!(Y(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function Np(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!xp(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function dA(e,t,n,r,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...Np(r),precedence:e.precedence,...Rp(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:o}:{}},a={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:s},c=n===void 0?a:Si(a,n,s,i);if(n===void 0&&st(c,s,i),n!==void 0&&s.estimated_tokens>r.tokens)throw new g("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",h.USAGE);return c}function lA(e,t,n){return e.command==="context"&&e.cost?.source==="legacy"&&!xp(n,e.cost.value)||cA(e,t,n)||t.outputRowContract===!0||t.output_row_contract===!0||e.canonical_options_used.includes("--output-include")||e.command==="list"&&e.canonical_options_used.length>0&&e.include?.value.includes("full")===!0}function uA(e,t,n,r,o){if(t!==void 0||Ne(n)||lA(e,o,n))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(rt(n).some(({value:s})=>(Array.isArray(s)?s.length:Object.keys(s).length)>i))return!1}return e.cost===void 0||e.cost.value==="unbounded"||e.cost.source==="legacy"&&e.command!=="context"||it(o.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,r)<=e.cost.value}function Dp(e,t,n){let r=Object.hasOwn(ve,t)?ve[t]:void 0,o=n.find(i=>r?.paths.includes(i.path));r!==void 0&&o!==void 0&&typeof e[r.total_key]!="number"&&(e[r.total_key]=o.total_rows)}function Pp(e,t,n){let r=ve[t]?.paths[0];r!==void 0&&Fp(e,t,n.producer,n.collectionsBeforeBudget.get(r)?.rows)}function fA(e,t,n,r){let o=n.backward?n.rows-r:n.baseOffset+r;return{path:t,cursor:Tc({command:e,path:t,offset:o,total_rows:n.totalRows,fingerprint:n.fingerprint,...n.backward?{direction:"backward"}:{}}),retained_rows:r,remaining_rows:n.backward?o:n.totalRows-o,total_rows:n.totalRows}}function mA(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(Cn(e).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),d=[...s.entries()].flatMap(([_,y])=>{let b=c.get(_);return b>=y.rows?[]:[fA(t.command,_,y,b)]}),l=d[0];Dp(e,t.command,d);let u=l?"; page --output-cursor":"",f=r.source==="session"?`Truncated by the remaining ${r.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${r.tokens}-token: raise --output-budget${u}`;n.migration_hints=[f,...t.migration_hints];let m=Dr({effective_budget_tokens:r.tokens,measured_result_tokens:i});l&&!o&&(typeof e.next_cursor!="string"||e.continuation_kind==="output_cursor")&&(e.next_cursor=l.cursor),e.continuation_kind=o?"producer_cursor":l?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:d.length>0,recovery_budget_multiplier:l?1:m.recovery_budget_multiplier,continuations:d,restore_with:l?"recovery":`Retry with --output-budget ${m.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${m.output_budget}`,sdk:{outputBudget:m.output_budget},mcp:{outputBudget:m.output_budget}}}}function Mp(e,t,n,r,o){if(typeof n!="string"||!Array.isArray(e.items))return!1;let i=e.items.length,s=t.length;if(i===0||i>=s)return!1;let a;try{a=Cc(n)}catch{return!1}let c=a.after_index;if(c===void 0)return!1;let d=t[i-1];if(Object.prototype.toString.call(d)!=="[object Object]")return!1;let l=Reflect.get(d,"id");if(typeof l!="string"||l.length===0)return!1;let u=r?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=jr(a.fingerprint,l,u,a.snapshot),!0)}function pA(e,t,n,r,o){let i=new Map(Cn(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=r?.path===c.path,u=Lt(n,c.path);return[c.path,{rows:d,totalRows:l?r.total_rows:d,baseOffset:l&&!u?r.offset:0,backward:u,fingerprint:l?r.fingerprint:Oi(c.path,c.value,n)}]})),s=typeof e.next_cursor=="string",a=r?.path==="items"?r.offset:0;return{collectionsBeforeBudget:i,originalItems:Array.isArray(t.items)?a>0?t.items.slice(a):t.items:[],originalItemOffset:a,cursorContinuesExistingPage:s,cursorSource:s?e.next_cursor:o.after,producer:t}}function _A(e,t,n,r,o,i,s,a,c,d){let l={...t,count_only:n},u=r.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>Y(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),r.command==="history"&&Array.isArray(e.diff))for(let m of Ir(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return Ep(e,o,i.tokens,f,d,m=>{Cr(m,l),Pp(m,r.command,a);let _=Mp(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(mA(m,r,o,i,_,c,a.collectionsBeforeBudget),r.command==="history"&&Y(m.projection)){m.has_more=typeof m.next_cursor=="string"||m.applied_bound?.kind==="output_limit";let y=m.projection.row_key;typeof y=="string"&&Array.isArray(m[y])&&(m.count=m[y].length)}s!==void 0&&Object.assign(m,Si(m,s,o,d))},r.command==="history"&&Array.isArray(e.diff),m=>Lt(r.command,m))}function jp(e,t,n){let r=Tp(e,t);if(!r)return n;let o=Pn(t),i=ki(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?Mr(s):void 0,c=rA(r),d=oA(r.command,n);if(a===void 0&&uA(r,i,d,o,t))return d;let l=aA(r,i),u=sA(d,r,i,a,t),f=u.projected;Nn(f,f,t.outputRowContract===!1);let m=Ne(f),_={contract_version:1,command:r.command,requested_dimensions:c,...Np(l,f),precedence:r.precedence,...Rp(r),legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.migration_hints,estimated_tokens:0,within_budget:!m,strings_compacted:!1,rows_compacted:!1,result_omitted:m};if(f.read_output=_,f=i===void 0?f:Si(f,i,_,o),st(f,_,o),l!==void 0&&_.estimated_tokens>l.tokens){let y=vp(r.command,t,f);y!==void 0&&(_.applied_depth="brief",_.degradation_reason="output_budget_reached",Nn(f,y),f=Ic(y,t)),_.estimated_tokens>l.tokens&&(f=_A(f,f,d.count_only===!0,r,_,l,i,u.continuationState,_.estimated_tokens,o))}return l!==void 0&&_.estimated_tokens>l.tokens?dA(r,c,i,l,_.estimated_tokens,o):f}function yA(e){return Y(e)&&Y(e.context_intent)&&e.context_intent.result_omitted===!0}function Ne(e){return hA(e)||yA(e)}function hA(e){return Y(e)&&Y(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function $p(e,t){let n=t.outputFormat??t.output_format;if(n==="json"||n==="toon")return n;let r=Tp(e,t)?.encoding;return r?.value==="json"||r?.value==="toon"?r.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83f3f6fd-bd97-54a4-b39e-c66ec8e333b2")}catch{}})();var bA=4096,wA=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),Lp=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:wA}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function Mn(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Fp(e,t,n=e,r){let o=Object.hasOwn(ve,t)?ve[t]:void 0;if(o?.delivered_row_counters===void 0)return;let i=o.paths[0],s=e[i],a=n[i];if(!Array.isArray(s)||!Array.isArray(a))return;let c=r??a.length,d=a.slice(Math.max(0,c-s.length),c);for(let l of o.delivered_row_counters)typeof e[l.key]=="number"&&(e[l.key]=d.filter(u=>Mn(u)&&u[l.field]===l.equals).length)}function $r(e){return Array.isArray(e)?e.map($r):Mn(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,$r(n)])):e}function Hp(e,t){if(!Mn(e))return $r(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!Mn(i)?[o,$r(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,$r(a)]))]))}function vA(e,t){return Array.isArray(e)?e.map(n=>Hp(n,t)):Hp(e,t)}function Oi(e,t,n){let r=n?Lp[n]:void 0,o=r?.paths.includes(e)===!0;return gA("sha256").update(R({path:e,value:o?vA(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function Tc(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint,...e.direction==="backward"?{d:"b"}:{}}),"utf8").toString("base64url")}function EA(e){return typeof e=="string"&&(at(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function kA(e){return e===void 0||e==="b"}function Mr(e){if(e.length>bA)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!Mn(t)||t.v!==1||!EA(t.c)||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0||!kA(t.d))throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f,...t.d==="b"?{direction:"backward"}:{}}}function Up(e){if(!Array.isArray(e.assertions))return e;let t=n=>!Mn(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function zp(e,t,n){if(!n)return e;if(n.command!==t)throw new g(`The read-output cursor belongs to ${n.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let r=Cn(e).find(c=>c.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0,i=Lt(t,n.path);if(!r||o!==n.total_rows||n.offset>o||i!==(n.direction==="backward")||Oi(n.path,r.value,t)!==n.fingerprint)throw new g("The read-output continuation no longer matches the declared row collection; restart the bounded read.",h.USAGE,{code:"read_output_cursor_stale"});if(!i)return fc(e,n.path,n.offset);let s=fc(e,n.path,0,n.offset);for(let c of["count","returned_count"])typeof s[c]=="number"&&(s[c]=n.offset);let a=ve[t].total_key;return typeof s[a]!="number"&&(s[a]=n.total_rows),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]="b6a81cf4-3095-5197-8e73-f017d98b1ccf")}catch{}})();var xc=1,qp=4096,OA=/^[A-Za-z0-9_-]+$/;function Rc(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function LL(e,t){let n=[...Object.values(To),...Co],r=new Set(n.flatMap(o=>[Rc(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){r.add(Rc(o.flag));for(let i of o.aliases??[])r.add(Rc(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!r.has(o)))}function FL(e,t){return SA("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function jr(e,t,n,r){return Buffer.from(JSON.stringify({version:xc,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function Ut(e,t){return new g(e,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${t} to obtain a fresh cursor.`]})}function AA(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===xc&&typeof t.fingerprint=="string"&&typeof t.after_id=="string"&&t.after_id.length>0&&(t.after_index===void 0||Number.isSafeInteger(t.after_index)&&t.after_index>=0)&&(t.snapshot===void 0||typeof t.snapshot=="string"&&t.snapshot.length>0)}function Cc(e,t="--after"){if(typeof e!="string")throw Ut("Query cursor is malformed.",t);let n=e.trim();if(n.length===0||n.length>qp||!OA.test(n))throw Ut("Query cursor is malformed.",t);let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw Ut("Query cursor is malformed.",t)}if(!AA(r)){let o=!1;try{Mr(n),o=!0}catch{}throw o?new g(`An output cursor must be continued with --output-cursor, not ${t}.`,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${t} with --output-cursor ${n}; retain any producer ${t} cursor from the original page.`]}):Ut("Query cursor version or payload is unsupported.",t)}return r}function Nc(e,t,n="--after"){let r=Cc(e,n);if(r.fingerprint!==t)throw Ut(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`,n);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function UL(e,t){return Nc(e,t).after_id}function IA(e,t,n,r,o="--after"){if(t===void 0)return 0;let i=Nc(t,n,o),s=e.findIndex(a=>r(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw Ut(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function zL(e,t){if(t.cursor!==void 0&&Nc(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Ut("Query cursor does not match the requested snapshot.","--after");let n=IA(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:jr(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var HL=Object.freeze({version:xc,max_length:qp});import{randomUUID as NA}from"node:crypto";import{randomUUID as TA}from"node:crypto";import{constants as jn}from"node:fs";import{lstat as Vp,mkdir as CA,open as Wp,rename as RA,rm as xA}from"node:fs/promises";import Ai 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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var qe={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30},X=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function zt(e){let t=Date.parse(e.now??new Date().toISOString());if(!Number.isFinite(t))throw new X("Context usage now must be a valid timestamp");return{iso:new Date(t).toISOString(),ms:t}}function Gp(e){let t=e.maxBytes??qe.max_bytes,n=e.maxEvents??qe.max_events,r=e.retentionDays??qe.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>qe.max_bytes||!Number.isSafeInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new X("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:n,cutoff:zt(e).ms-r*864e5}}async function Kp(e,t){if(!(await Vp(Ai.dirname(e))).isDirectory())throw new X("Context usage runtime must be a real directory");try{if((await Vp(e)).isSymbolicLink())throw new X("Context usage ledger must not be a symbolic link")}catch(r){if(!Z(r))throw r}let n=await Wp(e,t|jn.O_NOFOLLOW|jn.O_NONBLOCK,384);try{let r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new X("Context usage ledger must be an unshared regular file");return n}catch(r){throw await n.close(),r}}async function Ii(e){let t=Gp(e);try{let n=await Kp(Ai.join(e.pmRoot,"runtime","context-usage.jsonl"),jn.O_RDONLY);try{let r=(await n.stat()).size,o=Math.max(0,r-t.maxBytes),i=Buffer.alloc(Math.min(r,t.maxBytes)),{bytesRead:s}=await n.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
23
+ Diagnostic output exceeded its declared ${s}-token ceiling; rerun with structured JSON for the bounded recovery envelope.`,f=lp(t).trim()||"Inspect the diagnostic code and retry with corrected input.",m=Math.max(1,s*4-Buffer.byteLength(`${l}${u}`,"utf8")),_=d?`${l}${$t(f,m)}${u}`:a;return{output:_,diagnostic_output:{diagnostic_class:r,format:"text",budget:s,budget_source:i===void 0?"default":"explicit",original_estimated_tokens:c,estimated_tokens:jt(Buffer.byteLength(_,"utf8")),truncated:d,degradation_steps:d?[...o.degradation_ladder]:["full"],omitted_fields:d?["explanation","collections"]:[]}}}var Sc=Object.freeze({required:"Adjust command input or tracker state and retry.",why:Object.freeze(["pm enforces explicit, deterministic contracts for data and command semantics.","Commander validates CLI contracts before execution.","Unexpected runtime failures can occur from environment or extension-level issues.","Validation protects data consistency and deterministic behavior across commands.","Required options define command intent and enforce deterministic write contracts."]),examples:Object.freeze(["pm --help","pm <command> --help"])});function eL(e){return e?.trim()===Sc.required}function tL(e){let t=e?.trim();return t!==void 0&&Sc.why.includes(t)}function nL(e){return(e??[]).filter(t=>!Sc.examples.includes(t.trim()))}var rL=Object.freeze(["attempted_command","normalized_args","provided_fields"]);function oL(e){if(!e)return;let{attempted_command:t,normalized_args:n,provided_fields:r,...o}=e;return Object.values(o).some(i=>i!==void 0)?o:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="3a351971-6cfb-55eb-a266-3fec0af9eaa4")}catch{}})();var ve=Object.freeze({comments:Object.freeze({paths:Object.freeze(["comments"]),total_key:"total_count"}),notes:Object.freeze({paths:Object.freeze(["notes"]),total_key:"total_count",delivered_row_counters:Object.freeze([Object.freeze({key:"structured_event_count",field:"format",equals:"json"})])}),learnings:Object.freeze({paths:Object.freeze(["learnings"]),total_key:"total_count"})});function Lt(e,t){return e===void 0?!1:(Object.hasOwn(ve,e)?ve[e]:void 0)?.paths.includes(t)===!0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="24a8de41-54f9-5b59-8e58-7ac924ba6e08")}catch{}})();function uL(e){return typeof e=="object"&&e!==null&&"id"in e&&typeof e.id=="string"&&"context_ref"in e&&typeof e.context_ref=="string"&&e.context_ref.startsWith("session:")&&e.context_ref.endsWith(`:${e.id}`)}var Oc=256,Ac=1e4,VO=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/u,yp=/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/u,BO=new Set(["version","id","token_budget","spent_tokens","seen_item_ids"]),WO=[{valid:e=>e.version===1,reason:"version must equal 1."},{valid:e=>typeof e.id=="string"&&VO.test(e.id),reason:"id must be 1-64 portable identifier characters."},{valid:e=>Number.isSafeInteger(e.token_budget)&&e.token_budget>=Oc,reason:`token_budget must be a safe integer of at least ${Oc}.`},{valid:e=>Number.isSafeInteger(e.spent_tokens)&&e.spent_tokens>=0&&e.spent_tokens<=e.token_budget,reason:"spent_tokens must be a non-negative safe integer no larger than token_budget."},{valid:e=>Array.isArray(e.seen_item_ids)&&e.seen_item_ids.length<=Ac&&e.seen_item_ids.every(t=>typeof t=="string"&&yp.test(t)),reason:`seen_item_ids must contain at most ${Ac} portable item identifiers.`}];function ki(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Ei(e){throw new g(`--output-session ${e}`,h.USAGE,{code:"invalid_read_output_session",field:"outputSession"})}function Si(e){if(e===void 0)return;let t=e;if(typeof e=="string")try{t=JSON.parse(e)}catch{Ei("must be a valid JSON object.")}ki(t)||Ei("must be a JSON object.");let n=Object.keys(t).filter(i=>!BO.has(i));n.length>0&&Ei(`contains unknown field "${n.sort()[0]}".`);let r=WO.find(i=>!i.valid(t));r!==void 0&&Ei(r.reason);let o=[...new Set(t.seen_item_ids)].sort();return{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:o}}function hp(e){if(ki(e))return typeof e.id=="string"?e.id:typeof e.item_id=="string"?e.item_id:ki(e.item)&&typeof e.item.id=="string"?e.item.id:void 0}function GO(e){let t=new Set,n=0,r=rt(e),o=new Set(r.map(({path:s})=>s)),i=Object.entries(e).flatMap(([s,a])=>Array.isArray(a)&&!o.has(s)?[{path:s,value:a}]:[]);for(let s of[...r,...i]){let a=Array.isArray(s.value)?s.value:Object.values(s.value);for(let c of a){if(!ki(c))continue;if(typeof c.context_ref=="string"){n+=1;continue}let d=hp(c);d!==void 0&&yp.test(d)&&t.add(d)}}return{deliveredIds:t,suppressedRepeatCount:n}}function gp(e,t){let n=new Set(t.seen_item_ids);return Cr(e,r=>{let o=hp(r);return o!==void 0&&n.has(o)?{id:o,context_ref:`session:${t.id}:${o}`}:r})}function Ic(e,t,n){let{deliveredIds:r,suppressedRepeatCount:o}=GO(e),i=new Set(t.seen_item_ids),s=[...r].filter(y=>!i.has(y)).sort(),a=s.slice(0,Ac-t.seen_item_ids.length),c=[...t.seen_item_ids,...a].sort(),d=s.length-a.length,l={contract_version:1,id:t.id,measurement_scope:"complete_read_envelope",estimator:"ceil(utf8_bytes / 4)",token_budget:t.token_budget,spent_before_tokens:t.spent_tokens,spent_this_call_tokens:0,charged_this_call_tokens:0,spent_total_tokens:t.spent_tokens,remaining_tokens:t.token_budget-t.spent_tokens,exhausted:!1,seen_before_count:t.seen_item_ids.length,new_item_count:r.size,...d===0?{}:{seen_item_overflow_count:d},suppressed_repeat_count:o,reference_format:"session:<session-id>:<item-id>",restore_reference_with:"pm get <item-id> --depth brief",next_state:{version:1,id:t.id,token_budget:t.token_budget,spent_tokens:t.spent_tokens,seen_item_ids:c}},u={...e,read_session:l},f=y=>{l.spent_this_call_tokens=y,l.charged_this_call_tokens=Math.min(t.token_budget-t.spent_tokens,y),l.spent_total_tokens=Math.min(t.token_budget,t.spent_tokens+l.charged_this_call_tokens),l.remaining_tokens=Math.max(0,t.token_budget-l.spent_total_tokens),l.exhausted=l.remaining_tokens<Oc,l.next_state.spent_tokens=l.spent_total_tokens},m=0,_=0;for(let y=0;y<8;y+=1){f(m);let b=it(u,n);if(b===m)return u;_=Math.max(_,b),m=b}return f(_),u}function bp(e){return Math.max(0,e.token_budget-e.spent_tokens)}(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]="1cc0fcb7-2aaa-5233-bdfd-4b4d0fb3e9c1")}catch{}})();var Nr=Symbol.for("pm.readOutputInvocationProvenance");function mL(e,t){return Reflect.set(e,Nr,{canonical_include_modes:[...t],explicit_legacy_aliases:[],sdk_invocation_observed:!0}),e}(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]="2a596392-747a-5b55-854d-1e80964468d3")}catch{}})();var Ft=["include","amount","cost","encoding"],Tp=["canonical","legacy","intent","default"],Mr=Co,DL=Object.freeze(Ft.map(e=>Mr[e])),PL=Ro;function KO(e,t){let n=wi[e];if(n!==void 0)return n;let r=t==="include"?wc.has(e)?"<csv>":vi(e):t==="amount"?"<n>":t==="cost"?"<tokens>":"<toon|json>";return`${e} is a compatibility alias; prefer ${Mr[t]} ${r}.`}function Cp(e){let t=bc[e]??{},n=Object.freeze(Object.fromEntries(Ft.map(r=>[r,Object.freeze({dimension:r,canonical_option:Mr[r],applicable:!0,inapplicable_reason:null,legacy_aliases:Object.freeze((t[r]??[]).map(o=>Object.freeze({flag:o,semantics:wi[o]===void 0?"replacement":"behavior_preserving",migration_hint:KO(o,r),visibility:"hidden_alias"})))})])));return Object.freeze({command:e,dimensions:n,precedence:Tp,budget_retention_policy:e==="assurance"?"verdict_priority":Object.hasOwn(ve,e)?"ordered_suffix":"ordered_prefix",projection_modes:Object.freeze([...vc(e).keys()])})}var YO=Object.freeze(Et.map(Cp)),XO=new Map(YO.map(e=>[e.command,e]));function at(e,t={}){let n=Kn(e.trim().toLowerCase()),r=gc(n);return r!==void 0?r.read_output===void 0?void 0:`extension:${r.command}`:dp(n,t)}var JO=["outputInclude","output_include","outputLimit","output_limit","outputBudget","output_budget","outputFormat","output_format","outputSession","output_session","outputCursor","output_cursor","outputRowContract","output_row_contract"],wp={comments:["add","body","comment","text","stdin","file","edit","delete"],notes:["add","note","text","addJson","stdin","file","edit","delete"],learnings:["add","learning","text","stdin","file","edit","delete"],files:["add","addGlob","remove","migrate","apply","note"],docs:["add","addGlob","remove","migrate","note"],"package-catalog":["activate","adopt","adoptAll","deactivate","doctor","init","install","manage","migrate","reload","scaffold","uninstall"]};function ZO(e){return JO.some(t=>t!=="outputFormat"&&t!=="output_format"&&e[t]!==void 0)}var QO=[{keys:["outputInclude","output_include"],valid:e=>Dr(e)!==void 0,message:"--output-include requires at least one comma-separated field or section."},{keys:["outputLimit","output_limit"],valid:e=>e==="unbounded"||Pn(e)!==void 0,message:"--output-limit must be a positive integer or unbounded."},{keys:["outputBudget","output_budget"],valid:e=>e==="unbounded"||Pn(e)!==void 0,message:"--output-budget must be a positive integer or unbounded."},{keys:["outputSession","output_session"],valid:e=>(Si(e),!0),message:"--output-session must be a valid session-state object."},{keys:["outputCursor","output_cursor"],valid:e=>typeof e=="string"&&e.trim().length>0,message:"--output-cursor requires a non-empty continuation cursor."}],ML="read_output_mutation_conflict",Rp=[{flag:"--output-include",keys:["outputInclude","output_include"]},{flag:"--output-limit",keys:["outputLimit","output_limit"]},{flag:"--output-budget",keys:["outputBudget","output_budget"]},{flag:"--output-session",keys:["outputSession","output_session"]},{flag:"--output-cursor",keys:["outputCursor","output_cursor"]},{flag:"--output-row-contract",keys:["outputRowContract","output_row_contract"]}],$L=Rp.map(({flag:e})=>e);function eA(e,t,n){let r=Rp.filter(({keys:a})=>a.some(c=>t[c]!==void 0)),o=r.map(({flag:a})=>a),i=r.flatMap(({keys:a})=>a.filter(c=>t[c]!==void 0)),s=o.join(", ");return new g(`Universal output controls (${s}) cannot be combined with a ${e} mutation; nothing was written.`,h.USAGE,{code:"read_output_mutation_conflict",field:o[0],details:{surface:e,output_controls:o,output_option_keys:i,mutation_options:[...n]},required:`Retry the ${e} mutation without ${s}. To bound or page the result, read it with those controls in a separate call after the write.`,why:"Universal output controls shape a read. A mutation returns its own bounded receipt, so the controls have nothing to shape and the write is refused before it runs.",examples:[...tA[e]]})}var tA={comments:['pm comments <id> --add "<text>"',"pm comments <id> --output-limit 5"],notes:['pm notes <id> --add "<text>"',"pm notes <id> --output-limit 5"],learnings:['pm learnings <id> --add "<text>"',"pm learnings <id> --output-limit 5"],files:["pm files <id> --add path=<path>","pm files <id> --output-limit 5"],docs:["pm docs <id> --add path=<path>","pm docs <id> --output-limit 5"],"package-catalog":["pm package install <source> --project","pm package catalog --output-limit 5"]};function jL(e,t){let n=t.outputFormat??t.output_format;if(n!==void 0&&n!=="json"&&n!=="toon")throw new g("--output-format must be toon or json.",h.USAGE);if(!ZO(t))return;let r=at(e,t);if(!r)throw new g(`Universal output controls apply only to read commands; ${e||"this command"} is not a read surface.`,h.USAGE);if(Object.hasOwn(wp,r)){let o=r,i=wp[o].filter(s=>t[s]!==void 0&&t[s]!==!1);if(i.length>0)throw eA(o,t,i)}for(let o of QO){let i=o.keys.map(s=>t[s]).find(s=>s!==void 0);if(i!==void 0&&!o.valid(i))throw new g(o.message,h.USAGE)}}function xp(e){let t=at(e);return t?vc(t):new Map}function nA(e,t,n){let r=Dr(t)??[],o=xp(e),i=[],s=[],a=n,c=a[Nr],d=new Set(c?.canonical_include_modes??[]),l=new Set(c?.explicit_legacy_aliases??[]);for(let m of r){let _=o.get(m);if(_===void 0){i.push(m);continue}let y=`--${m.replaceAll("_","-")}`;Cc(Tc(n,y))&&l.add(y),n[_]=!0,s.push(m),d.add(m)}let u=at(e)==="get"?i.filter(m=>m!=="item"):[],f=u.length>0;return f&&(n.fields=[...new Set([...Dr(n.fields)??[],...u])].join(","),d.add("fields")),(s.length>0||f)&&(a[Nr]={canonical_include_modes:[...d],explicit_legacy_aliases:[...l],...c?.cli_invocation_observed===!0?{cli_invocation_observed:!0}:{}}),{selectors:i,modes:s}}function LL(e,t){let n=t.outputInclude??t.output_include;if(n===void 0)return;let{selectors:r,modes:o}=nA(e,n,t);if(o.length===0)return;let i=r.length>0?r.join(","):void 0;t.outputInclude=i,Object.hasOwn(t,"output_include")&&(t.output_include=i)}function Tc(e,t){let n=Ec(t);if(Object.hasOwn(e,n))return e[n];let r=t.slice(2).replaceAll("-","_");if(Object.hasOwn(e,r))return e[r];if(t==="--no-truncate"&&e.truncate===!1)return!0}function Cc(e){return e!==void 0&&e!==!1&&e!==null}function Dr(e){let t=(Array.isArray(e)?e:[e]).flatMap(n=>typeof n=="string"?n.split(","):[]).map(n=>n.trim()).filter(Boolean);return t.length>0?[...new Set(t)]:void 0}function Pn(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function rA(e,t,n,r){for(let o of e.legacy_aliases){if(r(o.flag))continue;let i=Tc(t,o.flag),s={value:i,flag:o.flag};if(Cc(i)&&n(s))return s}}function vp(e,t){let n=Dr(e);if(n)return{source:"canonical",value:n};if(t)return{source:"legacy",value:Dr(t.value)??[vi(t.flag)]}}function Ep(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Pn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;if(t.flag==="--no-truncate"||t.flag==="--unbounded")return{source:"legacy",value:"unbounded"};let r=Pn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function kp(e,t){if(e==="unbounded")return{source:"canonical",value:"unbounded"};let n=Pn(e);if(n!==void 0)return{source:"canonical",value:n};if(!t)return;let r=Pn(t.value);return r===void 0?void 0:{source:"legacy",value:r}}function Sp(e,t){if(e==="json"||e==="toon")return{source:"canonical",value:e};if(t)return t.flag==="--stream"||t.flag==="--follow"?{source:"legacy",value:"stream"}:t.value==="json"||t.value==="toon"?{source:"legacy",value:t.value}:void 0}function Np(e,t,n){if(!e)return!1;let r=new Set(e.explicit_legacy_aliases);if(e.cli_invocation_observed===!0||e.sdk_invocation_observed===!0)return!r.has(n);let o=new Set(e.canonical_include_modes.map(i=>`--${i.replaceAll("_","-")}`));return t==="include"&&o.has(n)&&!r.has(n)}function oA(e,t,n,r){return e.trim().toLowerCase().replaceAll(/\s+/gu," ").split(" ")[0]==="list-all"||Cc(Tc(r,"--no-truncate"))&&!Np(n,"amount","--no-truncate")||t.amount?.flag==="--no-truncate"||t.include?.flag==="--full"||n?.canonical_include_modes.includes("full")===!0}function iA(e,t){return Ft.flatMap(n=>e[n]?.source==="canonical"||n==="include"&&(t?.canonical_include_modes.length??0)>0?[Mr[n]]:[])}function Dp(e,t){let n=at(e,t);if(!n)return;let r=XO.get(n)??Cp(n),o=t[Nr],i={include:v=>vp(void 0,v),amount:v=>Ep(void 0,v),cost:v=>kp(void 0,v),encoding:v=>Sp(void 0,v)},s=Object.fromEntries(Ft.map(v=>[v,rA(r.dimensions[v],t,T=>i[v](T)!==void 0,T=>Np(o,v,T))])),a=Ft.flatMap(v=>{let T=s[v];return T?[T.flag]:[]}),c=Ft.flatMap(v=>{let T=s[v];return T?[r.dimensions[v].legacy_aliases.find(G=>G.flag===T.flag).migration_hint]:[]}),d=Sp(t.outputFormat??t.output_format,s.encoding),l=vp(t.outputInclude??t.output_include,s.include),u=Ep(t.outputLimit??t.output_limit,s.amount),f=kp(t.outputBudget??t.output_budget,s.cost),m=oA(e,s,o,t),_=mp(e,{generateFallback:!0}),y=d?.value==="json"||t.resolvedOutputFormat==="json"?"json":"toon",b=f??(m?{source:"intent",value:"unbounded"}:{source:"default",value:_.default_max_estimated_tokens_by_format[y]});return{command:n,include:l,amount:u,cost:b,encoding:d,canonical_options_used:iA({include:l,amount:u,cost:b,encoding:d},o),legacy_aliases_used:a,migration_hints:c,precedence:Tp}}function Y(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var Rc=new Set(["applied_bound","applied_limit","completeness","continuation_kind","continuation_path","continuation_contract","count","filters","has_more","next_cursor","now","omission_receipt","projection","budget_retention_policy","row_contract","sorting","total","truncated"]),sA=["collection_counts","notes_count","tests_count"];function Pp(e,t){let n=new Set(t.map(r=>r.split(".")[0]));return Object.fromEntries(Object.entries(e).filter(([r])=>n.has(r)))}function aA(e){let t=Y(e.item)?e.item:{},n=[...new Set([...Object.keys(t),...sA.filter(o=>Object.hasOwn(t,o))])].sort((o,i)=>o.localeCompare(i)),r=Object.keys(e).filter(o=>o!=="item"&&o!=="read_output"&&!Rc.has(o)).sort((o,i)=>o.localeCompare(i));return{item:t,itemFields:n,sections:r,valid:[...n,"item",...n.map(o=>`item.${o}`),...r]}}function cA(e,t){let n=aA(e),r=t.filter(l=>!n.valid.includes(l));if(r.length>0)throw new g(`Unknown --output-include selector(s) for get: ${r.join(", ")}. Valid selectors: ${n.valid.join(", ")}.`,h.USAGE);let o=t.includes("item"),i=t.flatMap(l=>l.startsWith("item.")?[l.slice(5)]:n.itemFields.includes(l)?[l]:[]).filter((l,u,f)=>f.indexOf(l)===u);if(o&&i.length>0)throw new g("--output-include cannot mix a full item with projected item fields; use item or item.<field>, not both.",h.USAGE);let s=new Set(t.filter(l=>n.sections.includes(l))),a=Object.fromEntries(Object.entries(e).filter(([l])=>Rc.has(l)||s.has(l)));o?a.item=n.item:i.length>0&&(a.item=Pp(n.item,i));let c=[...o?[]:i.length>0?n.itemFields.filter(l=>!i.includes(l)).map(l=>({name:`item.${l}`,restore_with:`--output-include item.${l}`})):[{name:"item",restore_with:"--output-include item"}],...n.sections.filter(l=>!s.has(l)).map(l=>({name:l,restore_with:`--output-include ${l}`}))],d=[...Y(a.omission_receipt)&&Array.isArray(a.omission_receipt.omitted_field_groups)?a.omission_receipt.omitted_field_groups:[],...c];return a.omission_receipt={has_omissions:d.length>0,omitted_field_group_count:d.length,omitted_field_groups:d},a}function Op(e){let t=0;return Cr({...e},n=>(Y(n)&&Object.keys(n).length>0&&(t+=1),n)),t}function dA(e,t,n,r){if(Op(t)===0||Op(n)>0)return;let o=[...xp(e).keys()],i=o.length>0?` Declared ${e} projection modes: ${o.join(", ")}.`:` The ${e} surface declares no projection modes; name row fields instead.`;throw new g(`Unknown --output-include selector(s) for ${e}: ${r.join(", ")}. No selector matched any returned row field.${i}`,h.USAGE)}function lA(e,t,n){if(e==="get")return cA(t,n);let r=gi(t),o=n.flatMap(s=>r.flatMap(a=>s.startsWith(`${a}.`)?[s.slice(a.length+1)]:[])),i=n.some(s=>Object.hasOwn(t,s.split(".")[0])&&!r.some(a=>s.startsWith(`${a}.`)));if(r.length>0&&(!i||o.length>0)){let s={...t},a=o.length>0?o:n,c=Cr(s,d=>Y(d)?Pp(d,a):d);return dA(e,t,c,a),c}return Object.fromEntries(Object.entries(t).filter(([s])=>n.some(a=>a.split(".")[0]===s)||Rc.has(s)))}function uA(e,t,n,r){if(t==="unbounded")return e;let{result:o,truncated:i}=ep(e,t,s=>Lt(n,s));if(!i)return o;if(o.has_more=!0,o.truncated=!0,Lp(o,n,[...r.entries()].flatMap(([s,a])=>a.rows>t?[{path:s,total_rows:a.totalRows}]:[])),typeof o.count=="number"){let s=Y(o.projection)?o.projection.row_key:void 0;o.count=typeof s=="string"&&Array.isArray(o[s])?o[s].length:xn(o)}return typeof o.returned_count=="number"&&(o.returned_count=xn(o)),o.applied_bound={kind:"output_limit",source:"explicit",value:t},o}function fA(e){return Ft.filter(t=>e[t]!==void 0&&e[t]?.source!=="default"||e.canonical_options_used.includes(Mr[t]))}function Oi(e,t,n,r){let o=Ic(e,t,r);Dn(e,o);for(let i=0;i<8;i+=1){let s=n.estimated_tokens,a=o.read_session.spent_this_call_tokens;st(o,n,r);let c=o;o=Ic(o,t,r),Dn(c,o);let d=o.read_session.spent_this_call_tokens;if(n.estimated_tokens===s&&d===a)return o}return o}function xc(e,t){if(!Y(e.read_output))return e;let n=Mn(t),r=e.read_output,o=Si(t.outputSession??t.output_session);return o===void 0?(st(e,r,n),e):Oi(e,o,r,n)}function mA(e,t){if(e!=="validate")return t;let n=Y(t.projection)?t.projection:void 0;if(!(Array.isArray(n?.declared_field_groups)?n.declared_field_groups:[]).some(l=>Y(l)&&l.name==="diagnostic_rows"))return t;let r=[...new Set(Tr(t).map(({path:l})=>l).filter(l=>/^checks\.\d+\.details\./u.test(l)))],o=r.filter(l=>!r.some(u=>u!==l&&l.startsWith(`${u}.`)));if(o.length===0)return t;let i=Y(t.row_contract)?t.row_contract:{},s=Array.isArray(i.row_keys)?i.row_keys.filter(l=>typeof l=="string"):[],a=Array.isArray(i.continuation_row_keys)?i.continuation_row_keys.filter(l=>typeof l=="string"):[],c=s.length>0?s:o,d=[...new Set(o)];return JSON.stringify(c)===JSON.stringify(s)&&JSON.stringify(d)===JSON.stringify(a)?t:{...t,row_contract:{...i,row_keys:c,continuation_row_keys:d,jq_selector:typeof i.jq_selector=="string"?i.jq_selector:".checks[].details"}}}function pA(e,t){return e.include?.source==="canonical"&&!Ne(t)}function _A(e,t,n,r,o){let i={...e};if(pA(t,e)&&(i=lA(t.command,i,t.include.value)),t.command==="assurance"&&(i=Bp(i)),Rr(i,e),i=Wp(i,t.command,r),t.command==="history"&&r){let c=["compact_history","provenance_history","history","diff"];if(i=Object.fromEntries(Object.entries(i).filter(([d])=>!c.includes(d)||d===r.path)),Y(i.projection)&&(i.projection={...i.projection,row_key:r.path}),Y(i.row_contract)){let d=i.row_contract;i.row_contract={...d,row_keys:[r.path],...Array.isArray(d.continuation_row_keys)?{continuation_row_keys:[r.path]}:{}}}i.count=Object.keys(i[r.path]).length}let s=e.count_only===!0?{...i,count_only:!0,count:e.count}:i,a=kA(i,e,t.command,r,o);return t.amount?.source==="canonical"&&(i=uA(i,t.amount.value,t.command,a.collectionsBeforeBudget),a.cursorContinuesExistingPage&&Up(i,a.originalItems,a.cursorSource,!0,a.originalItemOffset)),Rr(i,s),Fp(i,t.command,a),{projected:n===void 0?i:gp(i,n),continuationState:a}}function yA(e,t){return[...e.cost!==void 0&&e.cost.value!=="unbounded"&&(e.cost.source==="canonical"||e.cost.source==="default"||e.command==="context"&&e.cost.source==="legacy")?[{source:e.cost.source,tokens:e.cost.value}]:[],...t===void 0?[]:[{source:"session",tokens:bp(t)}]].sort((n,r)=>n.tokens-r.tokens)[0]}function Mp(e){let t=e.canonical_options_used;return t&&t.length>0?{canonical_options_used:t}:{}}function $p(e,t){return Y(e.context_intent)&&e.context_intent.command==="context"&&e.context_intent.token_budget===t&&e.context_intent.within_budget===!0}function hA(e,t,n){return e.command!=="next"||(t.tokenBudget??t.token_budget)===void 0?!1:!(Y(n.context_intent)&&n.context_intent.command==="next"&&n.context_intent.within_budget===!0)}function jp(e,t={}){return e?.source==="default"||e?.source==="legacy"&&!$p(t,e.tokens)?{budget_source:e.source,budget_tokens:e.tokens}:{}}function gA(e,t,n,r,o,i){let s={contract_version:1,command:e.command,requested_dimensions:t,...jp(r),precedence:e.precedence,...Mp(e),legacy_aliases_used:[],migration_hints:[],estimated_tokens:0,within_budget:!1,strings_compacted:!1,rows_compacted:!1,result_omitted:!0,...n===void 0?{omitted_result_estimated_tokens:o}:{}},a={output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},read_output:s},c=n===void 0?a:Oi(a,n,s,i);if(n===void 0&&st(c,s,i),n!==void 0&&s.estimated_tokens>r.tokens)throw new g("The remaining output-session budget cannot fit its mandatory receipts; start a new session with a larger token_budget.",h.USAGE);return c}function bA(e,t,n){return e.command==="context"&&e.cost?.source==="legacy"&&!$p(n,e.cost.value)||hA(e,t,n)||t.outputRowContract===!0||t.output_row_contract===!0||e.canonical_options_used.includes("--output-include")||e.command==="list"&&e.canonical_options_used.length>0&&e.include?.value.includes("full")===!0}function wA(e,t,n,r,o){if(t!==void 0||Ne(n)||bA(e,o,n))return!1;if(e.amount?.source==="canonical"&&e.amount.value!=="unbounded"){let i=e.amount.value;if(rt(n).some(({value:s})=>(Array.isArray(s)?s.length:Object.keys(s).length)>i))return!1}return e.cost===void 0||e.cost.value==="unbounded"||e.cost.source==="legacy"&&e.command!=="context"||it(o.outputRowContract===!1?Object.fromEntries(Object.entries(n).filter(([i])=>i!=="row_contract")):n,r)<=e.cost.value}function Lp(e,t,n){let r=Object.hasOwn(ve,t)?ve[t]:void 0,o=n.find(i=>r?.paths.includes(i.path));r!==void 0&&o!==void 0&&typeof e[r.total_key]!="number"&&(e[r.total_key]=o.total_rows)}function Fp(e,t,n){let r=ve[t]?.paths[0];r!==void 0&&Vp(e,t,n.producer,n.collectionsBeforeBudget.get(r)?.rows)}function vA(e,t,n,r){let o=n.backward?n.rows-r:n.baseOffset+r;return{path:t,cursor:Nc({command:e,path:t,offset:o,total_rows:n.totalRows,fingerprint:n.fingerprint,...n.backward?{direction:"backward"}:{}}),retained_rows:r,remaining_rows:n.backward?o:n.totalRows-o,total_rows:n.totalRows}}function EA(e,t,n,r,o,i,s){if(!n.rows_compacted)return;let a=t.amount?.value==="unbounded"?["amount"]:[],c=new Map(Rn(e).map(_=>[_.path,Array.isArray(_.value)?_.value.length:Object.keys(_.value).length])),d=[...s.entries()].flatMap(([_,y])=>{let b=c.get(_);return b>=y.rows?[]:[vA(t.command,_,y,b)]}),l=d[0];Lp(e,t.command,d);let u=l?"; page --output-cursor":"",f=r.source==="session"?`Truncated by the remaining ${r.tokens}-token session budget; start a new output session with a larger token_budget${u}.`:`${r.tokens}-token: raise --output-budget${u}`;n.migration_hints=[f,...t.migration_hints];let m=Pr({effective_budget_tokens:r.tokens,measured_result_tokens:i});l&&!o&&(typeof e.next_cursor!="string"||e.continuation_kind==="output_cursor")&&(e.next_cursor=l.cursor),e.continuation_kind=o?"producer_cursor":l?"output_cursor":"none",e.output_budget_truncation={reason:"output_budget_reached",budget_source:r.source,budget_tokens:r.tokens,overridden_dimensions:a,compacted_row_paths:n.compacted_row_paths,continuation_cursor_rebased:o,continuation_available:d.length>0,recovery_budget_multiplier:l?1:m.recovery_budget_multiplier,continuations:d,restore_with:l?"recovery":`Retry with --output-budget ${m.output_budget} because no declared row collection can be continued.`,recovery:l?{cursor:l.cursor,cli:"--output-cursor",sdk:"outputCursor",mcp:"outputCursor"}:{cli:`--output-budget ${m.output_budget}`,sdk:{outputBudget:m.output_budget},mcp:{outputBudget:m.output_budget}}}}function Up(e,t,n,r,o){if(typeof n!="string"||!Array.isArray(e.items))return!1;let i=e.items.length,s=t.length;if(i===0||i>=s)return!1;let a;try{a=Dc(n)}catch{return!1}let c=a.after_index;if(c===void 0)return!1;let d=t[i-1];if(Object.prototype.toString.call(d)!=="[object Object]")return!1;let l=Reflect.get(d,"id");if(typeof l!="string"||l.length===0)return!1;let u=r?c-(s-i):c+o+i;return u<0?!1:(e.next_cursor=jr(a.fingerprint,l,u,a.snapshot),!0)}function kA(e,t,n,r,o){let i=new Map(Rn(e).map(c=>{let d=Array.isArray(c.value)?c.value.length:Object.keys(c.value).length,l=r?.path===c.path,u=Lt(n,c.path);return[c.path,{rows:d,totalRows:l?r.total_rows:d,baseOffset:l&&!u?r.offset:0,backward:u,fingerprint:l?r.fingerprint:Ai(c.path,c.value,n)}]})),s=typeof e.next_cursor=="string",a=r?.path==="items"?r.offset:0;return{collectionsBeforeBudget:i,originalItems:Array.isArray(t.items)?a>0?t.items.slice(a):t.items:[],originalItemOffset:a,cursorContinuesExistingPage:s,cursorSource:s?e.next_cursor:o.after,producer:t}}function SA(e,t,n,r,o,i,s,a,c,d){let l={...t,count_only:n},u=r.command==="assurance"&&Array.isArray(e.assertions)?e.assertions.filter(m=>Y(m)&&m.verdict!=="pass").length:0,f=new Map;if(u>0&&f.set("assertions",u),r.command==="history"&&Array.isArray(e.diff))for(let m of Tr(e))m.path.startsWith("diff.")&&f.set(m.path,Object.keys(m.value).length);return Ip(e,o,i.tokens,f,d,m=>{Rr(m,l),Fp(m,r.command,a);let _=Up(m,a.originalItems,a.cursorSource,a.cursorContinuesExistingPage,a.originalItemOffset);if(EA(m,r,o,i,_,c,a.collectionsBeforeBudget),r.command==="history"&&Y(m.projection)){m.has_more=typeof m.next_cursor=="string"||m.applied_bound?.kind==="output_limit";let y=m.projection.row_key;typeof y=="string"&&Array.isArray(m[y])&&(m.count=m[y].length)}s!==void 0&&Object.assign(m,Oi(m,s,o,d))},r.command==="history"&&Array.isArray(e.diff),m=>Lt(r.command,m))}function zp(e,t,n){let r=Dp(e,t);if(!r)return n;let o=Mn(t),i=Si(t.outputSession??t.output_session),s=t.outputCursor??t.output_cursor,a=typeof s=="string"?$r(s):void 0,c=fA(r),d=mA(r.command,n);if(a===void 0&&wA(r,i,d,o,t))return d;let l=yA(r,i),u=_A(d,r,i,a,t),f=u.projected;Dn(f,f,t.outputRowContract===!1);let m=Ne(f),_={contract_version:1,command:r.command,requested_dimensions:c,...jp(l,f),precedence:r.precedence,...Mp(r),legacy_aliases_used:r.legacy_aliases_used,migration_hints:r.migration_hints,estimated_tokens:0,within_budget:!m,strings_compacted:!1,rows_compacted:!1,result_omitted:m};if(f.read_output=_,f=i===void 0?f:Oi(f,i,_,o),st(f,_,o),l!==void 0&&_.estimated_tokens>l.tokens){let y=Ap(r.command,t,f);y!==void 0&&(_.applied_depth="brief",_.degradation_reason="output_budget_reached",Dn(f,y),f=xc(y,t)),_.estimated_tokens>l.tokens&&(f=SA(f,f,d.count_only===!0,r,_,l,i,u.continuationState,_.estimated_tokens,o))}return l!==void 0&&_.estimated_tokens>l.tokens?gA(r,c,i,l,_.estimated_tokens,o):f}function OA(e){return Y(e)&&Y(e.context_intent)&&e.context_intent.result_omitted===!0}function Ne(e){return AA(e)||OA(e)}function AA(e){return Y(e)&&Y(e.output_budget_exceeded)&&e.output_budget_exceeded.omitted_result===!0&&e.output_budget_exceeded.reason==="requested_budget_infeasible"}function Hp(e,t){let n=t.outputFormat??t.output_format;if(n==="json"||n==="toon")return n;let r=Dp(e,t)?.encoding;return r?.value==="json"||r?.value==="toon"?r.value:void 0}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="83f3f6fd-bd97-54a4-b39e-c66ec8e333b2")}catch{}})();var TA=4096,CA=Object.freeze(["queue_draining","queue_entries","queue_exists","queue_high_retry_entries","queue_invalid_rows","queue_max_attempts","queue_rows_total","queue_size_bytes","pending_otel_spans","last_attempted_flush_at","last_failed_flush_at","last_otel_attempt_at","last_otel_failure_at","last_otel_success_at","last_successful_flush_at"]),qp=Object.freeze({health:Object.freeze({version:3,paths:Object.freeze(["checks"]),ignored_detail_field_names_by_row:Object.freeze({telemetry:CA}),guarantee:"nonvolatile_snapshot_and_stable_configuration"})});function $n(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vp(e,t,n=e,r){let o=Object.hasOwn(ve,t)?ve[t]:void 0;if(o?.delivered_row_counters===void 0)return;let i=o.paths[0],s=e[i],a=n[i];if(!Array.isArray(s)||!Array.isArray(a))return;let c=r??a.length,d=a.slice(Math.max(0,c-s.length),c);for(let l of o.delivered_row_counters)typeof e[l.key]=="number"&&(e[l.key]=d.filter(u=>$n(u)&&u[l.field]===l.equals).length)}function Lr(e){return Array.isArray(e)?e.map(Lr):$n(e)?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Lr(n)])):e}function Gp(e,t){if(!$n(e))return Lr(e);let n=typeof e.name=="string"?e.name:void 0,r=n!==void 0&&Object.hasOwn(t.ignored_detail_field_names_by_row,n)?t.ignored_detail_field_names_by_row[n]:void 0;return Object.fromEntries(Object.entries(e).map(([o,i])=>o!=="details"||!r||!$n(i)?[o,Lr(i)]:[o,Object.fromEntries(Object.entries(i).filter(([s])=>!r.includes(s)).map(([s,a])=>[s,Lr(a)]))]))}function RA(e,t){return Array.isArray(e)?e.map(n=>Gp(n,t)):Gp(e,t)}function Ai(e,t,n){let r=n?qp[n]:void 0,o=r?.paths.includes(e)===!0;return IA("sha256").update(R({path:e,value:o?RA(t,r):t,...o?{fingerprint_policy_version:r.version}:{}})).digest("base64url").slice(0,16)}function Nc(e){return Buffer.from(JSON.stringify({v:1,c:e.command,p:e.path,o:e.offset,n:e.total_rows,f:e.fingerprint,...e.direction==="backward"?{d:"b"}:{}}),"utf8").toString("base64url")}function xA(e){return typeof e=="string"&&(at(e)===e||/^extension:\S(?:[^\r\n]*\S)?$/u.test(e))}function NA(e){return e===void 0||e==="b"}function $r(e){if(e.length>TA)throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});let t;try{t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"))}catch{t=null}if(!$n(t)||t.v!==1||!xA(t.c)||typeof t.p!="string"||t.p.length===0||!Number.isSafeInteger(t.o)||t.o<0||!Number.isSafeInteger(t.n)||t.n<1||typeof t.f!="string"||t.f.length===0||!NA(t.d))throw new g("The read-output continuation cursor is malformed or unsupported.",h.USAGE,{code:"read_output_cursor_invalid"});return{version:1,command:t.c,path:t.p,offset:t.o,total_rows:t.n,fingerprint:t.f,...t.d==="b"?{direction:"backward"}:{}}}function Bp(e){if(!Array.isArray(e.assertions))return e;let t=n=>!$n(n)||n.verdict==="pass"?4:n.verdict==="retired"?3:n.enforcement==="block"?0:n.enforcement==="warn"?1:2;return{...e,assertions:e.assertions.map((n,r)=>({row:n,index:r})).sort((n,r)=>t(n.row)-t(r.row)||n.index-r.index).map(({row:n})=>n),budget_retention_policy:"verdict_priority"}}function Wp(e,t,n){if(!n)return e;if(n.command!==t)throw new g(`The read-output cursor belongs to ${n.command}, not ${t}.`,h.USAGE,{code:"read_output_cursor_command_mismatch"});let r=Rn(e).find(c=>c.path===n.path),o=r?Array.isArray(r.value)?r.value.length:Object.keys(r.value).length:0,i=Lt(t,n.path);if(!r||o!==n.total_rows||n.offset>o||i!==(n.direction==="backward")||Ai(n.path,r.value,t)!==n.fingerprint)throw new g("The read-output continuation no longer matches the declared row collection; restart the bounded read.",h.USAGE,{code:"read_output_cursor_stale"});if(!i)return yc(e,n.path,n.offset);let s=yc(e,n.path,0,n.offset);for(let c of["count","returned_count"])typeof s[c]=="number"&&(s[c]=n.offset);let a=ve[t].total_key;return typeof s[a]!="number"&&(s[a]=n.total_rows),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]="b6a81cf4-3095-5197-8e73-f017d98b1ccf")}catch{}})();var Mc=1,Kp=4096,PA=/^[A-Za-z0-9_-]+$/;function Pc(e){return e.replace(/^--/u,"").replace(/[-_]([a-z0-9])/gu,(t,n)=>n.toUpperCase())}function eF(e,t){let n=[...Object.values(Co),...Ro],r=new Set(n.flatMap(o=>[Pc(o),o.slice(2).replaceAll("-","_")]));for(let o of t)if(o.cursor_semantics==="presentation"){r.add(Pc(o.flag));for(let i of o.aliases??[])r.add(Pc(i))}return Object.fromEntries(Object.entries(e).filter(([o])=>!r.has(o)))}function tF(e,t){return DA("sha256").update(e).update("\0").update(R(t)).digest("hex").slice(0,24)}function jr(e,t,n,r){return Buffer.from(JSON.stringify({version:Mc,fingerprint:e,after_id:t,...n===void 0?{}:{after_index:n},...r===void 0?{}:{snapshot:r}})).toString("base64url")}function Ut(e,t){return new g(e,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the original query without ${t} to obtain a fresh cursor.`]})}function MA(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return t.version===Mc&&typeof t.fingerprint=="string"&&typeof t.after_id=="string"&&t.after_id.length>0&&(t.after_index===void 0||Number.isSafeInteger(t.after_index)&&t.after_index>=0)&&(t.snapshot===void 0||typeof t.snapshot=="string"&&t.snapshot.length>0)}function Dc(e,t="--after"){if(typeof e!="string")throw Ut("Query cursor is malformed.",t);let n=e.trim();if(n.length===0||n.length>Kp||!PA.test(n))throw Ut("Query cursor is malformed.",t);let r;try{r=JSON.parse(Buffer.from(n,"base64url").toString("utf8"))}catch{throw Ut("Query cursor is malformed.",t)}if(!MA(r)){let o=!1;try{$r(n),o=!0}catch{}throw o?new g(`An output cursor must be continued with --output-cursor, not ${t}.`,h.USAGE,{code:"invalid_query_cursor",nextSteps:[`Repeat the same query, replacing ${t} with --output-cursor ${n}; retain any producer ${t} cursor from the original page.`]}):Ut("Query cursor version or payload is unsupported.",t)}return r}function $c(e,t,n="--after"){let r=Dc(e,n);if(r.fingerprint!==t)throw Ut(`Query cursor does not match the current filters, sort, or query (${r.fingerprint} != ${t}).`,n);return{after_id:r.after_id,...r.after_index===void 0?{}:{after_index:r.after_index},...r.snapshot===void 0?{}:{snapshot:r.snapshot}}}function nF(e,t){return $c(e,t).after_id}function $A(e,t,n,r,o="--after"){if(t===void 0)return 0;let i=$c(t,n,o),s=e.findIndex(a=>r(a)===i.after_id);if(s<0){if(i.after_index!==void 0)return Math.min(i.after_index,e.length);throw Ut(`Query cursor item ${i.after_id} is no longer present in this result set.`,o)}return s+1}function rF(e,t){if(t.cursor!==void 0&&$c(t.cursor,t.fingerprint).snapshot!==t.snapshot)throw Ut("Query cursor does not match the requested snapshot.","--after");let n=$A(e,t.cursor,t.fingerprint,t.readId),r=e.slice(n,n+t.limit),o=r.length>0&&n+r.length<e.length,i=r.at(-1);return{rows:r,has_more:o,...o&&i!==void 0?{next_cursor:jr(t.fingerprint,t.readId(i),n+r.length-1,t.snapshot)}:{}}}var oF=Object.freeze({version:Mc,max_length:Kp});import{randomUUID as zA}from"node:crypto";import{randomUUID as jA}from"node:crypto";import{constants as jn}from"node:fs";import{lstat as Yp,mkdir as LA,open as Jp,rename as FA,rm as UA}from"node:fs/promises";import Ii 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]="71b65888-baa5-5c5f-a02c-4a0fd818fadb")}catch{}})();var qe={max_serving_rows:256,max_bytes:262144,max_event_bytes:32768,retained_byte_fraction:.5,max_events:2048,retention_days:30},X=class extends TypeError{code="context_usage_validation_failed";constructor(t){super(t),this.name="ContextUsageValidationError"}};function zt(e){let t=Date.parse(e.now??new Date().toISOString());if(!Number.isFinite(t))throw new X("Context usage now must be a valid timestamp");return{iso:new Date(t).toISOString(),ms:t}}function Zp(e){let t=e.maxBytes??qe.max_bytes,n=e.maxEvents??qe.max_events,r=e.retentionDays??qe.retention_days;if(!Number.isSafeInteger(t)||t<1024||t>qe.max_bytes||!Number.isSafeInteger(n)||n<1||!Number.isFinite(r)||r<=0)throw new X("Context usage retention requires positive maxEvents and retentionDays, and maxBytes from 1024 through 262144");return{maxBytes:t,maxEvents:n,cutoff:zt(e).ms-r*864e5}}async function Qp(e,t){if(!(await Yp(Ii.dirname(e))).isDirectory())throw new X("Context usage runtime must be a real directory");try{if((await Yp(e)).isSymbolicLink())throw new X("Context usage ledger must not be a symbolic link")}catch(r){if(!Q(r))throw r}let n=await Jp(e,t|jn.O_NOFOLLOW|jn.O_NONBLOCK,384);try{let r=await n.stat();if(!r.isFile()||r.nlink!==1)throw new X("Context usage ledger must be an unshared regular file");return n}catch(r){throw await n.close(),r}}async function Ti(e){let t=Zp(e);try{let n=await Qp(Ii.join(e.pmRoot,"runtime","context-usage.jsonl"),jn.O_RDONLY);try{let r=(await n.stat()).size,o=Math.max(0,r-t.maxBytes),i=Buffer.alloc(Math.min(r,t.maxBytes)),{bytesRead:s}=await n.read(i,0,i.length,o),a=i.subarray(0,s).toString("utf8");return(o>0?a.includes(`
24
24
  `)?a.slice(a.indexOf(`
25
25
  `)+1):"":a).split(`
26
- `).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await n.close()}}catch{return[]}}function Bp(e,t,n){let r=[],o=0;for(let i=e.length-1;i>=0&&r.length<n;i-=1){let s=`${JSON.stringify(e[i])}
27
- `;if(o+=Buffer.byteLength(s),o>t)break;r.push(s)}return r.reverse().join("")}async function Lr(e,t,n){let r=Gp(e),o=Ai.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(r.maxBytes*qe.retained_byte_fraction),s=Math.min(qe.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
28
- `)>s))throw new X("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=r.cutoff),c=Bp(a,i,r.maxEvents),d=performance.now(),l=await fe(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await CA(Ai.dirname(o),{recursive:!0});let f=await Kp(o,jn.O_WRONLY|jn.O_CREAT|jn.O_APPEND);try{let m=(await f.stat()).size,_=n===void 0?void 0:await Ii(e);if(_?.some(T=>T.kind==="delivery"&&T.serve_id===n))return{written_bytes:0,ledger_bytes:m,compacted:!1,lock_wait_ms:u};if(!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&m+Buffer.byteLength(c)<=r.maxBytes)return await f.writeFile(c,"utf8"),{written_bytes:Buffer.byteLength(c),ledger_bytes:m+Buffer.byteLength(c),compacted:!1,lock_wait_ms:u};let y=Bp([..._??await Ii(e),...a],i,r.maxEvents),b=`${o}.${process.pid}.${TA()}.tmp`,v=await Wp(b,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await RA(b,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await xA(b,{force:!0})}}finally{await f?.close()}}finally{await l()}}(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]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();var DA=864e5,Ti=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function Q(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function eF(e,t){let n=Q(e);n!==null&&t!==null&&(n[Ti]=t)}function Ht(e,t){let n=Q(e),r=Q(t),o=n?.[Ti];r!==null&&o!==void 0&&(r[Ti]=o)}function PA(e){return Q(e)?.[Ti]??null}function Xp(e){let t=Q(e);for(let n of["read_output","context_intent"])if(Q(t?.[n])?.result_omitted===!0)return!0;return!1}function ct(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function Jp(e,t){if(Array.isArray(t))for(let n of t)ct(e,Q(n)?.id)}function Yp(e,t){if(Array.isArray(t))for(let n of t)ct(e,n)}function MA(e,t){let n=Q(e.recommended)===null?[]:[e.recommended];for(let r of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[r])&&n.push(...e[r]);for(let r of n){let o=Q(r);ct(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])ct(t,Q(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])ct(t,i)}}function jA(e,t){for(let n of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])Jp(t,e[n]);for(let n of Array.isArray(e.blockers)?e.blockers:[])ct(t,Q(n)?.blocked_by);$A(e,t)}function $A(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=Q(o);ct(t,i?.id),Jp(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])Yp(t,Q(i)?.items);let n=Q(e.agenda);for(let o of Array.isArray(n?.events)?n.events:[])ct(t,Q(o)?.item_id);let r=Q(e.tests);Yp(t,r?.items_failing)}function LA(e,t){let n=Q(e);if(n===null||Xp(e))return[];let r=new Set;return t==="next"?MA(n,r):jA(n,r),[...r]}async function tF(e){let t=PA(e.result);if(t===null)return!1;let n=Xp(e.result);return await FA({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:LA(e.result,t.surface),resultOmitted:n}),!0}async function nF(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(o=>!o.id.trim()||!Number.isInteger(o.rank)||o.rank<1))throw new X("Context usage serving requires an author and valid ranked rows");let t=e.rows.map(o=>({id:o.id.trim(),rank:o.rank,included:o.included}));if(new Set(t.map(o=>o.id)).size!==t.length)throw new X("Context usage serving requires unique normalized row ids");let n=t.slice(0,qe.max_serving_rows),r={serve_id:NA(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:n.map(o=>o.id)};return r.storage=await Lr(e,[{kind:"serve",schema_version:2,serve_id:r.serve_id,at:zt(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:n,candidate_count:t.length,omitted_row_count:t.length-n.length,result_omitted:!1,packed_item_ids:n.filter(o=>o.included).map(o=>o.id)}]),r}async function FA(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;let t=new Set(e.receipt.rows.map(i=>i.id)),n=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(n.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&n.length>0)throw new X("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let r=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(i=>i.id)),o={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:zt(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:n.filter(i=>r.has(i))};await Lr(e,[o],o.serve_id)}async function rF(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new X("Context usage touch requires author, itemId, and intent");await Lr(e,[{kind:"touch",at:zt(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function oF(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new X("Context usage touch requires author and intent");let r=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new X("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new X("Context usage touch requires non-empty itemId");r.add(a)}let o=zt(e).iso,i=[...r].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:n}));await Lr(e,i)}function UA(e,t,n,r){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=n&&i-n<=r)?.time}function zA(e,t){let n=new Map;for(let r of e)r.kind==="delivery"&&r.schema_version===2&&r.author===t&&!n.has(r.serve_id)&&n.set(r.serve_id,r);return n}async function iF(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};let t=await Ii(e),n=zt(e).ms,r=(e.horizonHours??24)*36e5;if(![Number.isFinite(r),r>0].every(Boolean))throw new X("Context usage horizonHours must be positive");let o=e.author.trim(),i=t.filter(f=>f.kind==="touch").filter(f=>f.author===o).map(f=>({entry:f,time:Date.parse(f.at)})),s=new Map,a=0,c=0,d=0,l=zA(t,o);t.filter(f=>f.kind==="serve").filter(f=>f.author===o).forEach(f=>{if(![f.schema_version===2,!!f.serve_id].every(Boolean)){c+=1;return}a+=1;let m=Date.parse(f.at),_=l.get(f.serve_id),y=new Set(_?.delivered_item_ids??[]);for(let b of f.rows){if(!y.has(b.id))continue;let v=UA(i,b.id,m,r);if(v===void 0)continue;d+=1;let T=Math.max(0,(n-v)/DA);s.set(b.id,(s.get(b.id)??0)+Math.exp(-T/14))}});let u=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([f,m])=>[f,u===0?.05:.05+.95*m/u])),positive_judgments:d,serving_events:a,untrusted_serving_events:c}}(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]="b9a7ec77-c0da-589a-823e-dc1acae42797")}catch{}})();var qA="limit_overridden_by_intent",n_=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),r_=new HA;function VA(){return r_.getStore()??n_}function gF(e,t){return r_.run(WA(e.workspaceContracts,e.packageContracts),t)}function BA(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))throw new TypeError(`Invalid context intent command or name: ${o}`);if(e.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(e.token_budget)||e.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);let i=[...new Set(e.included_field_groups.map(s=>s.trim()).filter(Boolean))];if(i.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function WA(e=[],t=[]){let n=[{source:"core",contracts:n_,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=BA(s,i.source),c=`${a.command}:${a.intent}`;if(o.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);if(o.add(c),!i.allowOverride&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function o_(e,t,n=VA(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let m=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=m[0];m[0]=_;for(let b=1;b<=i.length;b+=1){let v=m[b];m[b]=Math.min(m[b]+1,m[b-1]+1,y+(f[_-1]===i[b-1]?0:1)),y=v}}return{candidate:f,distance:m[i.length]}}).sort((f,m)=>f.distance-m.distance||f.candidate.localeCompare(m.candidate))[0].candidate,d=[o,...r,"--for",i],l=[o,...r,"--for",c],u=dn(l);throw new g(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,h.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:dn(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}function Dc(e,t){let n=Vt(e.limit),r=String(n===void 0?t:Math.min(n,t));return(e.limit===void 0||n!==void 0)&&(e.limit=r),r}var i_={context:(e,t,n,r)=>{e.section===void 0&&e.depth===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard");let o=Ri(r,e.tokenBudget,t.token_budget),i=xi("context",t.intent,o,n),s=Dc(e,i);e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n,r)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let o=Ri(r,e.tokenBudget,t.token_budget),i=xi("list",t.intent,o,n);Dc(e,i)},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n,r)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let o=Ri(r,e.tokenBudget,t.token_budget),i=xi("search",t.intent,o,n);Dc(e,i)}};function bF(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==void 0&&(e==="get"||e==="list"||e==="search"))throw new g("--token-budget requires a declared context intent selected with --for",h.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let c={...t,tokenBudget:r};return delete c.token_budget,c}let o=o_(e,t.for,void 0,n),i=Fr(t),s=Vt(r)!==void 0||typeof i=="number",a={...t};return a.tokenBudget===void 0&&r!==void 0&&(a.tokenBudget=r),delete a.token_budget,typeof i=="number"?a.tokenBudget=String(i):a.tokenBudget===void 0&&(a.tokenBudget=String(o.token_budget)),i_[e](a,o,s,i),a}var GA={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Ci=256;function Mc(e){return Array.isArray(e)?e.map(Mc):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Mc(n)])):typeof e=="string"&&e.length>240?`${Ee(e,240)}\u2026`:e}function Vt(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function Fr(e){let t=e.outputBudget??e.output_budget;return t==="unbounded"?t:Vt(t)}function KA(e){return Fr(e)===void 0?"--token-budget":"--output-budget"}function Ri(e,t,n){return typeof e=="number"?e:YA(t,n)}function YA(e,t){let n=Vt(e);if(n===void 0)return t;if(n<Ci)throw new g(`Context intent token budget must be at least ${Ci}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Ci}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Ci} or omit the override.`]});return n}function s_(e,t){return e==="context"?e==="context"&&t==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:e==="list"?520:480,rowCost:16}}function xi(e,t,n,r){if(e==="get"||e==="next")return;let{overhead:o,rowCost:i}=s_(e,t),s=Math.max(e==="context"?1:2,Math.floor((n-o)/i));return r?s:Math.min(e==="context"?20:100,s)}function Bt(e,t,n){let r=Pn(n),o=n.outputRowContract===!0||n.output_row_contract===!0,i=t.estimated_tokens,s=i;for(let a=0;a<$c;a+=1){t.estimated_tokens=i;let c=it(o||!Object.hasOwn(e,"row_contract")?e:Object.fromEntries(Object.entries(e).filter(([d])=>d!=="row_contract")),r);if(c===i)return;i=c,s=Math.max(s,i)}t.estimated_tokens=s}var Qp={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function a_(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.fingerprint!="string"||!Number.isSafeInteger(t.after_index)?void 0:{fingerprint:t.fingerprint,after_index:t.after_index,...typeof t.snapshot=="string"?{snapshot:t.snapshot}:{}}}catch{return}}function XA(e){if(e===null||typeof e!="object")return;if(typeof e.id=="string")return e.id;let t=e.item?.id;return typeof t=="string"?t:void 0}function JA(e,t,n,r){let o=!1;for(;;){if(Bt(e,t,r),t.estimated_tokens<=t.token_budget||n.length<=1)return o;let i=Buffer.byteLength(JSON.stringify(n),"utf8"),s=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(s/Math.max(1,Math.ceil(i/n.length)))))),o=!0}}function QA(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=a_(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=JA(e,t,r,n)||d,!d)return!1;let l=XA(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),Bt(e,t,n),!1;if(e.next_cursor=jr(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),Bt(e,t,n),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function ZA(e,t,n,r){if(e==="list"||e==="search")return QA(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Bt(t,n,r),n.estimated_tokens<=n.token_budget)return o;let i=Qp[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,m)=>m.rows.length-f.rows.length||f.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=Qp[e].reduce((f,m)=>f+(Array.isArray(t[m])?t[m].length:0),0);if(s<=1)return o;let a=Math.min(i.rows.length,s-1),c=Buffer.byteLength(JSON.stringify(i.rows),"utf8"),d=Math.max(1,Math.ceil(c/i.rows.length)),l=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function Zp(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in i_))return n;let o=r,i=o_(o,t.for),s=Fr(t),a=Ri(s,t.tokenBudget??t.token_budget,i.token_budget),c={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:a,declared_token_budget:i.token_budget,token_budget_override:a-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:GA[o],declaration_feasible:!0,result_omitted:!1},d={...n},l=xi(o,i.intent,c.token_budget,Vt(t.tokenBudget??t.token_budget)!==void 0||typeof s=="number");if(l!==void 0){let y=Vt(t.limit),b=y!==void 0&&y<l;c.budget_derived_limit=l,c.binding_constraint=b?"explicit_limit":"token_budget",c.limit_reason=b?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",d.budget_derived_limit=l,iI({builtInCommand:o,intent:i.intent},c,d,t)}let u=c_.get(t)??0,f=c.token_budget;c.token_budget=f-u;let m=s==="unbounded"?jc(d,c,t):eI(o,d,c,t);c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget;let _=d_(s,c,m,()=>u_(e,o,i.intent,{...c,token_budget:f,estimated_tokens:c.estimated_tokens+u},d,t));return c.result_omitted&&(c.estimated_tokens+=u,c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget),c.token_budget=f,_}function jc(e,t,n){let r={...e,context_intent:t};return Bt(r,t,n),r}function eI(e,t,n,r){let o=jc(t,n,r);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",o=jc(Mc(t),n,r)),n.estimated_tokens>n.token_budget&&ZA(e,o,n,r)&&(n.degradation="budget_row_compaction",Bt(o,n,r)),o}var c_=new WeakMap;function d_(e,t,n,r){return t.estimated_tokens<=t.token_budget||(t.within_budget=!1,e==="unbounded")?n:(t.degradation="budget_receipt_only",t.result_omitted=!0,typeof e=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:t}:{budget_exceeded:{omitted_result:!0,reason:t.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:r()},context_intent:t})}var tI=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function nI(e,t){if(typeof e.after!="string"||e.after.length===0||Ne(t))return t;let n=a_(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of tI)delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function rI(e,t){let n=e==="get"&&dt(t.item)&&typeof t.item.id=="string"?t.item.id:e==="search"&&typeof t.query=="string"?t.query:void 0;return n===void 0?"":` ${l_(n)}`}function l_(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function oI(e){return typeof e.fields=="string"&&e.fields.trim()!==""?` --fields ${l_(e.fields)}`:""}function iI(e,t,n,r){let o=Vt(r.limit),i=t.budget_derived_limit;if(o===void 0||o<=i)return;let{overhead:s,rowCost:a}=s_(e.builtInCommand,e.intent),c=Math.max(t.token_budget,s+a*o);t.limit_reason=`The ${t.token_budget}-token ${e.intent} budget carries ${i} rows, so it reduced the caller's --limit ${o}.`,t.limit_override={flag:"--limit",requested:o,effective:i,...Number.isSafeInteger(c)?{token_budget_for_requested:c,restore_with:`${KA(r)} ${c}`}:{}};let d=`${qA}:--limit ${o}->${i}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,d]:[d],dt(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function u_(e,t,n,r,o,i){let s=rI(t,o),a=t==="get"?"":` --limit ${r.budget_derived_limit??1}`,{output_budget:c}=Dr({effective_budget_tokens:r.token_budget,measured_result_tokens:r.estimated_tokens});return`pm ${e}${s}${oI(i)} --for ${n} --token-budget ${c}${a}`}function qt(e,t){if(dt(e))return typeof e[t]=="number"?e[t]:void 0}function e_(e,t){let n=e;for(let r=0;r<8;r+=1){sI(n);let o=qt(n.context_intent,"estimated_tokens"),i=qt(n.read_output,"estimated_tokens"),s=qt(n.read_session,"spent_this_call_tokens");if(dt(n.context_intent)&&n.context_intent.result_omitted!==!0&&Bt(n,n.context_intent,t),n=Ic(n,t),qt(n.context_intent,"estimated_tokens")===o&&qt(n.read_output,"estimated_tokens")===i&&qt(n.read_session,"spent_this_call_tokens")===s)break}return n}function sI(e){let t=e.context_intent;dt(t)&&Number(t.estimated_tokens)>Number(t.token_budget)&&(t.within_budget=!1)}function Lc(e,t,n){let r=Gm(e,rp(e??"",n));if(typeof r!="object"||r===null||Array.isArray(r))return Ht(n,r),r;let o=e??"",i=r,s=Zp(o,t,i),a=qt(s.context_intent,"estimated_tokens"),c=Pc(o,t,n,s),d=t_(t,c,s.context_intent);if(d===void 0)return c;let l={...t};c_.set(l,d.estimated-Number(a));let u=Zp(o,l,i),f=Pc(o,l,n,u),m=t_(t,f,u.context_intent);if(m===void 0)return f;let _={...m.receipt,estimated_tokens:m.estimated};return Pc(o,t,n,d_(Fr(t),_,f,()=>u_(o,_.command,_.intent,_,i,t)))}function t_(e,t,n){let r=dt(t.context_intent),o=r?t.context_intent:n;if(!dt(o)||o.result_omitted===!0||Object.hasOwn(t,"output_budget_exceeded"))return;let i=o,s=r?i.estimated_tokens:it(t,Pn(e));return Fr(e)==="unbounded"||s<=i.token_budget?void 0:{receipt:i,estimated:s}}function Pc(e,t,n,r){let o=jp(e,{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},nI(t,r));if(Ht(n,o),t.outputRowContract===!0||t.output_row_contract===!0||!Object.hasOwn(o,"row_contract"))return dt(o.context_intent)?e_(o,t):o;let i=Object.fromEntries(Object.entries(o).filter(([a])=>a!=="row_contract"));Object.defineProperty(i,"row_contract",{value:o.row_contract,enumerable:!1,configurable:!0});let s=e_(i,t);return delete s.row_contract,Ht(o,s),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]="cb1266f3-8375-586f-87c6-356cf7843969")}catch{}})();var $n=["result_rows","envelope","diagnostics","hints"],aI=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,cI=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,dI=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,lI=8;function Fc(e){return Buffer.byteLength(e,"utf8")}function f_(e){return Fc(JSON.stringify(e)??"null")}function uI(e,t){return cI.test(e)?"diagnostics":dI.test(e)?"hints":aI.test(e)||Array.isArray(t)?"result_rows":"envelope"}function fI(e){let t={result_rows:0,envelope:0,diagnostics:0,hints:0};if(typeof e!="object"||e===null||Array.isArray(e))return t[Array.isArray(e)?"result_rows":"envelope"]=f_(e),t;for(let[n,r]of Object.entries(e))t[uI(n,r)]+=f_({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function mI(e,t){let n=$n.reduce((s,a)=>s+t[a],0),r=$n.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-$n.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||$n.indexOf(a.section)-$n.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function m_(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function p_(e,t){let n=Fc(t(e)),r=mI(n,fI(e)),o=Object.fromEntries($n.map(a=>[a,{bytes:r[a],estimated_tokens:$t(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:$t(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=m_(e,i);for(let a=0;a<lI;a+=1){let c=Fc(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:$t(c)},s=m_(e,i)}return 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]="787e6c05-d503-5602-a173-e6a59699cea6")}catch{}})();var __=Object.freeze({comments:Object.freeze(["comments"]),notes:Object.freeze(["notes"]),learnings:Object.freeze(["learnings"])});function y_(e){return e===void 0||!Object.hasOwn(__,e)?[]:__[e]}(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]="8e86e884-98ca-5b28-838b-db3543051112")}catch{}})();var h_=new Set(["body","item_hash","linked","claim_state","children","schedule","blockers"]),SF=new Set(["linked","claim_state","children","schedule"]);import{encode as qc}from"@toon-format/toon";(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]="d3d21124-3c8a-5049-803d-00c63c0c2b61")}catch{}})();function g_(e,t={}){let n=[...new Set(e.flatMap(l=>Object.keys(l)))],r=t.compact?n.filter(l=>e.every(u=>Object.hasOwn(u,l)&&u[l]===null)):[],o=t.compact?n.filter(l=>e.every(u=>{if(!Object.hasOwn(u,l))return!0;let f=u[l];return Array.isArray(f)&&f.every(m=>typeof m=="string"&&m!==""&&!m.includes(";"))})):[],i=new Set(o),s=new Set(r),a=n.filter(l=>!i.has(l)&&e.some(u=>{let f=u[l];return f!==null&&typeof f=="object"})),c=new Set(a),d=[];return{rows:e.map((l,u)=>Object.fromEntries(n.filter(f=>!s.has(f)).map(f=>{if(!Object.hasOwn(l,f))return d.push([u,f]),[f,null];let m=l[f];return i.has(f)?[f,m.join(";")]:[f,c.has(f)?JSON.stringify(m):m]}))),encoding:{json_columns:a,absent:d,...o.length?{list_columns:Object.fromEntries(o.map(l=>[l,";"]))}:{},...r.length?{null_columns:r,null_column_index:r.map(l=>n.indexOf(l))}:{}}}}function pI(e,t){let n=t.null_columns??[],r=t.null_column_index??[],o=[...e],i=n.map((s,a)=>({column:s,position:r[a]})).filter(s=>typeof s.position=="number").sort((s,a)=>s.position-a.position);for(let{column:s,position:a}of i)o.splice(Math.min(a,o.length),0,s);for(let s of n)o.includes(s)||o.push(s);return o}function AF(e){let t=new Set(e.encoding.json_columns),n=new Map(Object.entries(e.encoding.list_columns??{})),r=new Set(e.encoding.absent.map(([o,i])=>JSON.stringify([o,i])));return e.rows.map((o,i)=>{let s=new Map(Object.entries(o).flatMap(([c,d])=>{if(r.has(JSON.stringify([i,c])))return[];let l=n.get(c),u=l!==void 0?d===""?[]:String(d).split(l):t.has(c)?JSON.parse(String(d)):d;return[[c,u]]}));for(let c of e.encoding.null_columns??[])s.set(c,null);let a=e.encoding.column_order??pI(Object.keys(o),e.encoding);return Object.fromEntries(a.filter(c=>s.has(c)).map(c=>[c,s.get(c)]))})}(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]="43d2915b-7301-5e96-89e0-51c8e817789e")}catch{}})();function De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var _I=new Set(["brief","compact","fields"]);function b_(e){if(!De(e))return!1;let t=e.fields;return _I.has(e.mode)&&Object.keys(e).length===2&&Array.isArray(t)&&t.length>0&&t.every(n=>typeof n=="string"&&n.length>0)}function w_(e,t){return e.every(n=>De(n)&&Object.keys(n).length===t.fields.length&&t.fields.every(r=>Object.hasOwn(n,r)))}function v_(e,t){return e.mode==="fields"&&t===0?{projection:e}:{}}function E_(e,t){return typeof e.has_more=="boolean"&&e.truncated===e.has_more&&e.count===t&&typeof e.total=="number"&&Number.isSafeInteger(e.total)&&(e.has_more?e.total>t&&typeof e.next_cursor=="string"&&e.next_cursor.length>0:e.total===t&&e.next_cursor==null)}function yI(e){return De(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function Uc(e,t="full_item_fields"){if(!De(e)||!Array.isArray(e.omitted_field_groups))return!1;let n=e.omitted_field_groups,r=n[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&n.length===1&&De(r)&&Object.keys(r).length===2&&r.name===t&&r.restore_with==="--full"}function k_(e){if(!De(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!b_(e.projection)||!w_(e.items,e.projection)||!yI(e.completeness)||!E_(e,e.items.length)||!Uc(e.omission_receipt))return e;let{total:t,has_more:n,truncated:r,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,filters:l,...u}=e,f=i.status==="complete"&&!n&&Object.keys(i).length===3,{unreadable_item_count:m,unreadable_directory_count:_,...y}=i;return{...u,...f?{}:{total:t,has_more:n,completeness:y},...n?{next_cursor:o}:{},...bI(d),...S_(l,u.applied_limit,s),...v_(s,e.items.length),details:"--full"}}function hI(e){return De(e)&&e.sort==="default"&&e.order==="asc"&&Object.keys(e).every(t=>t==="sort"||t==="order"||t==="effective_keys")}function gI(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&(e[1]==="asc"||e[1]==="desc")}function bI(e){if(!hI(e))return{sorting:e};let t=e.effective_keys;return t===void 0?{}:!Array.isArray(t)||!t.every(gI)?{sorting:e}:{sorting:{effective_keys:t.map(([n,r])=>`${n} ${r}`).join(", ")}}}function wI(e,t){if(typeof e!="string"||t===void 0)return!1;let n=e.split(",").map(r=>r.trim()).filter(Boolean);return n.length===t.fields.length&&n.every((r,o)=>r===t.fields[o])}function S_(e,t,n){if(!De(e))return e===void 0?{}:{filters:e};let r=Object.fromEntries(Object.entries(e).filter(([o,i])=>!(o==="limit"&&String(i)===String(t))&&!(o==="fields"&&wI(i,n))&&!(o==="runtime_filters"&&De(i)&&Object.keys(i).length===0)));return Object.keys(r).length===0?{}:{filters:r}}function vI(e,t){return e.count===t&&!Object.hasOwn(e,"has_more")&&!Object.hasOwn(e,"truncated")&&e.next_cursor==null&&(e.total===void 0||e.total===t)}function EI(e){if(!Object.hasOwn(e,"projection"))return Uc(e.omission_receipt,"projection_metadata")?{}:void 0;let t=e.projection;return b_(t)&&t.mode==="fields"&&w_(e.items,t)&&typeof e.now=="string"&&Uc(e.omission_receipt)?{projection:t}:void 0}function O_(e){if(!De(e)||typeof e.query!="string"||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!(E_(e,e.items.length)||vI(e,e.items.length)))return e;let t=EI(e);if(t===void 0)return e;let{truncated:n,omission_receipt:r,filters:o,projection:i,now:s,mode_source:a,...c}=e;return{...c,...a==="settings"||t.projection===void 0&&a!==void 0?{mode_source:a}:{},...S_(o,c.applied_limit,t.projection),...t.projection?v_(t.projection,e.items.length):{},details:"--full"}}import{isBoxedPrimitive as kI}from"node:util/types";(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]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();var A_=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function NF(e){return e.replaceAll(A_,"\uFFFD")}function SI(e,t,n){return n&&/^\d+$/u.test(t)?`${e}[${t}]`:/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function zc(e,t,n){if(typeof e=="string"){let r=e.search(A_);return r<0?void 0:{field:t,index:r}}if(!(e===null||typeof e!="object"||n.has(e))){n.add(e);for(let[r,o]of Object.entries(e)){let i=SI(t,r,Array.isArray(e)),s=zc(r,`${i} (key)`,n)??zc(o,i,n);if(s)return s}}}function I_(e,t,n){if(e===null||typeof e!="object")return e;if(kI(e)||typeof e.toJSON=="function")return JSON.parse(JSON.stringify({[t]:e}))[t];if(n.has(e))return n.get(e);let r=Array.isArray(e)?new Array(e.length):{};n.set(e,r);for(let o of Object.keys(e))Object.defineProperty(r,o,{value:I_(e[o],o,n),enumerable:!0,configurable:!0,writable:!0});return r}function Hc(e){let t=I_(e,"",new WeakMap),n=zc(t,"$",new WeakSet);return n&&OI(n),t}function OI(e){throw new g(`Output field ${e.field} contains an unpaired surrogate code unit at index ${e.index}; structured output requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:e.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function DF(e){Hc(e)}(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]="a378018f-b981-5e5e-98a4-45d190039473")}catch{}})();var AI=new Set(Object.values(h)),II=new Map([["notes_count","notes"],["tests_count","tests"]]),Vc="__pm_native_output",T_=!1;function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xc(e){let t={read_output:{result_omitted:!0}};Ht(e,t),Uo(t)}function Bc(e,t,n){if(n){Uo(e);return}Xc(t)}function TI(e){if(!x(e)||e[Vc]!==!0)return e;let{[Vc]:t,...n}=e;return n}function Wc(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function CI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function RI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function Gc(e){if(e==="stdout"){CI();return}RI()}function C_(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function xI(){T_||(T_=!0,process.stdout.on("error",e=>{if(Wc(e)){Gc("stdout");return}C_(e)}),process.stderr.on("error",e=>{if(Wc(e)){Gc("stderr");return}C_(e)}))}function R_(e,t){xI();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Wc(n))return Gc(e),!1;throw n}}function NI(e){return R_("stdout",e)}function Ur(e){return R_("stderr",e)}function x_(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Kc(e,t){let n=" ".repeat(t);return e.split(`
26
+ `).flatMap(c=>{try{let d=JSON.parse(c);return d&&Date.parse(d.at)>=t.cutoff?[d]:[]}catch{return[]}}).slice(-t.maxEvents)}finally{await n.close()}}catch{return[]}}function Xp(e,t,n){let r=[],o=0;for(let i=e.length-1;i>=0&&r.length<n;i-=1){let s=`${JSON.stringify(e[i])}
27
+ `;if(o+=Buffer.byteLength(s),o>t)break;r.push(s)}return r.reverse().join("")}async function Fr(e,t,n){let r=Zp(e),o=Ii.join(e.pmRoot,"runtime","context-usage.jsonl"),i=Math.floor(r.maxBytes*qe.retained_byte_fraction),s=Math.min(qe.max_event_bytes,i);if(t.some(f=>Buffer.byteLength(`${JSON.stringify(f)}
28
+ `)>s))throw new X("Context usage event exceeds the declared byte ceiling");let a=t.filter(f=>Date.parse(f.at)>=r.cutoff),c=Xp(a,i,r.maxEvents),d=performance.now(),l=await fe(e.pmRoot,"context-usage-ledger",30,`context-usage:${process.pid}`,!1,!1,3e3),u=performance.now()-d;try{await LA(Ii.dirname(o),{recursive:!0});let f=await Qp(o,jn.O_WRONLY|jn.O_CREAT|jn.O_APPEND);try{let m=(await f.stat()).size,_=n===void 0?void 0:await Ti(e);if(_?.some(T=>T.kind==="delivery"&&T.serve_id===n))return{written_bytes:0,ledger_bytes:m,compacted:!1,lock_wait_ms:u};if(!(e.maxEvents!==void 0||e.retentionDays!==void 0)&&m+Buffer.byteLength(c)<=r.maxBytes)return await f.writeFile(c,"utf8"),{written_bytes:Buffer.byteLength(c),ledger_bytes:m+Buffer.byteLength(c),compacted:!1,lock_wait_ms:u};let y=Xp([..._??await Ti(e),...a],i,r.maxEvents),b=`${o}.${process.pid}.${jA()}.tmp`,v=await Jp(b,"wx",384);try{try{await v.writeFile(y,"utf8")}finally{await v.close()}return await f.close(),f=void 0,await FA(b,o),{written_bytes:Buffer.byteLength(y),ledger_bytes:Buffer.byteLength(y),compacted:!0,lock_wait_ms:u}}finally{await UA(b,{force:!0})}}finally{await f?.close()}}finally{await l()}}(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]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();var HA=864e5,Ci=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function Z(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function yF(e,t){let n=Z(e);n!==null&&t!==null&&(n[Ci]=t)}function Ht(e,t){let n=Z(e),r=Z(t),o=n?.[Ci];r!==null&&o!==void 0&&(r[Ci]=o)}function qA(e){return Z(e)?.[Ci]??null}function t_(e){let t=Z(e);for(let n of["read_output","context_intent"])if(Z(t?.[n])?.result_omitted===!0)return!0;return!1}function ct(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function n_(e,t){if(Array.isArray(t))for(let n of t)ct(e,Z(n)?.id)}function e_(e,t){if(Array.isArray(t))for(let n of t)ct(e,n)}function VA(e,t){let n=Z(e.recommended)===null?[]:[e.recommended];for(let r of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[r])&&n.push(...e[r]);for(let r of n){let o=Z(r);ct(t,o?.id);for(let i of Array.isArray(o?.blockers)?o.blockers:[])ct(t,Z(i)?.id);for(let i of Array.isArray(o?.unblocks)?o.unblocks:[])ct(t,i)}}function BA(e,t){for(let n of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])n_(t,e[n]);for(let n of Array.isArray(e.blockers)?e.blockers:[])ct(t,Z(n)?.blocked_by);WA(e,t)}function WA(e,t){for(let o of Array.isArray(e.hierarchy)?e.hierarchy:[]){let i=Z(o);ct(t,i?.id),n_(t,i?.children)}for(let o of["files","workload"])for(let i of Array.isArray(e[o])?e[o]:[])e_(t,Z(i)?.items);let n=Z(e.agenda);for(let o of Array.isArray(n?.events)?n.events:[])ct(t,Z(o)?.item_id);let r=Z(e.tests);e_(t,r?.items_failing)}function GA(e,t){let n=Z(e);if(n===null||t_(e))return[];let r=new Set;return t==="next"?VA(n,r):BA(n,r),[...r]}async function hF(e){let t=qA(e.result);if(t===null)return!1;let n=t_(e.result);return await KA({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:GA(e.result,t.surface),resultOmitted:n}),!0}async function gF(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(o=>!o.id.trim()||!Number.isInteger(o.rank)||o.rank<1))throw new X("Context usage serving requires an author and valid ranked rows");let t=e.rows.map(o=>({id:o.id.trim(),rank:o.rank,included:o.included}));if(new Set(t.map(o=>o.id)).size!==t.length)throw new X("Context usage serving requires unique normalized row ids");let n=t.slice(0,qe.max_serving_rows),r={serve_id:zA(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:n.map(o=>o.id)};return r.storage=await Fr(e,[{kind:"serve",schema_version:2,serve_id:r.serve_id,at:zt(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:n,candidate_count:t.length,omitted_row_count:t.length-n.length,result_omitted:!1,packed_item_ids:n.filter(o=>o.included).map(o=>o.id)}]),r}async function KA(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;let t=new Set(e.receipt.rows.map(i=>i.id)),n=[...new Set(e.deliveredItemIds.map(i=>i.trim()))];if(n.some(i=>i.length===0||!t.has(i))||e.resultOmitted&&n.length>0)throw new X("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");let r=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(i=>i.id)),o={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:zt(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:n.filter(i=>r.has(i))};await Fr(e,[o],o.serve_id)}async function bF(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new X("Context usage touch requires author, itemId, and intent");await Fr(e,[{kind:"touch",at:zt(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function wF(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;let t=e.author.trim(),n=e.intent.trim();if(!t||!n)throw new X("Context usage touch requires author and intent");let r=new Set;for(let s of e.itemIds){if(typeof s!="string")throw new X("Context usage touch requires string itemIds");let a=s.trim();if(!a)throw new X("Context usage touch requires non-empty itemId");r.add(a)}let o=zt(e).iso,i=[...r].map(s=>({kind:"touch",at:o,author:t,item_id:s,intent:n}));await Fr(e,i)}function YA(e,t,n,r){return e.find(({entry:o,time:i})=>o.item_id===t&&i>=n&&i-n<=r)?.time}function XA(e,t){let n=new Map;for(let r of e)r.kind==="delivery"&&r.schema_version===2&&r.author===t&&!n.has(r.serve_id)&&n.set(r.serve_id,r);return n}async function vF(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};let t=await Ti(e),n=zt(e).ms,r=(e.horizonHours??24)*36e5;if(![Number.isFinite(r),r>0].every(Boolean))throw new X("Context usage horizonHours must be positive");let o=e.author.trim(),i=t.filter(f=>f.kind==="touch").filter(f=>f.author===o).map(f=>({entry:f,time:Date.parse(f.at)})),s=new Map,a=0,c=0,d=0,l=XA(t,o);t.filter(f=>f.kind==="serve").filter(f=>f.author===o).forEach(f=>{if(![f.schema_version===2,!!f.serve_id].every(Boolean)){c+=1;return}a+=1;let m=Date.parse(f.at),_=l.get(f.serve_id),y=new Set(_?.delivered_item_ids??[]);for(let b of f.rows){if(!y.has(b.id))continue;let v=YA(i,b.id,m,r);if(v===void 0)continue;d+=1;let T=Math.max(0,(n-v)/HA);s.set(b.id,(s.get(b.id)??0)+Math.exp(-T/14))}});let u=Math.max(0,...s.values());return{affinity:Object.fromEntries([...s.entries()].map(([f,m])=>[f,u===0?.05:.05+.95*m/u])),positive_judgments:d,serving_events:a,untrusted_serving_events:c}}(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]="b9a7ec77-c0da-589a-823e-dc1acae42797")}catch{}})();var ZA="limit_overridden_by_intent",a_=Object.freeze([{command:"context",intent:"orient",description:"Bounded active hierarchy, ownership, blockers, and recent progress.",included_field_groups:["summary","focus","hierarchy","blockers","activity"],token_budget:3e3,source:"core"},{command:"context",intent:"handoff",description:"Active ownership, evidence, decisions, and immediate continuation context.",included_field_groups:["summary","focus","in_progress","decisions","activity"],token_budget:2200,source:"core"},{command:"get",intent:"inspect",description:"Standard-depth item metadata, relationships, evidence, and lifecycle state.",included_field_groups:["item","children","claim_state","linked"],token_budget:3200,source:"core"},{command:"list",intent:"triage",description:"A budget-derived page of compact governance, ownership, priority, and blocker rows for triage.",included_field_groups:["identity","governance","ownership","dependencies"],token_budget:3200,source:"core"},{command:"next",intent:"execute",description:"The highest-ranked actionable work with concise ranking evidence.",included_field_groups:["recommended"],token_budget:1200,source:"core"},{command:"search",intent:"discover",description:"A budget-derived page of ranked canonical lineage candidates with compact match evidence.",included_field_groups:["identity","status","lineage","match"],token_budget:1800,source:"core"}]),c_=new JA;function QA(){return c_.getStore()??a_}function PF(e,t){return c_.run(tI(e.workspaceContracts,e.packageContracts),t)}function eI(e,t){let n=e.command.trim().toLowerCase(),r=e.intent.trim().toLowerCase(),o=`${n}:${r}`;if(!/^[a-z0-9][a-z0-9-]*$/.test(n)||!/^[a-z0-9][a-z0-9-]*$/.test(r))throw new TypeError(`Invalid context intent command or name: ${o}`);if(e.description.trim().length===0)throw new TypeError(`Context intent ${o} requires a non-empty description`);if(!Number.isSafeInteger(e.token_budget)||e.token_budget<=0)throw new TypeError(`Context intent ${o} requires a positive integer token_budget`);let i=[...new Set(e.included_field_groups.map(s=>s.trim()).filter(Boolean))];if(i.length===0)throw new TypeError(`Context intent ${o} requires included_field_groups`);return{command:n,intent:r,description:e.description.trim(),included_field_groups:i,token_budget:e.token_budget,source:t}}function tI(e=[],t=[]){let n=[{source:"core",contracts:a_,allowOverride:!1},{source:"package",contracts:t,allowOverride:!1},{source:"workspace",contracts:e,allowOverride:!0}],r=new Map,o=new Set;for(let i of n){o.clear();for(let s of i.contracts){let a=eI(s,i.source),c=`${a.command}:${a.intent}`;if(o.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);if(o.add(c),!i.allowOverride&&r.has(c))throw new TypeError(`Duplicate context intent declaration: ${c}`);r.set(c,a)}}return[...r.values()].sort((i,s)=>i.command.localeCompare(s.command)||i.intent.localeCompare(s.intent))}function d_(e,t,n=QA(),r=[]){let o=e.trim().toLowerCase(),i=t.trim().toLowerCase(),s=n.find(f=>f.command===o&&f.intent===i);if(s)return{...s,source:s.source??"core"};let a=n.filter(f=>f.command===o).map(f=>f.intent);if(a.length===0)return;let c=a.map(f=>{let m=Array.from({length:i.length+1},(_,y)=>y);for(let _=1;_<=f.length;_+=1){let y=m[0];m[0]=_;for(let b=1;b<=i.length;b+=1){let v=m[b];m[b]=Math.min(m[b]+1,m[b-1]+1,y+(f[_-1]===i[b-1]?0:1)),y=v}}return{candidate:f,distance:m[i.length]}}).sort((f,m)=>f.distance-m.distance||f.candidate.localeCompare(m.candidate))[0].candidate,d=[o,...r,"--for",i],l=[o,...r,"--for",c],u=dn(l);throw new g(`Unknown context intent "${i}" for ${o}. Did you mean "${c}"?`,h.USAGE,{code:"unknown_context_intent",reason:"unknown_intent",field:"for",flag:"--for",value:i,required:`Use a declared ${o} intent.`,why:"Intent names are command-local contracts and cannot be inferred from output section names.",nextSteps:[u],recovery:{recovery_mode:"compact",attempted_command:dn(d),allowed_values:[...a].sort(),suggested_retry:u,suggested_retry_args:l}})}function jc(e,t){let n=Vt(e.limit),r=String(n===void 0?t:Math.min(n,t));return(e.limit===void 0||n!==void 0)&&(e.limit=r),r}var l_={context:(e,t,n,r)=>{e.section===void 0&&e.depth===void 0&&(e.section=t.intent==="handoff"?["activity","progress","blockers"]:["hierarchy","blockers","activity"]),e.depth===void 0&&(e.depth=t.intent==="handoff"?"deep":"standard");let o=xi(r,e.tokenBudget,t.token_budget),i=Ni("context",t.intent,o,n),s=jc(e,i);e.activityLimit===void 0&&(e.activityLimit=s)},get:e=>{e.depth===void 0&&e.fields===void 0&&(e.depth="standard")},list:(e,t,n,r)=>{e.brief===void 0&&e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.fields="id,title,status,type,priority,parent,assignee,risk,blocked_by");let o=xi(r,e.tokenBudget,t.token_budget),i=Ni("list",t.intent,o,n);jc(e,i)},next:e=>{e.readyOnly===void 0&&(e.readyOnly=!0)},search:(e,t,n,r)=>{e.compact===void 0&&e.full===void 0&&e.fields===void 0&&(e.compact=!0);let o=xi(r,e.tokenBudget,t.token_budget),i=Ni("search",t.intent,o,n);jc(e,i)}};function MF(e,t,n=[]){let r=t.tokenBudget??t.token_budget;if(typeof t.for!="string"){if(r!==void 0&&(e==="get"||e==="list"||e==="search"))throw new g("--token-budget requires a declared context intent selected with --for",h.USAGE,{code:"missing_required_option",field:"for",required:"Select a context intent with --for when setting --token-budget.",why:"A token-budget override has no projection contract to constrain without a selected intent.",nextSteps:["Retry with --for <intent> --token-budget <n>, or omit --token-budget."]});if(t.tokenBudget!==void 0||t.token_budget===void 0)return t;let c={...t,tokenBudget:r};return delete c.token_budget,c}let o=d_(e,t.for,void 0,n),i=Ur(t),s=Vt(r)!==void 0||typeof i=="number",a={...t};return a.tokenBudget===void 0&&r!==void 0&&(a.tokenBudget=r),delete a.token_budget,typeof i=="number"?a.tokenBudget=String(i):a.tokenBudget===void 0&&(a.tokenBudget=String(o.token_budget)),l_[e](a,o,s,i),a}var nI={context:"bounded_sections",get:"standard_item",list:"bounded_fields_and_rows",next:"bounded_ranked_rows",search:"bounded_ranked_rows"},Ri=256;function Fc(e){return Array.isArray(e)?e.map(Fc):e!==null&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([t,n])=>[t,Fc(n)])):typeof e=="string"&&e.length>240?`${Ee(e,240)}\u2026`:e}function Vt(e){let t=typeof e=="number"?e:typeof e=="string"&&/^\d+$/u.test(e.trim())?Number(e):Number.NaN;return Number.isSafeInteger(t)&&t>0?t:void 0}function Ur(e){let t=e.outputBudget??e.output_budget;return t==="unbounded"?t:Vt(t)}function rI(e){return Ur(e)===void 0?"--token-budget":"--output-budget"}function xi(e,t,n){return typeof e=="number"?e:oI(t,n)}function oI(e,t){let n=Vt(e);if(n===void 0)return t;if(n<Ri)throw new g(`Context intent token budget must be at least ${Ri}`,h.USAGE,{code:"invalid_argument_value",reason:"below_minimum",field:"tokenBudget",value:String(e),required:`Use an integer token budget of at least ${Ri}.`,why:"Smaller ceilings cannot contain the minimum machine-readable intent receipt.",nextSteps:[`Retry with --token-budget ${Ri} or omit the override.`]});return n}function u_(e,t){return e==="context"?e==="context"&&t==="orient"?{overhead:1200,rowCost:600}:{overhead:800,rowCost:500}:{overhead:e==="list"?520:480,rowCost:16}}function Ni(e,t,n,r){if(e==="get"||e==="next")return;let{overhead:o,rowCost:i}=u_(e,t),s=Math.max(e==="context"?1:2,Math.floor((n-o)/i));return r?s:Math.min(e==="context"?20:100,s)}function Bt(e,t,n){let r=Mn(n),o=n.outputRowContract===!0||n.output_row_contract===!0,i=t.estimated_tokens,s=i;for(let a=0;a<zc;a+=1){t.estimated_tokens=i;let c=it(o||!Object.hasOwn(e,"row_contract")?e:Object.fromEntries(Object.entries(e).filter(([d])=>d!=="row_contract")),r);if(c===i)return;i=c,s=Math.max(s,i)}t.estimated_tokens=s}var r_={context:["high_level","low_level","blocked_fallback","recently_created","unparented","hierarchy","activity","blockers"],get:["children"],list:["items"],next:["ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items"]};function f_(e){try{let t=JSON.parse(Buffer.from(e,"base64url").toString("utf8"));return typeof t.fingerprint!="string"||!Number.isSafeInteger(t.after_index)?void 0:{fingerprint:t.fingerprint,after_index:t.after_index,...typeof t.snapshot=="string"?{snapshot:t.snapshot}:{}}}catch{return}}function iI(e){if(e===null||typeof e!="object")return;if(typeof e.id=="string")return e.id;let t=e.item?.id;return typeof t=="string"?t:void 0}function sI(e,t,n,r){let o=!1;for(;;){if(Bt(e,t,r),t.estimated_tokens<=t.token_budget||n.length<=1)return o;let i=Buffer.byteLength(JSON.stringify(n),"utf8"),s=(t.estimated_tokens-t.token_budget)*4;n.splice(-Math.min(n.length-1,Math.max(1,Math.ceil(s/Math.max(1,Math.ceil(i/n.length)))))),o=!0}}function aI(e,t,n){let r=e.items,o=typeof e.next_cursor=="string",i=o?e.next_cursor:n.after;if(!Array.isArray(r)||typeof i!="string")return!1;let s=f_(i);if(s===void 0)return!1;let a=r.length,c=[...r],d=!1;for(;;){if(d=sI(e,t,r,n)||d,!d)return!1;let l=iI(r.at(-1));if(l===void 0)return r.splice(0,r.length,...c),Bt(e,t,n),!1;if(e.next_cursor=jr(s.fingerprint,l,o?s.after_index-(a-r.length):s.after_index+r.length,s.snapshot),Bt(e,t,n),t.estimated_tokens<=t.token_budget||r.length<=1)break}return typeof e.count=="number"&&(e.count=r.length),typeof e.applied_limit=="number"&&(e.applied_limit=r.length),!0}function cI(e,t,n,r){if(e==="list"||e==="search")return aI(t,n,r);if(e!=="next"||typeof t.next_cursor=="string")return!1;let o=!1;for(;;){if(Bt(t,n,r),n.estimated_tokens<=n.token_budget)return o;let i=r_[e].map(f=>({key:f,rows:Array.isArray(t[f])?t[f]:[]})).filter(({rows:f})=>f.length>0).sort((f,m)=>m.rows.length-f.rows.length||f.key.localeCompare(m.key))[0];if(i===void 0)return o;let s=r_[e].reduce((f,m)=>f+(Array.isArray(t[m])?t[m].length:0),0);if(s<=1)return o;let a=Math.min(i.rows.length,s-1),c=Buffer.byteLength(JSON.stringify(i.rows),"utf8"),d=Math.max(1,Math.ceil(c/i.rows.length)),l=(n.estimated_tokens-n.token_budget)*4,u=Math.min(a,Math.max(1,Math.ceil(l/d)));i.rows.splice(-u,u),o=!0}}function o_(e,t,n){if(typeof t.for!="string")return n;let r=e.startsWith("list-")?"list":e;if(!(r in l_))return n;let o=r,i=d_(o,t.for),s=Ur(t),a=xi(s,t.tokenBudget??t.token_budget,i.token_budget),c={command:o,intent:i.intent,source:i.source,included_field_groups:[...i.included_field_groups],token_budget:a,declared_token_budget:i.token_budget,token_budget_override:a-i.token_budget,estimated_tokens:0,within_budget:!0,degradation:nI[o],declaration_feasible:!0,result_omitted:!1},d={...n},l=Ni(o,i.intent,c.token_budget,Vt(t.tokenBudget??t.token_budget)!==void 0||typeof s=="number");if(l!==void 0){let y=Vt(t.limit),b=y!==void 0&&y<l;c.budget_derived_limit=l,c.binding_constraint=b?"explicit_limit":"token_budget",c.limit_reason=b?"The caller supplied a smaller row limit than the budget-derived ceiling.":"The selected intent token budget constrains the effective row ceiling.",d.budget_derived_limit=l,pI({builtInCommand:o,intent:i.intent},c,d,t)}let u=m_.get(t)??0,f=c.token_budget;c.token_budget=f-u;let m=s==="unbounded"?Uc(d,c,t):dI(o,d,c,t);c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget;let _=p_(s,c,m,()=>y_(e,o,i.intent,{...c,token_budget:f,estimated_tokens:c.estimated_tokens+u},d,t));return c.result_omitted&&(c.estimated_tokens+=u,c.declaration_feasible=c.estimated_tokens<=c.declared_token_budget),c.token_budget=f,_}function Uc(e,t,n){let r={...e,context_intent:t};return Bt(r,t,n),r}function dI(e,t,n,r){let o=Uc(t,n,r);return n.estimated_tokens>n.token_budget&&(n.degradation="recursive_budget_compaction",o=Uc(Fc(t),n,r)),n.estimated_tokens>n.token_budget&&cI(e,o,n,r)&&(n.degradation="budget_row_compaction",Bt(o,n,r)),o}var m_=new WeakMap;function p_(e,t,n,r){return t.estimated_tokens<=t.token_budget||(t.within_budget=!1,e==="unbounded")?n:(t.degradation="budget_receipt_only",t.result_omitted=!0,typeof e=="number"?{output_budget_exceeded:{omitted_result:!0,reason:"requested_budget_infeasible",restore_with:"Unbounded",recovery:{outputBudget:"unbounded"}},context_intent:t}:{budget_exceeded:{omitted_result:!0,reason:t.token_budget_override===0?"declared_budget_infeasible":"effective_budget_infeasible",restore_with:r()},context_intent:t})}var lI=["applied_limit","completeness","context_intent","count","filters","has_more","now","omission_receipt","projection","row_contract","sorting","total","truncated"];function uI(e,t){if(typeof e.after!="string"||e.after.length===0||Ne(t))return t;let n=f_(e.after)?.fingerprint??"opaque_cursor",r={...t};for(let o of lI)delete r[o];return r.continuation_contract={fingerprint:n,metadata:"reference",restore_with:"omit --after"},r}function dt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fI(e,t){let n=e==="get"&&dt(t.item)&&typeof t.item.id=="string"?t.item.id:e==="search"&&typeof t.query=="string"?t.query:void 0;return n===void 0?"":` ${__(n)}`}function __(e){return`'${e.replaceAll("'",`'"'"'`)}'`}function mI(e){return typeof e.fields=="string"&&e.fields.trim()!==""?` --fields ${__(e.fields)}`:""}function pI(e,t,n,r){let o=Vt(r.limit),i=t.budget_derived_limit;if(o===void 0||o<=i)return;let{overhead:s,rowCost:a}=u_(e.builtInCommand,e.intent),c=Math.max(t.token_budget,s+a*o);t.limit_reason=`The ${t.token_budget}-token ${e.intent} budget carries ${i} rows, so it reduced the caller's --limit ${o}.`,t.limit_override={flag:"--limit",requested:o,effective:i,...Number.isSafeInteger(c)?{token_budget_for_requested:c,restore_with:`${rI(r)} ${c}`}:{}};let d=`${ZA}:--limit ${o}->${i}`;n.warnings=Array.isArray(n.warnings)?[...n.warnings,d]:[d],dt(n.filters)&&(n.filters={...n.filters,requested_limit:String(o)})}function y_(e,t,n,r,o,i){let s=fI(t,o),a=t==="get"?"":` --limit ${r.budget_derived_limit??1}`,{output_budget:c}=Pr({effective_budget_tokens:r.token_budget,measured_result_tokens:r.estimated_tokens});return`pm ${e}${s}${mI(i)} --for ${n} --token-budget ${c}${a}`}function qt(e,t){if(dt(e))return typeof e[t]=="number"?e[t]:void 0}function i_(e,t){let n=e;for(let r=0;r<8;r+=1){_I(n);let o=qt(n.context_intent,"estimated_tokens"),i=qt(n.read_output,"estimated_tokens"),s=qt(n.read_session,"spent_this_call_tokens");if(dt(n.context_intent)&&n.context_intent.result_omitted!==!0&&Bt(n,n.context_intent,t),n=xc(n,t),qt(n.context_intent,"estimated_tokens")===o&&qt(n.read_output,"estimated_tokens")===i&&qt(n.read_session,"spent_this_call_tokens")===s)break}return n}function _I(e){let t=e.context_intent;dt(t)&&Number(t.estimated_tokens)>Number(t.token_budget)&&(t.within_budget=!1)}function Hc(e,t,n){let r=Zm(e,cp(e??"",n));if(typeof r!="object"||r===null||Array.isArray(r))return Ht(n,r),r;let o=e??"",i=r,s=o_(o,t,i),a=qt(s.context_intent,"estimated_tokens"),c=Lc(o,t,n,s),d=s_(t,c,s.context_intent);if(d===void 0)return c;let l={...t};m_.set(l,d.estimated-Number(a));let u=o_(o,l,i),f=Lc(o,l,n,u),m=s_(t,f,u.context_intent);if(m===void 0)return f;let _={...m.receipt,estimated_tokens:m.estimated};return Lc(o,t,n,p_(Ur(t),_,f,()=>y_(o,_.command,_.intent,_,i,t)))}function s_(e,t,n){let r=dt(t.context_intent),o=r?t.context_intent:n;if(!dt(o)||o.result_omitted===!0||Object.hasOwn(t,"output_budget_exceeded"))return;let i=o,s=r?i.estimated_tokens:it(t,Mn(e));return Ur(e)==="unbounded"||s<=i.token_budget?void 0:{receipt:i,estimated:s}}function Lc(e,t,n,r){let o=zp(e,{...t,outputRowContract:t.outputRowContract===!0||t.output_row_contract===!0},uI(t,r));if(Ht(n,o),t.outputRowContract===!0||t.output_row_contract===!0||!Object.hasOwn(o,"row_contract"))return dt(o.context_intent)?i_(o,t):o;let i=Object.fromEntries(Object.entries(o).filter(([a])=>a!=="row_contract"));Object.defineProperty(i,"row_contract",{value:o.row_contract,enumerable:!1,configurable:!0});let s=i_(i,t);return delete s.row_contract,Ht(o,s),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]="cb1266f3-8375-586f-87c6-356cf7843969")}catch{}})();var Ln=["result_rows","envelope","diagnostics","hints"],yI=/^(?:items|results|rows|ready|blocked|recommended|decision_needed|children|dependencies|events|matches|commands|tools)$/u,hI=/^(?:diagnostics|errors?|warnings?|findings|violations|failures?)$/u,gI=/^(?:hints?|suggestions?|next_steps?|recovery|remediation|examples?)$/u,bI=8;function qc(e){return Buffer.byteLength(e,"utf8")}function h_(e){return qc(JSON.stringify(e)??"null")}function wI(e,t){return hI.test(e)?"diagnostics":gI.test(e)?"hints":yI.test(e)||Array.isArray(t)?"result_rows":"envelope"}function vI(e){let t={result_rows:0,envelope:0,diagnostics:0,hints:0};if(typeof e!="object"||e===null||Array.isArray(e))return t[Array.isArray(e)?"result_rows":"envelope"]=h_(e),t;for(let[n,r]of Object.entries(e))t[wI(n,r)]+=h_({[n]:r});return Object.values(t).every(n=>n===0)&&(t.envelope=1),t}function EI(e,t){let n=Ln.reduce((s,a)=>s+t[a],0),r=Ln.map(s=>({section:s,value:e*t[s]/n})),o={result_rows:0,envelope:0,diagnostics:0,hints:0};for(let s of r)o[s.section]=Math.floor(s.value);let i=e-Ln.reduce((s,a)=>s+o[a],0);for(let s of[...r].sort((a,c)=>c.value-Math.floor(c.value)-(a.value-Math.floor(a.value))||Ln.indexOf(a.section)-Ln.indexOf(c.section))){if(i===0)break;o[s.section]+=1,i-=1}return o}function g_(e,t){return typeof e=="object"&&e!==null&&!Array.isArray(e)?{...e,token_accounting:t}:{result:e,token_accounting:t}}function b_(e,t){let n=qc(t(e)),r=EI(n,vI(e)),o=Object.fromEntries(Ln.map(a=>[a,{bytes:r[a],estimated_tokens:jt(r[a])}])),i={version:1,measurement_scope:"output_before_token_accounting",estimator:"ceil(utf8_bytes / 4)",total_bytes:n,total_estimated_tokens:jt(n),sections:o,accounting_receipt_bytes:0,accounting_receipt_estimated_tokens:0,excluded_fields:["token_accounting"],section_allocation:"proportional_canonical_json"},s=g_(e,i);for(let a=0;a<bI;a+=1){let c=qc(t(s))-n;if(c===i.accounting_receipt_bytes)return s;i={...i,accounting_receipt_bytes:c,accounting_receipt_estimated_tokens:jt(c)},s=g_(e,i)}return 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]="787e6c05-d503-5602-a173-e6a59699cea6")}catch{}})();var w_=Object.freeze({comments:Object.freeze(["comments"]),notes:Object.freeze(["notes"]),learnings:Object.freeze(["learnings"])});function v_(e){return e===void 0||!Object.hasOwn(w_,e)?[]:w_[e]}(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]="8e86e884-98ca-5b28-838b-db3543051112")}catch{}})();var E_=new Set(["body","item_hash","linked","claim_state","children","schedule","blockers"]),UF=new Set(["linked","claim_state","children","schedule"]);import{encode as Gc}from"@toon-format/toon";(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]="d3d21124-3c8a-5049-803d-00c63c0c2b61")}catch{}})();function k_(e,t={}){let n=[...new Set(e.flatMap(l=>Object.keys(l)))],r=t.compact?n.filter(l=>e.every(u=>Object.hasOwn(u,l)&&u[l]===null)):[],o=t.compact?n.filter(l=>e.every(u=>{if(!Object.hasOwn(u,l))return!0;let f=u[l];return Array.isArray(f)&&f.every(m=>typeof m=="string"&&m!==""&&!m.includes(";"))})):[],i=new Set(o),s=new Set(r),a=n.filter(l=>!i.has(l)&&e.some(u=>{let f=u[l];return f!==null&&typeof f=="object"})),c=new Set(a),d=[];return{rows:e.map((l,u)=>Object.fromEntries(n.filter(f=>!s.has(f)).map(f=>{if(!Object.hasOwn(l,f))return d.push([u,f]),[f,null];let m=l[f];return i.has(f)?[f,m.join(";")]:[f,c.has(f)?JSON.stringify(m):m]}))),encoding:{json_columns:a,absent:d,...o.length?{list_columns:Object.fromEntries(o.map(l=>[l,";"]))}:{},...r.length?{null_columns:r,null_column_index:r.map(l=>n.indexOf(l))}:{}}}}function kI(e,t){let n=t.null_columns??[],r=t.null_column_index??[],o=[...e],i=n.map((s,a)=>({column:s,position:r[a]})).filter(s=>typeof s.position=="number").sort((s,a)=>s.position-a.position);for(let{column:s,position:a}of i)o.splice(Math.min(a,o.length),0,s);for(let s of n)o.includes(s)||o.push(s);return o}function HF(e){let t=new Set(e.encoding.json_columns),n=new Map(Object.entries(e.encoding.list_columns??{})),r=new Set(e.encoding.absent.map(([o,i])=>JSON.stringify([o,i])));return e.rows.map((o,i)=>{let s=new Map(Object.entries(o).flatMap(([c,d])=>{if(r.has(JSON.stringify([i,c])))return[];let l=n.get(c),u=l!==void 0?d===""?[]:String(d).split(l):t.has(c)?JSON.parse(String(d)):d;return[[c,u]]}));for(let c of e.encoding.null_columns??[])s.set(c,null);let a=e.encoding.column_order??kI(Object.keys(o),e.encoding);return Object.fromEntries(a.filter(c=>s.has(c)).map(c=>[c,s.get(c)]))})}(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]="43d2915b-7301-5e96-89e0-51c8e817789e")}catch{}})();function De(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var SI=new Set(["brief","compact","fields"]);function S_(e){if(!De(e))return!1;let t=e.fields;return SI.has(e.mode)&&Object.keys(e).length===2&&Array.isArray(t)&&t.length>0&&t.every(n=>typeof n=="string"&&n.length>0)}function O_(e,t){return e.every(n=>De(n)&&Object.keys(n).length===t.fields.length&&t.fields.every(r=>Object.hasOwn(n,r)))}function A_(e,t){return e.mode==="fields"&&t===0?{projection:e}:{}}function I_(e,t){return typeof e.has_more=="boolean"&&e.truncated===e.has_more&&e.count===t&&typeof e.total=="number"&&Number.isSafeInteger(e.total)&&(e.has_more?e.total>t&&typeof e.next_cursor=="string"&&e.next_cursor.length>0:e.total===t&&e.next_cursor==null)}function OI(e){return De(e)&&(e.status==="complete"||e.status==="unchecked")&&e.unreadable_item_count===0&&e.unreadable_directory_count===0}function Vc(e,t="full_item_fields"){if(!De(e)||!Array.isArray(e.omitted_field_groups))return!1;let n=e.omitted_field_groups,r=n[0];return e.has_omissions===!0&&e.omitted_field_group_count===1&&Object.keys(e).length===3&&n.length===1&&De(r)&&Object.keys(r).length===2&&r.name===t&&r.restore_with==="--full"}function T_(e){if(!De(e)||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!S_(e.projection)||!O_(e.items,e.projection)||!OI(e.completeness)||!I_(e,e.items.length)||!Vc(e.omission_receipt))return e;let{total:t,has_more:n,truncated:r,next_cursor:o,completeness:i,projection:s,now:a,omission_receipt:c,sorting:d,filters:l,...u}=e,f=i.status==="complete"&&!n&&Object.keys(i).length===3,{unreadable_item_count:m,unreadable_directory_count:_,...y}=i;return{...u,...f?{}:{total:t,has_more:n,completeness:y},...n?{next_cursor:o}:{},...TI(d),...C_(l,u.applied_limit,s),...A_(s,e.items.length),details:"--full"}}function AI(e){return De(e)&&e.sort==="default"&&e.order==="asc"&&Object.keys(e).every(t=>t==="sort"||t==="order"||t==="effective_keys")}function II(e){return Array.isArray(e)&&e.length===2&&typeof e[0]=="string"&&(e[1]==="asc"||e[1]==="desc")}function TI(e){if(!AI(e))return{sorting:e};let t=e.effective_keys;return t===void 0?{}:!Array.isArray(t)||!t.every(II)?{sorting:e}:{sorting:{effective_keys:t.map(([n,r])=>`${n} ${r}`).join(", ")}}}function CI(e,t){if(typeof e!="string"||t===void 0)return!1;let n=e.split(",").map(r=>r.trim()).filter(Boolean);return n.length===t.fields.length&&n.every((r,o)=>r===t.fields[o])}function C_(e,t,n){if(!De(e))return e===void 0?{}:{filters:e};let r=Object.fromEntries(Object.entries(e).filter(([o,i])=>!(o==="limit"&&String(i)===String(t))&&!(o==="fields"&&CI(i,n))&&!(o==="runtime_filters"&&De(i)&&Object.keys(i).length===0)));return Object.keys(r).length===0?{}:{filters:r}}function RI(e,t){return e.count===t&&!Object.hasOwn(e,"has_more")&&!Object.hasOwn(e,"truncated")&&e.next_cursor==null&&(e.total===void 0||e.total===t)}function xI(e){if(!Object.hasOwn(e,"projection"))return Vc(e.omission_receipt,"projection_metadata")?{}:void 0;let t=e.projection;return S_(t)&&t.mode==="fields"&&O_(e.items,t)&&typeof e.now=="string"&&Vc(e.omission_receipt)?{projection:t}:void 0}function R_(e){if(!De(e)||typeof e.query!="string"||!Array.isArray(e.items)||Object.hasOwn(e,"details")||!(I_(e,e.items.length)||RI(e,e.items.length)))return e;let t=xI(e);if(t===void 0)return e;let{truncated:n,omission_receipt:r,filters:o,projection:i,now:s,mode_source:a,...c}=e;return{...c,...a==="settings"||t.projection===void 0&&a!==void 0?{mode_source:a}:{},...C_(o,c.applied_limit,t.projection),...t.projection?A_(t.projection,e.items.length):{},details:"--full"}}import{isBoxedPrimitive as NI}from"node:util/types";(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]="1b399abd-460a-55a5-9df2-db23537aac0d")}catch{}})();var x_=/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/gu;function KF(e){return e.replaceAll(x_,"\uFFFD")}function DI(e,t,n){return n&&/^\d+$/u.test(t)?`${e}[${t}]`:/^[A-Za-z_$][\w$]*$/u.test(t)?`${e}.${t}`:`${e}[${JSON.stringify(t)}]`}function Bc(e,t,n){if(typeof e=="string"){let r=e.search(x_);return r<0?void 0:{field:t,index:r}}if(!(e===null||typeof e!="object"||n.has(e))){n.add(e);for(let[r,o]of Object.entries(e)){let i=DI(t,r,Array.isArray(e)),s=Bc(r,`${i} (key)`,n)??Bc(o,i,n);if(s)return s}}}function N_(e,t,n){if(e===null||typeof e!="object")return e;if(NI(e)||typeof e.toJSON=="function")return JSON.parse(JSON.stringify({[t]:e}))[t];if(n.has(e))return n.get(e);let r=Array.isArray(e)?new Array(e.length):{};n.set(e,r);for(let o of Object.keys(e))Object.defineProperty(r,o,{value:N_(e[o],o,n),enumerable:!0,configurable:!0,writable:!0});return r}function Wc(e){let t=N_(e,"",new WeakMap),n=Bc(t,"$",new WeakSet);return n&&PI(n),t}function PI(e){throw new g(`Output field ${e.field} contains an unpaired surrogate code unit at index ${e.index}; structured output requires well-formed Unicode.`,h.USAGE,{code:"text_unpaired_surrogate",field:e.field,required:"Well-formed UTF-16 strings and object keys in both JSON and TOON output.",nextSteps:["Repair the producer's text before returning output; use toWellFormedText from @unbrained/pm-cli/sdk when replacement is intended."]})}function YF(e){Wc(e)}(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]="a378018f-b981-5e5e-98a4-45d190039473")}catch{}})();var MI=new Set(Object.values(h)),$I=new Map([["notes_count","notes"],["tests_count","tests"]]),Kc="__pm_native_output",D_=!1;function x(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ed(e){let t={read_output:{result_omitted:!0}};Ht(e,t),zo(t)}function Yc(e,t,n){if(n){zo(e);return}ed(t)}function jI(e){if(!x(e)||e[Kc]!==!0)return e;let{[Kc]:t,...n}=e;return n}function Xc(e){return typeof e=="object"&&e!==null&&e.code==="EPIPE"}function LI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.SUCCESS)}function FI(){(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=h.GENERIC_FAILURE)}function Jc(e){if(e==="stdout"){LI();return}FI()}function P_(e){let t=e instanceof Error?e:new Error(String(e));setImmediate(()=>{throw t})}function UI(){D_||(D_=!0,process.stdout.on("error",e=>{if(Xc(e)){Jc("stdout");return}P_(e)}),process.stderr.on("error",e=>{if(Xc(e)){Jc("stderr");return}P_(e)}))}function M_(e,t){UI();try{return e==="stdout"?process.stdout.write(t):process.stderr.write(t),!0}catch(n){if(Xc(n))return Jc(e),!1;throw n}}function zI(e){return M_("stdout",e)}function zr(e){return M_("stderr",e)}function $_(e){return typeof e=="string"?JSON.stringify(e):typeof e=="number"||typeof e=="boolean"?String(e):e===null?"null":JSON.stringify(e)}function Zc(e,t){let n=" ".repeat(t);return e.split(`
29
29
  `).map(r=>`${n}${r}`).join(`
30
- `)}function DI(e){let t=new Set,n=0;for(let r of e){let o=Object.keys(r);n+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=n*2}function PI(e,t,n,r){let o=" ".repeat(n);if(!x(t)&&!Array.isArray(t))return`${o}${e}: ${x_(t)}`;if(e==="omission_receipt"&&KI(t))return`${o}${e}: complete`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=Kc(qc({[e]:t}),n);return r&&t.length>=1&&t.every(x)&&DI(t)?[!1,!0].map(s=>{let a=g_(t,{compact:s});return Kc(qc({[e]:a.rows,[`${e}_encoding`]:a.encoding}),n)}).reduce((s,a)=>Buffer.byteLength(a)<Buffer.byteLength(s)?a:s,i):i}return x(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
31
- ${N_(t,n+1)}`}function MI(e,t,n){let r=e.map(o=>Wt(o,t,n||t.preserveRowFacts&&x(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function Wt(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return MI(e,t,n);if(x(e)){let r=[],o=Object.entries(e).filter(([i,s])=>{let a=II.get(i);return!t.omitDuplicateCountAliases||a===void 0||!x(e.collection_counts)||s!==e.collection_counts[a]});for(let[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){r.push([i,[]]);continue}let a=Wt(s,t,n);a!==void 0&&r.push([i,a])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function N_(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":Kc(qc(e),t);if(x(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>PI(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&x(e.verdict)&&e.verdict.authority==="ok"))).join(`
32
- `)}return`${n}${x_(e)}`}function jI(e){if(!x(e)||e.output_default!=="markdown"||typeof e.view!="string"||!Array.isArray(e.events)||!Array.isArray(e.days))return null;let t=[`# pm calendar (${e.view})`,""],n=x(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
30
+ `)}function HI(e){let t=new Set,n=0;for(let r of e){let o=Object.keys(r);n+=o.length;for(let i of o)t.add(i)}return e.length*t.size<=n*2}function qI(e,t,n,r){let o=" ".repeat(n);if(!x(t)&&!Array.isArray(t))return`${o}${e}: ${$_(t)}`;if(e==="omission_receipt"&&rT(t))return`${o}${e}: complete`;if(Array.isArray(t)){if(t.length===0)return`${o}${e}: []`;let i=Zc(Gc({[e]:t}),n);return r&&t.length>=1&&t.every(x)&&HI(t)?[!1,!0].map(s=>{let a=k_(t,{compact:s});return Zc(Gc({[e]:a.rows,[`${e}_encoding`]:a.encoding}),n)}).reduce((s,a)=>Buffer.byteLength(a)<Buffer.byteLength(s)?a:s,i):i}return x(t)&&Object.keys(t).length===0?`${o}${e}: {}`:`${o}${e}:
31
+ ${j_(t,n+1)}`}function VI(e,t,n){let r=e.map(o=>Wt(o,t,n||t.preserveRowFacts&&x(o))).filter(o=>o!==void 0);return r.length>0||n?r:void 0}function Wt(e,t={omitDuplicateCountAliases:!0,preserveRowFacts:!0},n=!1){if(e===null)return n?null:void 0;if(Array.isArray(e))return VI(e,t,n);if(x(e)){let r=[],o=Object.entries(e).filter(([i,s])=>{let a=$I.get(i);return!t.omitDuplicateCountAliases||a===void 0||!x(e.collection_counts)||s!==e.collection_counts[a]});for(let[i,s]of o){if(i==="omitted_field_groups"&&Array.isArray(s)&&s.length===0){r.push([i,[]]);continue}let a=Wt(s,t,n);a!==void 0&&r.push([i,a])}return r.length>0||n?Object.fromEntries(r):void 0}return e}function j_(e,t){let n=" ".repeat(t);if(Array.isArray(e))return e.length===0?"[]":Zc(Gc(e),t);if(x(e)){let r=Object.entries(e);return r.length===0?"{}":r.map(([o,i])=>qI(o,i,t,!Object.hasOwn(e,`${o}_encoding`)&&!(o==="checks"&&x(e.verdict)&&e.verdict.authority==="ok"))).join(`
32
+ `)}return`${n}${$_(e)}`}function BI(e){if(!x(e)||e.output_default!=="markdown"||typeof e.view!="string"||!Array.isArray(e.events)||!Array.isArray(e.days))return null;let t=[`# pm calendar (${e.view})`,""],n=x(e.summary)?e.summary:{};if(t.push(`- events: ${String(n.events??0)}`),t.push(""),e.events.length===0)return t.push("No calendar events matched the selected filters."),`${t.join(`
33
33
  `)}
34
34
  `;for(let r of e.events){if(!x(r))continue;let o=typeof r.kind=="string"?r.kind:"event",i=typeof r.item_title=="string"?r.item_title:"",s=typeof r.item_id=="string"?r.item_id:"",a=typeof r.reminder_text=="string"&&r.reminder_text.length>0?` ${r.reminder_text}`:"";t.push(`- [${o}] ${s} ${i}${a}`.trim())}return`${t.join(`
35
35
  `)}
36
- `}var $I=new Set(["filters","now","projection","sorting"]);function LI(e){let t=Wt(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!x(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!$I.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function FI(e,t){if(!x(e)||!Array.isArray(e.run_results)||!e.run_results.every(x))return e;let n=e.run_results,r=UI(n),o=n.map(i=>{let{execution_context:s,stdout:a,stderr:c,...d}=i;return r===void 0?i:!t||i.status!=="passed"?{...d,stdout:a,stderr:c}:d});return t&&zI(e,r,n)?HI(e,r,o):{...e,...r===void 0?{}:{execution_context:r},run_results:o}}function UI(e){let t=e.map(r=>r.execution_context).filter(r=>r!==void 0);if(t.length!==e.length||t.length===0)return;let n=JSON.stringify(t[0]);return t.every(r=>JSON.stringify(r)===n)?t[0]:void 0}function zI(e,t,n){if(e.ok!==!0||!x(t)||t.mismatch_detected!==!1||!n.every(o=>o.status==="passed"))return!1;let r=e.failure_categories;return!(x(r)&&Object.values(r).some(o=>o!==0))}function HI(e,t,n){let{failure_categories:r,...o}=e,i=x(t.trust)?t.trust:{};return{...o,execution_context:{pm_context_mode:t.pm_context_mode,workspace_context_mode:t.workspace_context_mode,mismatch_detected:!1,...typeof i.trusted=="boolean"?{trusted:i.trusted}:{},...i.reason===void 0?{}:{trust_reason:i.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:n}}function qI(e){return!x(e)||e.ok!==!0||!x(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(VI)}}function VI(e){if(!x(e)||e.ok!==!0||!x(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...n}=e;return n}function Di(e,t,n=!1,r={}){if(e=Hc(e),t==="json"){let i=n?LI(e):e,s=x(e)&&x(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(i,null,s?void 0:2)}
37
- `}let o=WI(e,BI(e,Wt(qI(O_(k_(e))),Pi),r.preserveEmptyItemCollections===!0),r.positionalRowPaths??[]);return o===void 0?`{}
38
- `:`${N_(o,0)}
39
- `}var Pi={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function Yc(e,t,n=!1){if(Array.isArray(e)){if(e.length===0)return[];let i=Array.isArray(t)?t:[],s=i.length===e.length,a=0,c=e.flatMap(d=>{let l=n||x(d),u=!s&&Wt(d,Pi,l)===void 0,f=Yc(d,u?void 0:i[a++],l);return f===void 0?[]:[f]});return c.length>0?c:t}if(!x(e))return t;let r=x(t)?t:{},o=Object.entries(e).flatMap(([i,s])=>{let a=Yc(s,Object.hasOwn(r,i)?r[i]:void 0,n);return a===void 0?[]:[[i,a]]});return o.length>0||Object.keys(e).length===0?Object.fromEntries(o):t}function BI(e,t,n){if(!n||!x(e))return t;let r=x(t)?t:{},o=new Map(Object.keys(e).filter(i=>i==="item"||h_.has(i)).map(i=>[i,Yc(e[i],r[i])]));return D_(e,r,o)}function D_(e,t,n){let r=Object.entries(t).map(([i,s])=>[i,n.has(i)?n.get(i):s]),o=Object.keys(e);for(let[i,s]of n){if(Object.hasOwn(t,i)||s===void 0)continue;let a=new Set(o.slice(o.indexOf(i)+1)),c=r.findIndex(([d])=>a.has(d));r.splice(c===-1?r.length:c,0,[i,s])}return Object.fromEntries(r)}function WI(e,t,n){if(!x(e))return t;let r=n.filter(s=>{let a=e[s];return Array.isArray(a)&&a.some(c=>Wt(c,Pi,x(c))===void 0)});if(r.length===0)return t;let o=x(t)?t:{},i=new Map(r.map(s=>[s,e[s].map(a=>Wt(a,Pi,!0))]));return D_(e,o,i)}var GI=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function KI(e){let t=Object.entries(Object(e)).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(Object.fromEntries(t))===GI}function YI(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:ha("output_format",{command:n.command,args:n.commandArgs,command_options:n.commandOptions,global:{...n},pm_root:n.pmRoot,format:r,options:{...n},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&Ur(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
36
+ `}var WI=new Set(["filters","now","projection","sorting"]);function GI(e){let t=Wt(e,{omitDuplicateCountAliases:!1,preserveRowFacts:!1});if(!x(t)||!Array.isArray(t.items))return t??null;let n=Object.fromEntries(Object.entries(t).filter(([r])=>!WI.has(r)));return n.has_more!==!0&&delete n.next_cursor,n}function KI(e,t){if(!x(e)||!Array.isArray(e.run_results)||!e.run_results.every(x))return e;let n=e.run_results,r=YI(n),o=n.map(i=>{let{execution_context:s,stdout:a,stderr:c,...d}=i;return r===void 0?i:!t||i.status!=="passed"?{...d,stdout:a,stderr:c}:d});return t&&XI(e,r,n)?JI(e,r,o):{...e,...r===void 0?{}:{execution_context:r},run_results:o}}function YI(e){let t=e.map(r=>r.execution_context).filter(r=>r!==void 0);if(t.length!==e.length||t.length===0)return;let n=JSON.stringify(t[0]);return t.every(r=>JSON.stringify(r)===n)?t[0]:void 0}function XI(e,t,n){if(e.ok!==!0||!x(t)||t.mismatch_detected!==!1||!n.every(o=>o.status==="passed"))return!1;let r=e.failure_categories;return!(x(r)&&Object.values(r).some(o=>o!==0))}function JI(e,t,n){let{failure_categories:r,...o}=e,i=x(t.trust)?t.trust:{};return{...o,execution_context:{pm_context_mode:t.pm_context_mode,workspace_context_mode:t.workspace_context_mode,mismatch_detected:!1,...typeof i.trusted=="boolean"?{trusted:i.trusted}:{},...i.reason===void 0?{}:{trust_reason:i.reason},restore_with:"not retained; a run without --lean reports the full context"},run_results:n}}function ZI(e){return!x(e)||e.ok!==!0||!x(e.verdict)||e.verdict.authority!=="ok"||!Array.isArray(e.checks)?e:{...e,checks:e.checks.map(QI)}}function QI(e){if(!x(e)||e.ok!==!0||!x(e.details)||Object.keys(e.details).length!==0)return e;let{details:t,...n}=e;return n}function Pi(e,t,n=!1,r={}){if(e=Wc(e),t==="json"){let i=n?GI(e):e,s=x(e)&&x(e.projection)&&e.projection.mode==="brief"&&Array.isArray(e.items);return`${JSON.stringify(i,null,s?void 0:2)}
37
+ `}let o=tT(e,eT(e,Wt(ZI(R_(T_(e))),Mi),r.preserveEmptyItemCollections===!0),r.positionalRowPaths??[]);return o===void 0?`{}
38
+ `:`${j_(o,0)}
39
+ `}var Mi={omitDuplicateCountAliases:!0,preserveRowFacts:!0};function Qc(e,t,n=!1){if(Array.isArray(e)){if(e.length===0)return[];let i=Array.isArray(t)?t:[],s=i.length===e.length,a=0,c=e.flatMap(d=>{let l=n||x(d),u=!s&&Wt(d,Mi,l)===void 0,f=Qc(d,u?void 0:i[a++],l);return f===void 0?[]:[f]});return c.length>0?c:t}if(!x(e))return t;let r=x(t)?t:{},o=Object.entries(e).flatMap(([i,s])=>{let a=Qc(s,Object.hasOwn(r,i)?r[i]:void 0,n);return a===void 0?[]:[[i,a]]});return o.length>0||Object.keys(e).length===0?Object.fromEntries(o):t}function eT(e,t,n){if(!n||!x(e))return t;let r=x(t)?t:{},o=new Map(Object.keys(e).filter(i=>i==="item"||E_.has(i)).map(i=>[i,Qc(e[i],r[i])]));return L_(e,r,o)}function L_(e,t,n){let r=Object.entries(t).map(([i,s])=>[i,n.has(i)?n.get(i):s]),o=Object.keys(e);for(let[i,s]of n){if(Object.hasOwn(t,i)||s===void 0)continue;let a=new Set(o.slice(o.indexOf(i)+1)),c=r.findIndex(([d])=>a.has(d));r.splice(c===-1?r.length:c,0,[i,s])}return Object.fromEntries(r)}function tT(e,t,n){if(!x(e))return t;let r=n.filter(s=>{let a=e[s];return Array.isArray(a)&&a.some(c=>Wt(c,Mi,x(c))===void 0)});if(r.length===0)return t;let o=x(t)?t:{},i=new Map(r.map(s=>[s,e[s].map(a=>Wt(a,Mi,!0))]));return L_(e,o,i)}var nT=JSON.stringify({has_omissions:!1,omitted_field_group_count:0,omitted_field_groups:[]});function rT(e){let t=Object.entries(Object(e)).sort(([n],[r])=>n.localeCompare(r));return JSON.stringify(Object.fromEntries(t))===nT}function oT(e,t,n,r){let o=t?{handled:!1,result:e,warnings:[]}:va("output_format",{command:n.command,args:n.commandArgs,command_options:n.commandOptions,global:{...n},pm_root:n.pmRoot,format:r,options:{...n},result:e}),i=o.warnings.find(s=>s.startsWith("extension_output_format_payload_echo_deprecated:"));return i!==void 0&&zr(`Warning: ${i}. Returning context.payload now declines safely for compatibility; migrate the override to declineServiceOverride() or { handled: false }.
40
40
  `),o.handled&&typeof o.result=="string"?{result:o.result,rendered:o.result.endsWith(`
41
41
  `)?o.result:`${o.result}
42
- `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||x(o.result)}}function XI(e,t,n,r){let o=df(),i=n.command??o?.command,s={...o?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(y=>y[1]!==void 0))},a=$p(i??"",s)??r,c={...s,resolvedOutputFormat:a},d={...n,command:i,commandOptions:c},l=YI(e,t,d,a),u=JI(a,i,c,n.lean===!0);if(l.rendered!==null)return QI(l.rendered,{format:a,renderNative:u,contract:()=>Lc(i,c,e),effectiveResult:e,quiet:n.quiet===!0});let f=l.result;Ht(e,f);let m=i==="test"?FI(f,n.lean===!0):f,_=!1;return ZI({format:a,contract:()=>Lc(i,c,m),renderDelivered:y=>{if(a==="toon"){let v=jI(y);if(v!==null)return{text:v,custom:!1}}let b=t||_||Ne(y)?{rendered:null}:uf(a,y);return b.rendered!==null?{text:b.rendered.endsWith(`
42
+ `,structuredDeliveryPreserved:!1}:{result:o.handled?o.result:e,rendered:null,structuredDeliveryPreserved:!o.handled||x(o.result)}}function iT(e,t,n,r){let o=pf(),i=n.command??o?.command,s={...o?.options,...n.commandOptions,...Object.fromEntries([["outputInclude",n.outputInclude],["outputLimit",n.outputLimit],["outputBudget",n.outputBudget],["outputFormat",n.outputFormat],["outputSession",n.outputSession],["outputCursor",n.outputCursor],["outputRowContract",n.outputRowContract]].filter(y=>y[1]!==void 0))},a=Hp(i??"",s)??r,c={...s,resolvedOutputFormat:a},d={...n,command:i,commandOptions:c},l=oT(e,t,d,a),u=sT(a,i,c,n.lean===!0);if(l.rendered!==null)return aT(l.rendered,{format:a,renderNative:u,contract:()=>Hc(i,c,e),effectiveResult:e,quiet:n.quiet===!0});let f=l.result;Ht(e,f);let m=i==="test"?KI(f,n.lean===!0):f,_=!1;return cT({format:a,contract:()=>Hc(i,c,m),renderDelivered:y=>{if(a==="toon"){let v=BI(y);if(v!==null)return{text:v,custom:!1}}let b=t||_||Ne(y)?{rendered:null}:yf(a,y);return b.rendered!==null?{text:b.rendered.endsWith(`
43
43
  `)?b.rendered:`${b.rendered}
44
- `,custom:!0}:{text:u(y),custom:!1}},renderNative:u,useNativeRendering:()=>{_=!0},structuredDeliveryPreserved:l.structuredDeliveryPreserved,tokenAccounting:n.tokenAccounting===!0,quiet:n.quiet===!0,effectiveResult:e})}function JI(e,t,n,r){if(e==="json")return a=>Di(a,"json",r);let o=n.fields,i=t==="get"&&typeof o=="string"&&o.trim().length>0,s=y_(t===void 0?void 0:at(t,n));return a=>Di(a,"toon",!1,{preserveEmptyItemCollections:i,positionalRowPaths:s})}function QI(e,t){let n=Ni(t.format,r=>Ne(r)?t.renderNative(r):e,t.contract);return Ne(n)?(process.exitCode||=h.USAGE,Bc(n,t.effectiveResult,!t.quiet),t.renderNative(n)):(Xc(t.effectiveResult),e)}function ZI(e){let t=Ni(e.format,a=>e.renderDelivered(a).text,e.contract),n=e.renderDelivered(t);n.custom&&tT(t,n.text)&&(e.useNativeRendering(),t=Ni(e.format,e.renderNative,e.contract),n={text:e.renderNative(t),custom:!1}),Ne(t)&&(process.exitCode||=h.USAGE);let r=e.structuredDeliveryPreserved&&!n.custom;if(!e.tokenAccounting)return Bc(t,e.effectiveResult,!e.quiet&&r),n.text;let o=a=>{let c=e.renderDelivered(a);return c.custom&&(r=!1),c.text},i=p_(t,o),s=o(i);return Bc(i,e.effectiveResult,!e.quiet&&r),s}var eT=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function tT(e,t){let n=Math.ceil(Buffer.byteLength(t,"utf8")/4),r=Object(e);return eT.some(([o,i])=>{let s=r[o],a=x(s)?s[i]:void 0;return typeof a=="number"&&a<n})}function nT(e,t){let n=lf(e),r=Ao(n.result)?n.result:null,o=n.result,i=x(o)&&o[Vc]===!0,s=r?r.result:TI(n.result);if(Uo(s),r)return Xc(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return XI(s,i,t,a)}function XF(e,t){x(e)&&Number.isInteger(e.exit_code)&&AI.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?Rr(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?Rr(e,{changedFields:"compact"}):Rr(e,{compactEnvelope:!0}),r=nT(n,t);t.quiet||NI(r)}function JF(e){let t=ha("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;Ur(n.endsWith(`
44
+ `,custom:!0}:{text:u(y),custom:!1}},renderNative:u,useNativeRendering:()=>{_=!0},structuredDeliveryPreserved:l.structuredDeliveryPreserved,tokenAccounting:n.tokenAccounting===!0,quiet:n.quiet===!0,effectiveResult:e})}function sT(e,t,n,r){if(e==="json")return a=>Pi(a,"json",r);let o=n.fields,i=t==="get"&&typeof o=="string"&&o.trim().length>0,s=v_(t===void 0?void 0:at(t,n));return a=>Pi(a,"toon",!1,{preserveEmptyItemCollections:i,positionalRowPaths:s})}function aT(e,t){let n=Di(t.format,r=>Ne(r)?t.renderNative(r):e,t.contract);return Ne(n)?(process.exitCode||=h.USAGE,Yc(n,t.effectiveResult,!t.quiet),t.renderNative(n)):(ed(t.effectiveResult),e)}function cT(e){let t=Di(e.format,a=>e.renderDelivered(a).text,e.contract),n=e.renderDelivered(t);n.custom&&lT(t,n.text)&&(e.useNativeRendering(),t=Di(e.format,e.renderNative,e.contract),n={text:e.renderNative(t),custom:!1}),Ne(t)&&(process.exitCode||=h.USAGE);let r=e.structuredDeliveryPreserved&&!n.custom;if(!e.tokenAccounting)return Yc(t,e.effectiveResult,!e.quiet&&r),n.text;let o=a=>{let c=e.renderDelivered(a);return c.custom&&(r=!1),c.text},i=b_(t,o),s=o(i);return Yc(i,e.effectiveResult,!e.quiet&&r),s}var dT=[["read_output","estimated_tokens"],["context_intent","estimated_tokens"],["read_session","spent_this_call_tokens"]];function lT(e,t){let n=Math.ceil(Buffer.byteLength(t,"utf8")/4),r=Object(e);return dT.some(([o,i])=>{let s=r[o],a=x(s)?s[i]:void 0;return typeof a=="number"&&a<n})}function uT(e,t){let n=_f(e),r=Io(n.result)?n.result:null,o=n.result,i=x(o)&&o[Kc]===!0,s=r?r.result:jI(n.result);if(zo(s),r)return ed(s),"";let a=t.json===!0||t.json===void 0&&t.defaultOutputFormat==="json"?"json":"toon";return iT(s,i,t,a)}function fU(e,t){x(e)&&Number.isInteger(e.exit_code)&&MI.has(Number(e.exit_code))&&(process.exitCode===void 0||process.exitCode===h.SUCCESS)&&(process.exitCode=Number(e.exit_code));let n=t.idOnly?xr(e,{idOnly:!0}):t.fullChangedFields?e:t.noChangedFields?xr(e,{changedFields:"compact"}):xr(e,{compactEnvelope:!0}),r=uT(n,t);t.quiet||zI(r)}function mU(e){let t=va("error_format",{message:e}),n=t.handled&&typeof t.result=="string"?t.result:e;zr(n.endsWith(`
45
45
  `)?n:`${n}
46
- `)}(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]="cc4233e3-6eda-535f-a31b-e4c7b2d29404")}catch{}})();var $c=8,rT=64,oT=5,iT=4,P_=100;function vp(e,t,n){if(e!=="get"||!Jc(n.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(c=>t[c]!==void 0)||t.full===!0||t.tree===!0||t.depth!==void 0&&t.depth!=="standard")return;let r=n.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(n,c)),s=Object.fromEntries(Object.entries(n).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(r).filter(([c])=>c!=="body")),Object.hasOwn(r,"body")&&i.push("body");let a=[...Jc(n.omission_receipt)&&Array.isArray(n.omission_receipt.omitted_field_groups)?n.omission_receipt.omitted_field_groups:[],...i.map(c=>({name:c,restore_with:`--fields ${c}`}))];return s.omission_receipt={has_omissions:a.length>0,omitted_field_group_count:a.length,omitted_field_groups:a},s}function Dr(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*oT/iT),i=Math.ceil(o/P_)*P_;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function Nn(e,t,n=!1){let r=Object.getOwnPropertyDescriptor(e,"row_contract");r&&(n||r.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...r,enumerable:!1})}function Pn(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}var lt;function Ni(e,t,n){let r=lt;lt={format:e,render:t};try{return n()}finally{lt=r}}function it(e,t){let n=t===void 0?JSON.stringify(e):lt!==void 0&&lt.format===t?sT(lt,e):Di(e,t);return Math.ceil(Buffer.byteLength(n,"utf8")/4)}function sT(e,t){lt=void 0;try{return e.render(t)}finally{lt=e}}function Jc(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Qc(e,t,n=!1){return typeof e=="string"?n||e.length<=240?e:(t.compacted=!0,`${Ee(e,240)}\u2026`):Array.isArray(e)?e.map(r=>Qc(r,t,n)):Jc(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,Qc(o,t,n||r==="focus_row_states")])):e}function st(e,t,n){let r=t.estimated_tokens;for(let o=0;o<$c;o+=1){t.estimated_tokens=r;let i=it(e,n);if(i===r)return;r=i}t.estimated_tokens=r}function aT(e,t){return Ir(e).filter(n=>(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length)>Math.max(1,t.get(n.path)??0)).map(n=>({collection:n,length:Array.isArray(n.value)?n.value.length:Object.keys(n.value).length})).sort((n,r)=>r.length-n.length||n.collection.path.localeCompare(r.collection.path))[0]?.collection}function cT(e,t,n,r,o,i,s){for(let a=0;a<rT;a+=1){if(i?.(e),st(e,t,o),t.estimated_tokens<=n)return;let c=aT(e,r);if(!c)return;let d=Math.max(1,r.get(c.path)??0),l=Array.isArray(c.value)?[...c.value]:Object.entries(c.value),u=s(c.path),f=b=>{let v=u?l.length-b:0;if(Array.isArray(c.value)){c.value.length=b;for(let T=0;T<b;T+=1)c.value[T]=l[v+T]}else{for(let T of Object.keys(c.value))delete c.value[T];Object.defineProperties(c.value,Object.getOwnPropertyDescriptors(Object.fromEntries(l.slice(v,v+b))))}typeof e.count=="number"&&(e.count=Rn(e)),typeof e.returned_count=="number"&&(e.returned_count=Rn(e)),c.path==="items"&&(e.applied_limit=b),i?.(e),st(e,t,o)};t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],c.path])].sort((b,v)=>b.localeCompare(v)),e.has_more=!0,e.truncated=!0;let m=d,_=l.length-1,y=d;for(;m<=_;){let b=Math.floor((m+_)/2);f(b),t.estimated_tokens<=n?(y=b,m=b+1):_=b-1}f(y)}}function Ep(e,t,n,r=new Map,o,i,s=!1,a=()=>!1){let c={compacted:!1},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,Qc(u,c,s&&l==="diff")]));return Nn(e,d),t.strings_compacted=c.compacted,d.read_output=t,cT(d,t,n,r,o,i,a),st(d,t,o),d}import gy from"fast-json-patch";import py from"node:fs/promises";import XT from"node:path";import $ from"node:fs/promises";import z from"node:path";import{createHash as Hi,randomUUID as ad}from"node:crypto";import{createRequire as vT}from"node:module";import{setImmediate as B_}from"node:timers/promises";import td from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();var dT={metadata:{},body:""};function ji(){return structuredClone(dT)}function uU(e,t=Gt,n){return Zc(e,t,n)[0]}function Zc(e,t,n){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return L_($i(e),t,n)}catch{}let r=Je(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),n);return t===2?[r,r]:[r]}function F_(e,t,n,r,o){let i=Tt(r.hash_algorithm),s=`${n}:${i}`,a=o?.before.get(s)??Zc(e,n,i),c=Zc(t,n,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===r.before_hash&&c[l]===r.after_hash),beforeIndex:a.indexOf(r.before_hash),afterIndex:c.indexOf(r.after_hash)}}function $i(e){return{metadata:e.metadata,body:e.body}}function fU(e,t={}){return Sn($i(e),t)}function mU(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=Sn(e);return{metadata:A(t.metadata,Ve),body:t.body}}function M_(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function lT(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function U_(e){return Array.isArray(e)?e.filter(lT).map(t=>({...t,path:M_(t.path),from:typeof t.from=="string"?M_(t.from):void 0})):[]}function uT(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function Li(e,t){try{let n=U_(t),r=td.applyPatch(structuredClone(e),n,!0,!0).newDocument;return uT(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function fT(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&zr.includes(t)))]}function z_(e){return e!==void 0&&!zr.includes(e)}function mT(e,t){return e!==void 0?[e]:t===void 0?[...zr]:[t]}function H_(e){let t=Mi(e);if(!t.ok)return t.error;let n=ed(e);return n.ok?void 0:n.error}function pT(e,t){let n=H_(e);if(n)return{ok:!1,error:n};let r=Li(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function _T(e,t){let n=H_(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function yT(e,t,n,r,o){let i=[];for(let s of n){let a=F_(e,t,s,r,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Fi(e){let t=ji(),n=new Map,r,o,i=pf(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`);for(let s=0;s<e.length;s+=1){let a=e[s],c=a.item_hash_version,d=z_(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=pT(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,n=new Map,r=void 0,o=void 0;continue}let u=mT(c,o),f={before:n,after:new Map},m=yT(t,l.document,u,a,f),_=m.find(({match:b})=>b.pairIndex>=0);if(_===void 0){let b=m.some(({match:v})=>v.beforeIndex>=0);return{ok:!1,errors:[...i,`verify_failed:${b?"after":"before"}_hash_mismatch:entry_${s+1}`]}}let y=_.version;t=l.document,n=f.after,r=y,o=c??o}return i.length>0?{ok:!1,errors:i,...r===void 0?{}:{item_hash_version:r}}:{ok:!0,errors:[],...r===void 0?{}:{item_hash_version:r}}}function Kt(e){let t=Fi(e);return{ok:t.ok,errors:t.errors}}function j_(e,t){try{return{ok:!0,document:td.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function hT(e,t){let n=structuredClone(e),r=0,o=0;for(let s of U_(t)){let a=j_(n,s);if(a.ok){n=a.document;continue}if(s.op==="replace"){let c=j_(n,{...s,op:"add"});if(c.ok){n=c.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function gT(e){let t=fT(e);if(t.length===1)return t[0];let n=Fi(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Gt}function bT(e,t,n=t.patch){let r=Li(e,n);if(r.ok)return{next:r.document,patch:n,repaired:R(n)!==R(t.patch),converted:0,skipped:0};let o=hT(e,n);return{next:o.document,patch:td.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function wT(e,t,n){return bT(e,t,n.projectPatch?.(t,e))}function pU(e,t=gT(e),n={}){let r=e.findIndex(m=>z_(m.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=ji(),i=[],s=[],a=0,c=0,d=0,l=0,u,f=t!==1||e.some(m=>m.item_hash_version!==void 0);for(let m=0;m<e.length;m+=1){let _=e[m];_T(_,m);let y=wT(o,_,n),{next:b,patch:v,repaired:T,converted:G,skipped:ce}=y;d+=G,l+=ce,c+=Number(T);let de=F_(o,b,t,_);u===void 0||n.continuousHashSurface!==!0?u=[de.pairIndex,de.beforeIndex,de.afterIndex,Math.min(u??0,de.beforeHashes.length-1)].find(gh=>gh>=0):u=Math.min(u,de.beforeHashes.length-1);let Ud=de.beforeHashes[u],zd=de.afterHashes[u],ms=Ud!==_.before_hash||zd!==_.after_hash;ms&&(a+=1);let rn={..._,patch:v,before_hash:Ud,after_hash:zd};f?rn.item_hash_version=t:delete rn.item_hash_version;let hh=rn.item_hash_version!==_.item_hash_version;(ms||T||hh)&&(rn=$_(_,rn,{retainOriginalPatch:T})),i.push(rn),s.push({index:m+1,rehashed:ms,patch_repaired:T,converted_replace_to_add:G,skipped_ops:ce}),o=b}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function _U(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
46
+ `)}(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]="cc4233e3-6eda-535f-a31b-e4c7b2d29404")}catch{}})();var zc=8,fT=64,mT=5,pT=4,F_=100;function Ap(e,t,n){if(e!=="get"||!td(n.item)||["fields","outputInclude","output_include","outputCursor","output_cursor"].some(c=>t[c]!==void 0)||t.full===!0||t.tree===!0||t.depth!==void 0&&t.depth!=="standard")return;let r=n.item,o=["linked","claim_state","schedule"],i=o.filter(c=>Object.hasOwn(n,c)),s=Object.fromEntries(Object.entries(n).filter(([c])=>!o.includes(c)));s.item=Object.fromEntries(Object.entries(r).filter(([c])=>c!=="body")),Object.hasOwn(r,"body")&&i.push("body");let a=[...td(n.omission_receipt)&&Array.isArray(n.omission_receipt.omitted_field_groups)?n.omission_receipt.omitted_field_groups:[],...i.map(c=>({name:c,restore_with:`--fields ${c}`}))];return s.omission_receipt={has_omissions:a.length>0,omitted_field_group_count:a.length,omitted_field_groups:a},s}function Pr(e){let t=Math.trunc(e.effective_budget_tokens),n=Math.trunc(e.measured_result_tokens);if(!Number.isSafeInteger(t)||t<=0||!Number.isSafeInteger(n)||n<=0)return{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"};let r=Math.max(t+1,n),o=Math.ceil(r*mT/pT),i=Math.ceil(o/F_)*F_;return Number.isSafeInteger(i)?{output_budget:i,recovery_budget_multiplier:i/t,rule_version:"v1"}:{output_budget:"unbounded",recovery_budget_multiplier:null,rule_version:"v1"}}function Dn(e,t,n=!1){let r=Object.getOwnPropertyDescriptor(e,"row_contract");r&&(n||r.enumerable===!1)&&Object.defineProperty(t,"row_contract",{...r,enumerable:!1})}function Mn(e){let t=e.resolvedOutputFormat??e.outputFormat??e.output_format??e.format;return t==="json"||t==="toon"?t:void 0}var lt;function Di(e,t,n){let r=lt;lt={format:e,render:t};try{return n()}finally{lt=r}}function it(e,t){let n=t===void 0?JSON.stringify(e):lt!==void 0&&lt.format===t?_T(lt,e):Pi(e,t);return Math.ceil(Buffer.byteLength(n,"utf8")/4)}function _T(e,t){lt=void 0;try{return e.render(t)}finally{lt=e}}function td(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function nd(e,t,n=!1){return typeof e=="string"?n||e.length<=240?e:(t.compacted=!0,`${Ee(e,240)}\u2026`):Array.isArray(e)?e.map(r=>nd(r,t,n)):td(e)?Object.fromEntries(Object.entries(e).map(([r,o])=>[r,nd(o,t,n||r==="focus_row_states")])):e}function st(e,t,n){let r=t.estimated_tokens;for(let o=0;o<zc;o+=1){t.estimated_tokens=r;let i=it(e,n);if(i===r)return;r=i}t.estimated_tokens=r}function yT(e,t){return Tr(e).filter(n=>(Array.isArray(n.value)?n.value.length:Object.keys(n.value).length)>Math.max(1,t.get(n.path)??0)).map(n=>({collection:n,length:Array.isArray(n.value)?n.value.length:Object.keys(n.value).length})).sort((n,r)=>r.length-n.length||n.collection.path.localeCompare(r.collection.path))[0]?.collection}function hT(e,t,n,r,o,i,s){for(let a=0;a<fT;a+=1){if(i?.(e),st(e,t,o),t.estimated_tokens<=n)return;let c=yT(e,r);if(!c)return;let d=Math.max(1,r.get(c.path)??0),l=Array.isArray(c.value)?[...c.value]:Object.entries(c.value),u=s(c.path),f=b=>{let v=u?l.length-b:0;if(Array.isArray(c.value)){c.value.length=b;for(let T=0;T<b;T+=1)c.value[T]=l[v+T]}else{for(let T of Object.keys(c.value))delete c.value[T];Object.defineProperties(c.value,Object.getOwnPropertyDescriptors(Object.fromEntries(l.slice(v,v+b))))}typeof e.count=="number"&&(e.count=xn(e)),typeof e.returned_count=="number"&&(e.returned_count=xn(e)),c.path==="items"&&(e.applied_limit=b),i?.(e),st(e,t,o)};t.rows_compacted=!0,t.compacted_row_paths=[...new Set([...t.compacted_row_paths??[],c.path])].sort((b,v)=>b.localeCompare(v)),e.has_more=!0,e.truncated=!0;let m=d,_=l.length-1,y=d;for(;m<=_;){let b=Math.floor((m+_)/2);f(b),t.estimated_tokens<=n?(y=b,m=b+1):_=b-1}f(y)}}function Ip(e,t,n,r=new Map,o,i,s=!1,a=()=>!1){let c={compacted:!1},d=Object.fromEntries(Object.entries(e).map(([l,u])=>[l,nd(u,c,s&&l==="diff")]));return Dn(e,d),t.strings_compacted=c.compacted,d.read_output=t,hT(d,t,n,r,o,i,a),st(d,t,o),d}import ky from"fast-json-patch";import by from"node:fs/promises";import iC from"node:path";import j from"node:fs/promises";import z from"node:path";import{createHash as qi,randomUUID as ud}from"node:crypto";import{createRequire as RT}from"node:module";import{setImmediate as X_}from"node:timers/promises";import id from"fast-json-patch";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="0c0cb8c7-4d7d-53f8-8ec2-d6dc98fc6dc5")}catch{}})();var gT={metadata:{},body:""};function ji(){return structuredClone(gT)}function IU(e,t=Gt,n){return rd(e,t,n)[0]}function rd(e,t,n){if(Object.keys(e.metadata).length===0||Array.isArray(e.metadata.tags))try{return q_(Li(e),t,n)}catch{}let r=Je(R({replay_fallback:!0,metadata:e.metadata,body:e.body}),n);return t===2?[r,r]:[r]}function V_(e,t,n,r,o){let i=Tt(r.hash_algorithm),s=`${n}:${i}`,a=o?.before.get(s)??rd(e,n,i),c=rd(t,n,i);return o?.after.set(s,c),{beforeHashes:a,afterHashes:c,pairIndex:a.findIndex((d,l)=>d===r.before_hash&&c[l]===r.after_hash),beforeIndex:a.indexOf(r.before_hash),afterIndex:c.indexOf(r.after_hash)}}function Li(e){return{metadata:e.metadata,body:e.body}}function TU(e,t={}){return On(Li(e),t)}function CU(e){if(!e.metadata||Object.keys(e.metadata).length===0)return{metadata:{},body:e.body??""};let t=On(e);return{metadata:A(t.metadata,Ve),body:t.body}}function U_(e){return e==="/front_matter"?"/metadata":e.startsWith("/front_matter/")?`/metadata/${e.slice(14)}`:e}function bT(e){return typeof e=="object"&&e!==null&&typeof e.op=="string"&&typeof e.path=="string"}function B_(e){return Array.isArray(e)?e.filter(bT).map(t=>({...t,path:U_(t.path),from:typeof t.from=="string"?U_(t.from):void 0})):[]}function wT(e){return typeof e=="object"&&e!==null&&"metadata"in e&&"body"in e&&typeof e.body=="string"&&typeof e.metadata=="object"&&e.metadata!==null}function Fi(e,t){try{let n=B_(t),r=id.applyPatch(structuredClone(e),n,!0,!0).newDocument;return wT(r)?{ok:!0,document:{metadata:r.metadata,body:r.body}}:{ok:!1,error:new Error("history_replay_invalid_document_shape")}}catch(n){return{ok:!1,error:n}}}function vT(e){return[...new Set(e.map(t=>t.item_hash_version).filter(t=>t!==void 0&&Hr.includes(t)))]}function W_(e){return e!==void 0&&!Hr.includes(e)}function ET(e,t){return e!==void 0?[e]:t===void 0?[...Hr]:[t]}function G_(e){let t=$i(e);if(!t.ok)return t.error;let n=od(e);return n.ok?void 0:n.error}function kT(e,t){let n=G_(e);if(n)return{ok:!1,error:n};let r=Fi(t,e.patch);return r.ok?{ok:!0,document:r.document}:{ok:!1,error:"patch_apply_failed"}}function ST(e,t){let n=G_(e);if(n)throw new TypeError(`${n}:entry_${t+1}`)}function OT(e,t,n,r,o){let i=[];for(let s of n){let a=V_(e,t,s,r,o);if(i.push({version:s,match:a}),a.pairIndex>=0)break}return i}function Ui(e){let t=ji(),n=new Map,r,o,i=bf(e).map(s=>`verify_failed:duplicate_create:entry_${s.repeated_create_index}:prior_${s.prior_genesis_index}`);for(let s=0;s<e.length;s+=1){let a=e[s],c=a.item_hash_version,d=W_(c);d&&i.push(`verify_failed:unsupported_item_hash_version:${String(c)}:entry_${s+1}`);let l=kT(a,t);if(!l.ok)return{ok:!1,errors:[...i,`verify_failed:${l.error}:entry_${s+1}`]};if(d){t=l.document,n=new Map,r=void 0,o=void 0;continue}let u=ET(c,o),f={before:n,after:new Map},m=OT(t,l.document,u,a,f),_=m.find(({match:b})=>b.pairIndex>=0);if(_===void 0){let b=m.some(({match:v})=>v.beforeIndex>=0);return{ok:!1,errors:[...i,`verify_failed:${b?"after":"before"}_hash_mismatch:entry_${s+1}`]}}let y=_.version;t=l.document,n=f.after,r=y,o=c??o}return i.length>0?{ok:!1,errors:i,...r===void 0?{}:{item_hash_version:r}}:{ok:!0,errors:[],...r===void 0?{}:{item_hash_version:r}}}function Kt(e){let t=Ui(e);return{ok:t.ok,errors:t.errors}}function z_(e,t){try{return{ok:!0,document:id.applyPatch(structuredClone(e),[t],!0,!1).newDocument}}catch{return{ok:!1}}}function AT(e,t){let n=structuredClone(e),r=0,o=0;for(let s of B_(t)){let a=z_(n,s);if(a.ok){n=a.document;continue}if(s.op==="replace"){let c=z_(n,{...s,op:"add"});if(c.ok){n=c.document,r+=1;continue}}o+=1}let i=n;return{document:{metadata:typeof i.metadata=="object"&&i.metadata!==null?i.metadata:{},body:typeof i.body=="string"?i.body:e.body},convertedReplaceToAdd:r,skippedOps:o}}function IT(e){let t=vT(e);if(t.length===1)return t[0];let n=Ui(e);return n.ok&&n.item_hash_version!==void 0?n.item_hash_version:t.length===0?1:Gt}function TT(e,t,n=t.patch){let r=Fi(e,n);if(r.ok)return{next:r.document,patch:n,repaired:R(n)!==R(t.patch),converted:0,skipped:0};let o=AT(e,n);return{next:o.document,patch:id.compare(e,o.document),repaired:!0,converted:o.convertedReplaceToAdd,skipped:o.skippedOps}}function CT(e,t,n){return TT(e,t,n.projectPatch?.(t,e))}function RU(e,t=IT(e),n={}){let r=e.findIndex(m=>W_(m.item_hash_version));if(r>=0)throw new TypeError(`unsupported_item_hash_version:${String(e[r]?.item_hash_version)}:entry_${r+1}`);let o=ji(),i=[],s=[],a=0,c=0,d=0,l=0,u,f=t!==1||e.some(m=>m.item_hash_version!==void 0);for(let m=0;m<e.length;m+=1){let _=e[m];ST(_,m);let y=CT(o,_,n),{next:b,patch:v,repaired:T,converted:G,skipped:ce}=y;d+=G,l+=ce,c+=Number(T);let de=V_(o,b,t,_);u===void 0||n.continuousHashSurface!==!0?u=[de.pairIndex,de.beforeIndex,de.afterIndex,Math.min(u??0,de.beforeHashes.length-1)].find(kh=>kh>=0):u=Math.min(u,de.beforeHashes.length-1);let Vd=de.beforeHashes[u],Bd=de.afterHashes[u],ps=Vd!==_.before_hash||Bd!==_.after_hash;ps&&(a+=1);let rn={..._,patch:v,before_hash:Vd,after_hash:Bd};f?rn.item_hash_version=t:delete rn.item_hash_version;let Eh=rn.item_hash_version!==_.item_hash_version;(ps||T||Eh)&&(rn=H_(_,rn,{retainOriginalPatch:T})),i.push(rn),s.push({index:m+1,rehashed:ps,patch_repaired:T,converted_replace_to_add:G,skipped_ops:ce}),o=b}return{entries:i,finalDocument:o,entriesRehashed:a,entriesPatchRepaired:c,convertedReplaceToAdd:d,skippedOps:l,details:s,itemHashVersion:t,explicitItemHashVersion:f}}function xU(e){return e.length===0?"":`${e.map(t=>JSON.stringify(t)).join(`
47
47
  `)}
48
- `}(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]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function q_(e){let t=process.emitWarning;process.emitWarning=(n,...r)=>{n==="SQLite is an experimental feature and might change at any time"&&r[0]==="ExperimentalWarning"||Reflect.apply(t,process,[n,...r])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function V_(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?q_(t):null}(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]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();var ET="history-event-index.sqlite",cd="7",kT=8,W_=32,Z_="history-event-index",ST="history-event-index:append:",OT=5e3,dd=300,ey=3e4,AT="history-event-index-invalidation",IT="history-event-index-invalidations",TT=dd*2*1e3,ut=Symbol("history-index-changed"),Yt=new Map;function Jt(e){return z.join(e,"runtime",ET)}function ty(e){return z.join(e,"runtime","history-event-index-repair-deferred")}async function ny(e){try{let t=Number(await $.readFile(ty(e),"utf8")),n=Date.now()-t;return n>=0&&n<OT}catch{return!1}}async function G_(e){try{await $.writeFile(ty(e),`${Date.now()}
49
- `)}catch{}}function Hr(e){return z.join(e,"runtime",IT)}async function qi(e){let t=await $.readdir(Hr(e)).catch(n=>{if(Z(n))return[];throw n});return{pending:t.filter(n=>n.endsWith(".pending")).sort(),committed:t.filter(n=>n.endsWith(".committed")).sort()}}async function K_(e){let t=await qi(e);return{pending:(await Promise.all(t.pending.map(async n=>{let r=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(n);if(r!==null){let o=r[2];if(await Ar({pid:Number(r[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(r[3])),TT))return n}return await $.rm(z.join(Hr(e),n),{force:!0}),null}))).filter(n=>n!==null),committed:t.committed}}async function id(e,t,n=ey){let r=await fe(e,AT,dd,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await r()}}async function CT(e){let t=Hr(e);await $.mkdir(t,{recursive:!0});let n=ad(),r=await Or(),o=z.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await $.writeFile(o,`pending
50
- `,{flag:"wx"}),{pendingPath:o,committedPath:z.join(t,`${n}.committed`)}}function RT(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}async function Vi(e){try{await $.rm(Jt(e),{force:!0})}catch{}}async function nd(e,t){let n=Hr(e);await $.mkdir(n,{recursive:!0}),await $.writeFile(z.join(n,`${ad()}${t?".contended":""}.committed`),`committed
51
- `,{flag:"wx"}),t||await Vi(e)}function Bi(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function sd(e,t){let n;try{return n=new t(Jt(e)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return Xt(r)}finally{n?.close()}}async function Y_(e,t){return t.pending.length>0||await gm(e,Z_,ST)}async function ry(e,t,n=ey,r="rebuild"){let o=await fe(e,Z_,dd,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function oy(e,t,n=!1){let r=z.join(e,"history"),o=await $.readdir(r,{withFileTypes:!0}).catch(u=>{if(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT")return[];throw u}),i=Yt.get(e)??{streams:new Map,ordered_events:[]},s=new Map(i.streams),a=i.ordered_events,c=new Set,d=!Yt.has(e);for(let u of o.filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).sort((f,m)=>f.name.localeCompare(m.name))){let f=u.name.slice(0,-6);c.add(f);let m=z.join(r,u.name);if(!rd(f,t))continue;let _=await NT(m,f,s.get(f),n);_!==void 0&&(s.set(f,_),d=!0)}for(let u of s.keys())c.has(u)||(s.delete(u),d=!0);d&&(a=[...s.values()].flatMap(u=>u.events).sort(ld));let l={streams:s,ordered_events:a};if(Yt.delete(e),Yt.set(e,l),Yt.size>kT){let u=Yt.keys().next().value;Yt.delete(u)}return{events:l.ordered_events.filter(u=>rd(u.stream_id,t)).map(u=>xT(u,n)),stream_receipts:new Map([...l.streams].filter(([u])=>rd(u,t)).map(([u,f])=>[u,{byte_size:f.byte_size,content_hash:f.signature}]))}}function xT(e,t){return t||e.recorded_entry===void 0?e:{stream_id:e.stream_id,stream_offset:e.stream_offset,entry:e.entry}}function rd(e,t){return!t?.length||t.includes(e)}async function NT(e,t,n,r){if(!r&&n!==void 0&&n.byte_size===(await $.stat(e)).size){let o=Hi("sha256").update(await $.readFile(e)).digest("hex");if(n.signature===o)return}return DT(e,t,r)}async function DT(e,t,n){let r=await pi(e,t);if(n){let i=Fi(r.entries);if(!i.ok)throw new g(`Authoritative history integrity verification failed for ${t}.`,h.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${t} --verify to inspect the authoritative chain before retrying.`]})}let o=r.raw_bytes??new Uint8Array;return{signature:Hi("sha256").update(o).digest("hex"),byte_size:o.byteLength,events:iy(r.entries,t).map((i,s)=>({stream_id:t,stream_offset:s,entry:i,...n?{recorded_entry:r.entries[s]}:{}}))}}async function PT(e,t){return iy((await pi(e,t)).entries,t)}function iy(e,t){for(let[n,r]of e.entries())if(typeof r.ts!="string"||!ln(r.ts.trim()))throw new g(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return e.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}var od;function Gi(){return od!==void 0||(od=V_(process.versions.node,vT(import.meta.url))),od}function MT(e){e.exec(`
48
+ `}(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]="812b558d-59f3-58d6-b04e-6a4f8689e866")}catch{}})();function K_(e){let t=process.emitWarning;process.emitWarning=(n,...r)=>{n==="SQLite is an experimental feature and might change at any time"&&r[0]==="ExperimentalWarning"||Reflect.apply(t,process,[n,...r])};try{return e(["node","sqlite"].join(":")).DatabaseSync??null}catch{return null}finally{process.emitWarning=t}}function Y_(e,t){let n=Number.parseInt(e,10);return Number.isFinite(n)&&n>=22?K_(t):null}(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]="c5f096f6-4af4-568e-89ef-1aa0a8718973")}catch{}})();var xT="history-event-index.sqlite",fd="7",NT=8,J_=32,oy="history-event-index",DT="history-event-index:append:",PT=5e3,md=300,iy=3e4,MT="history-event-index-invalidation",$T="history-event-index-invalidations",jT=md*2*1e3,ut=Symbol("history-index-changed"),Yt=new Map;function Jt(e){return z.join(e,"runtime",xT)}function sy(e){return z.join(e,"runtime","history-event-index-repair-deferred")}async function ay(e){try{let t=Number(await j.readFile(sy(e),"utf8")),n=Date.now()-t;return n>=0&&n<PT}catch{return!1}}async function Z_(e){try{await j.writeFile(sy(e),`${Date.now()}
49
+ `)}catch{}}function qr(e){return z.join(e,"runtime",$T)}async function Vi(e){let t=await j.readdir(qr(e)).catch(n=>{if(Q(n))return[];throw n});return{pending:t.filter(n=>n.endsWith(".pending")).sort(),committed:t.filter(n=>n.endsWith(".committed")).sort()}}async function Q_(e){let t=await Vi(e);return{pending:(await Promise.all(t.pending.map(async n=>{let r=/^(\d+)-(unknown|\d+)-(\d+)-.+\.pending$/u.exec(n);if(r!==null){let o=r[2];if(await Ir({pid:Number(r[1]),...o==="unknown"?{}:{process_start_identity:o}},Math.max(0,Date.now()-Number(r[3])),jT))return n}return await j.rm(z.join(qr(e),n),{force:!0}),null}))).filter(n=>n!==null),committed:t.committed}}async function dd(e,t,n=iy){let r=await fe(e,MT,md,`history-event-index-invalidation:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await r()}}async function LT(e){let t=qr(e);await j.mkdir(t,{recursive:!0});let n=ud(),r=await Ar(),o=z.join(t,`${r.pid}-${r.process_start_identity??"unknown"}-${Date.now()}-${n}.pending`);return await j.writeFile(o,`pending
50
+ `,{flag:"wx"}),{pendingPath:o,committedPath:z.join(t,`${n}.committed`)}}function FT(e,t){return e.length===t.length&&e.every((n,r)=>n===t[r])}async function Bi(e){try{await j.rm(Jt(e),{force:!0})}catch{}}async function sd(e,t){let n=qr(e);await j.mkdir(n,{recursive:!0}),await j.writeFile(z.join(n,`${ud()}${t?".contended":""}.committed`),`committed
51
+ `,{flag:"wx"}),t||await Bi(e)}function Wi(e){return e.committed.some(t=>t.endsWith(".contended.committed"))}function ld(e,t){let n;try{return n=new t(Jt(e)),n.exec("PRAGMA busy_timeout = 0"),n.exec("BEGIN EXCLUSIVE"),!1}catch(r){return Xt(r)}finally{n?.close()}}async function ey(e,t){return t.pending.length>0||await km(e,oy,DT)}async function cy(e,t,n=iy,r="rebuild"){let o=await fe(e,oy,md,`history-event-index:${r}:${process.pid}`,!1,!1,n,n===0?{maxWaitMs:0}:void 0);try{return await t()}finally{await o()}}async function dy(e,t,n=!1){let r=z.join(e,"history"),o=await j.readdir(r,{withFileTypes:!0}).catch(u=>{if(typeof u=="object"&&u!==null&&"code"in u&&u.code==="ENOENT")return[];throw u}),i=Yt.get(e)??{streams:new Map,ordered_events:[]},s=new Map(i.streams),a=i.ordered_events,c=new Set,d=!Yt.has(e);for(let u of o.filter(f=>f.isFile()&&f.name.endsWith(".jsonl")).sort((f,m)=>f.name.localeCompare(m.name))){let f=u.name.slice(0,-6);c.add(f);let m=z.join(r,u.name);if(!ad(f,t))continue;let _=await zT(m,f,s.get(f),n);_!==void 0&&(s.set(f,_),d=!0)}for(let u of s.keys())c.has(u)||(s.delete(u),d=!0);d&&(a=[...s.values()].flatMap(u=>u.events).sort(pd));let l={streams:s,ordered_events:a};if(Yt.delete(e),Yt.set(e,l),Yt.size>NT){let u=Yt.keys().next().value;Yt.delete(u)}return{events:l.ordered_events.filter(u=>ad(u.stream_id,t)).map(u=>UT(u,n)),stream_receipts:new Map([...l.streams].filter(([u])=>ad(u,t)).map(([u,f])=>[u,{byte_size:f.byte_size,content_hash:f.signature}]))}}function UT(e,t){return t||e.recorded_entry===void 0?e:{stream_id:e.stream_id,stream_offset:e.stream_offset,entry:e.entry}}function ad(e,t){return!t?.length||t.includes(e)}async function zT(e,t,n,r){if(!r&&n!==void 0&&n.byte_size===(await j.stat(e)).size){let o=qi("sha256").update(await j.readFile(e)).digest("hex");if(n.signature===o)return}return HT(e,t,r)}async function HT(e,t,n){let r=await _i(e,t);if(n){let i=Ui(r.entries);if(!i.ok)throw new g(`Authoritative history integrity verification failed for ${t}.`,h.GENERIC_FAILURE,{code:"event_history_integrity_failed",why:i.errors.join(", "),nextSteps:[`Run pm history ${t} --verify to inspect the authoritative chain before retrying.`]})}let o=r.raw_bytes??new Uint8Array;return{signature:qi("sha256").update(o).digest("hex"),byte_size:o.byteLength,events:ly(r.entries,t).map((i,s)=>({stream_id:t,stream_offset:s,entry:i,...n?{recorded_entry:r.entries[s]}:{}}))}}async function qT(e,t){return ly((await _i(e,t)).entries,t)}function ly(e,t){for(let[n,r]of e.entries())if(typeof r.ts!="string"||!un(r.ts.trim()))throw new g(`History for ${t} contains an invalid or sub-millisecond timestamp at line ${n+1}. Repair or restore the history stream and retry.`,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"});return e.map(n=>({...n,ts:new Date(n.ts.trim()).toISOString()}))}var cd;function Ki(){return cd!==void 0||(cd=Y_(process.versions.node,RT(import.meta.url))),cd}function VT(e){e.exec(`
52
52
  PRAGMA journal_mode = OFF;
53
53
  PRAGMA synchronous = OFF;
54
54
  CREATE TABLE metadata (
@@ -84,14 +84,14 @@ ${N_(t,n+1)}`}function MI(e,t,n){let r=e.map(o=>Wt(o,t,n||t.preserveRowFacts&&x(
84
84
  ON events(agent_harness, ts, stream_id, stream_offset);
85
85
  CREATE INDEX events_instance_order
86
86
  ON events(agent_instance, ts, stream_id, stream_offset);
87
- `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(cd)}function sy(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
87
+ `),e.prepare("INSERT INTO metadata(key, value) VALUES ('version', ?)").run(fd)}function uy(e,t){let n={...t.entry,ts:new Date(t.entry.ts.trim()).toISOString()};e.prepare(`INSERT INTO events(
88
88
  stream_id, stream_offset, ts, author, agent_harness,
89
89
  agent_instance, op, event_class, entry_json
90
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,Tn(n),JSON.stringify(n))}function ay(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!ln(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function cy(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
91
- ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(t,n.byte_size,n.content_hash)}async function jT(e,t={}){let n=Gi();return n?ry(e,async()=>{let r;try{r=await id(e,()=>K_(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(r.pending.length>0||Bi(r)&&sd(e,n))return!1;let o=Jt(e);await $.mkdir(z.dirname(o),{recursive:!0});let i=`${o}.${ad()}.tmp`,s;try{s=new n(i),MT(s),s.exec("BEGIN IMMEDIATE");let a=await oy(e);await $T(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await id(e,async()=>{let d=await K_(e);return d.pending.length>0||!RT(r.committed,d.committed)||Bi(d)&&sd(e,n)?!1:(await $.rm(o,{force:!0}),await $.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(r.committed.map(d=>$.rm(z.join(Hr(e),d),{force:!0}))),c||(await G_(e),await $.rm(i,{force:!0})),c}catch(a){throw await G_(e),s?.close(),await $.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function $T(e,t){let n=0;for(let r of t.events)sy(e,r),++n%500===0&&await B_();for(let[r,o]of t.stream_receipts)cy(e,r,o),++n%500===0&&await B_()}function Ui(e,t){return!t||t.length===0||t.includes(e)}function ld(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function Wi(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function LT(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(ld(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:Wi(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<Wi(t.since_ts))return!1;return!0}function FT(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function UT(e,t){return!LT(e,t)||!Ui(e.entry.op,t.ops)||!Ui(e.entry.author,t.authors)||!Ui(e.entry.agent_instance??"",t.agent_instances)||!Ui(e.stream_id,t.stream_ids)||!FT(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function zT(e,t){let n=Math.max(0,Math.floor(t.limit)),r=await oy(e,t.stream_ids,t.verify),o=r.events.filter(i=>UT(i,t)).slice(0,n+1);return{events:o.slice(0,t.limit),has_more:o.length>t.limit,...t.verify?{verified_streams:r.stream_receipts.size}:{}}}async function HT(e,t){let n=e.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(z.basename(t,".jsonl")),r=0;try{r=(await $.stat(t)).size}catch(i){if(!Z(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;let o=await fd(z.dirname(z.dirname(t)),z.basename(t,".jsonl"));return n===void 0?o?.byte_size===0:o?.content_hash===n.content_hash}async function dy(e,t,n){let r=z.dirname(z.dirname(e)),o=Gi(),i=!1,s=async()=>{await n(),i=!0};if(!o){await X_(r,s);return}try{await ry(r,async()=>{let a=Jt(r);try{await $.access(a)}catch{await s();return}let c;try{if(c=new o(a),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==cd)throw new TypeError("Unsupported history event index version");if(!await HT(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Xt(l))throw l;await nd(r,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Xt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await nd(r,!1),await s();return}let d=!1;try{await s(),d=!0;let l=z.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);sy(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),cy(c,l,await fd(r,l)),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await nd(r,Xt(l))}},0,"append")}catch(a){if(i){await Vi(r);return}if(!VT(a))throw a;await X_(r,s,Xt(a))}}async function X_(e,t,n=!1){let r=!1,o;try{await id(e,async()=>{let i=n||Bi(await qi(e)),s=await CT(e);o=s.pendingPath;try{await t(),r=!0}catch(a){throw await $.rm(s.pendingPath,{force:!0}),a}await $.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await Vi(e)})}catch(i){if(r){await Vi(e);try{await $.rm(o,{force:!0})}catch{}return}throw i}}async function ud(e){await $.rm(Jt(z.dirname(z.dirname(e))),{force:!0})}function zi(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function qT(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function ly(e,t,n,r){let o;try{let i=await qi(e);if(await Y_(e,i))return ut;let s=await J_(e);if(i.committed.length>0)return Bi(i)&&sd(e,t)?ut:null;if(o=new t(Jt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==cd)return null;let a=r(o);if(a===null)return null;let c=BT(o,n),d=o;o=void 0,d.close();let l=await GT([...c.keys()],e,n),u=await WT(c,e,l),f=await qi(e);return f.committed.length>0||await Y_(e,f)||s!==await J_(e)?ut:u?a:null}catch(i){return Xt(i)?ut:null}finally{o?.close()}}function Xt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function VT(e){return Xt(e)||e instanceof g&&e.code==="lock_conflict"}function BT(e,t){let n=new Map,r=t&&t.length>0?[...new Set(t)]:void 0;if(r===void 0)for(let o of e.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(o.stream_id),{byte_size:Number(o.byte_size),content_hash:String(o.content_hash)});else for(let o=0;o<r.length;o+=500){let i=r.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)})}return n}async function J_(e){let t=await $.stat(Jt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function NU(e,t){if(t.verify)return{result:await zT(e,t),repair_needed:!1};let n=Gi();if(!n)return{result:null,repair_needed:!1};let r=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=Wi(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(r.push("ts >= ?"),o.push(Wi(t.since_ts)));zi(r,o,"op",t.ops),zi(r,o,"author",t.authors),qT(r,o,t.harnesses,t.harness_alias_authors),zi(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);zi(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s=await ly(e,n,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
90
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(t.stream_id,t.stream_offset,n.ts,n.author,n.agent_harness??null,n.agent_instance??null,n.op,Cn(n),JSON.stringify(n))}function fy(e){let t=JSON.parse(String(e.entry_json));return typeof t.ts!="string"||!un(t.ts.trim())?null:{stream_id:String(e.stream_id),stream_offset:Number(e.stream_offset),entry:{...t,ts:new Date(t.ts.trim()).toISOString()}}}function my(e,t,n){e.prepare(`INSERT INTO streams(stream_id, byte_size, content_hash) VALUES (?, ?, ?)
91
+ ON CONFLICT(stream_id) DO UPDATE SET byte_size = excluded.byte_size, content_hash = excluded.content_hash`).run(t,n.byte_size,n.content_hash)}async function BT(e,t={}){let n=Ki();return n?cy(e,async()=>{let r;try{r=await dd(e,()=>Q_(e),t.lockWaitMs)}catch(a){if(a instanceof g&&a.code==="lock_conflict")return!1;throw a}if(r.pending.length>0||Wi(r)&&ld(e,n))return!1;let o=Jt(e);await j.mkdir(z.dirname(o),{recursive:!0});let i=`${o}.${ud()}.tmp`,s;try{s=new n(i),VT(s),s.exec("BEGIN IMMEDIATE");let a=await dy(e);await WT(s,a),s.exec("COMMIT"),s.close(),s=void 0;let c=await dd(e,async()=>{let d=await Q_(e);return d.pending.length>0||!FT(r.committed,d.committed)||Wi(d)&&ld(e,n)?!1:(await j.rm(o,{force:!0}),await j.rename(i,o),!0)},t.lockWaitMs);return c&&await Promise.all(r.committed.map(d=>j.rm(z.join(qr(e),d),{force:!0}))),c||(await Z_(e),await j.rm(i,{force:!0})),c}catch(a){throw await Z_(e),s?.close(),await j.rm(i,{force:!0}),a}},t.lockWaitMs):!1}async function WT(e,t){let n=0;for(let r of t.events)uy(e,r),++n%500===0&&await X_();for(let[r,o]of t.stream_receipts)my(e,r,o),++n%500===0&&await X_()}function zi(e,t){return!t||t.length===0||t.includes(e)}function pd(e,t){return e.entry.ts.localeCompare(t.entry.ts)||e.stream_id.localeCompare(t.stream_id)||e.stream_offset-t.stream_offset}function Gi(e){let t=Date.parse(e);return Number.isFinite(t)?new Date(t).toISOString():e}function GT(e,t){if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){if(pd(e,{stream_id:t.after_stream_id,stream_offset:t.after_stream_offset,entry:{...e.entry,ts:Gi(t.after_ts)}})<=0)return!1}else if(t.since_ts!==void 0&&e.entry.ts<Gi(t.since_ts))return!1;return!0}function KT(e,t){return!t.harnesses||t.harnesses.length===0||t.harnesses.includes(e.entry.agent_harness??"")?!0:e.entry.agent_harness===void 0&&(t.harness_alias_authors??[]).includes(e.entry.author)}function YT(e,t){return!GT(e,t)||!zi(e.entry.op,t.ops)||!zi(e.entry.author,t.authors)||!zi(e.entry.agent_instance??"",t.agent_instances)||!zi(e.stream_id,t.stream_ids)||!KT(e,t)?!1:(t.provenance??[]).every(n=>{let r=e.entry.agent_provenance?.[n.dimension]?.value;return r!==void 0&&n.values.includes(r)})}async function XT(e,t){let n=Math.max(0,Math.floor(t.limit)),r=await dy(e,t.stream_ids,t.verify),o=r.events.filter(i=>YT(i,t)).slice(0,n+1);return{events:o.slice(0,t.limit),has_more:o.length>t.limit,...t.verify?{verified_streams:r.stream_receipts.size}:{}}}async function JT(e,t){let n=e.prepare("SELECT byte_size, content_hash FROM streams WHERE stream_id = ?").get(z.basename(t,".jsonl")),r=0;try{r=(await j.stat(t)).size}catch(i){if(!Q(i))throw i}if(Number(n?.byte_size??0)!==r)return!1;let o=await yd(z.dirname(z.dirname(t)),z.basename(t,".jsonl"));return n===void 0?o?.byte_size===0:o?.content_hash===n.content_hash}async function py(e,t,n){let r=z.dirname(z.dirname(e)),o=Ki(),i=!1,s=async()=>{await n(),i=!0};if(!o){await ty(r,s);return}try{await cy(r,async()=>{let a=Jt(r);try{await j.access(a)}catch{await s();return}let c;try{if(c=new o(a),c.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==fd)throw new TypeError("Unsupported history event index version");if(!await JT(c,e))throw new TypeError("Stale history event index append base")}catch(l){if(c?.close(),Xt(l))throw l;await sd(r,!0),await s();return}try{c.exec("PRAGMA busy_timeout = 0"),c.exec("BEGIN IMMEDIATE")}catch(l){if(c.close(),Xt(l)||!(l instanceof Error)||l.code!=="ERR_SQLITE_ERROR")throw l;await sd(r,!1),await s();return}let d=!1;try{await s(),d=!0;let l=z.basename(e,".jsonl"),u=c.prepare("SELECT COALESCE(MAX(stream_offset), -1) + 1 AS value FROM events WHERE stream_id = ?").get(l);uy(c,{stream_id:l,stream_offset:Number(u.value),entry:t}),my(c,l,await yd(r,l)),c.exec("COMMIT"),c.close()}catch(l){if(c?.close(),!d)throw l;await sd(r,Xt(l))}},0,"append")}catch(a){if(i){await Bi(r);return}if(!QT(a))throw a;await ty(r,s,Xt(a))}}async function ty(e,t,n=!1){let r=!1,o;try{await dd(e,async()=>{let i=n||Wi(await Vi(e)),s=await LT(e);o=s.pendingPath;try{await t(),r=!0}catch(a){throw await j.rm(s.pendingPath,{force:!0}),a}await j.rename(s.pendingPath,i?s.committedPath.replace(/\.committed$/u,".contended.committed"):s.committedPath),i||await Bi(e)})}catch(i){if(r){await Bi(e);try{await j.rm(o,{force:!0})}catch{}return}throw i}}async function _d(e){await j.rm(Jt(z.dirname(z.dirname(e))),{force:!0})}function Hi(e,t,n,r){!r||r.length===0||(e.push(`${n} IN (${r.map(()=>"?").join(", ")})`),t.push(...r))}function ZT(e,t,n,r){if(!n||n.length===0)return;let o=n.map(()=>"?").join(", "),i=r??[];if(i.length>0){e.push(`(agent_harness IN (${o}) OR (agent_harness IS NULL AND author IN (${i.map(()=>"?").join(", ")})))`),t.push(...n,...i);return}e.push(`agent_harness IN (${o})`),t.push(...n)}async function _y(e,t,n,r){let o;try{let i=await Vi(e);if(await ey(e,i))return ut;let s=await ny(e);if(i.committed.length>0)return Wi(i)&&ld(e,t)?ut:null;if(o=new t(Jt(e),{readOnly:!0}),o.exec("BEGIN"),o.prepare("SELECT value FROM metadata WHERE key = 'version'").get()?.value!==fd)return null;let a=r(o);if(a===null)return null;let c=eC(o,n),d=o;o=void 0,d.close();let l=await nC([...c.keys()],e,n),u=await tC(c,e,l),f=await Vi(e);return f.committed.length>0||await ey(e,f)||s!==await ny(e)?ut:u?a:null}catch(i){return Xt(i)?ut:null}finally{o?.close()}}function Xt(e){return typeof e=="object"&&e!==null&&"errcode"in e&&[5,6].includes(e.errcode)}function QT(e){return Xt(e)||e instanceof g&&e.code==="lock_conflict"}function eC(e,t){let n=new Map,r=t&&t.length>0?[...new Set(t)]:void 0;if(r===void 0)for(let o of e.prepare("SELECT stream_id, byte_size, content_hash FROM streams").all())n.set(String(o.stream_id),{byte_size:Number(o.byte_size),content_hash:String(o.content_hash)});else for(let o=0;o<r.length;o+=500){let i=r.slice(o,o+500);for(let s of e.prepare(`SELECT stream_id, byte_size, content_hash FROM streams WHERE stream_id IN (${i.map(()=>"?").join(", ")})`).all(...i))n.set(String(s.stream_id),{byte_size:Number(s.byte_size),content_hash:String(s.content_hash)})}return n}async function ny(e){let t=await j.stat(Jt(e),{bigint:!0});return[t.dev,t.ino,t.size,t.mtimeNs,t.ctimeNs].join(":")}async function KU(e,t){if(t.verify)return{result:await XT(e,t),repair_needed:!1};let n=Ki();if(!n)return{result:null,repair_needed:!1};let r=[],o=[];if(t.after_ts!==void 0&&t.after_stream_id!==void 0&&t.after_stream_offset!==void 0){r.push("(ts > ? OR (ts = ? AND stream_id > ?) OR (ts = ? AND stream_id = ? AND stream_offset > ?))");let a=Gi(t.after_ts);o.push(a,a,t.after_stream_id,a,t.after_stream_id,t.after_stream_offset)}else t.since_ts!==void 0&&(r.push("ts >= ?"),o.push(Gi(t.since_ts)));Hi(r,o,"op",t.ops),Hi(r,o,"author",t.authors),ZT(r,o,t.harnesses,t.harness_alias_authors),Hi(r,o,"agent_instance",t.agent_instances);for(let a of t.provenance??[])r.push(`json_extract(entry_json, '$.agent_provenance.${a.dimension}.value') IN (${a.values.map(()=>"?").join(", ")})`),o.push(...a.values);Hi(r,o,"stream_id",t.stream_ids);let i=r.length===0?"":` WHERE ${r.join(" AND ")}`,s=await _y(e,n,t.stream_ids,a=>{let c=a.prepare(`SELECT stream_id, stream_offset, entry_json
92
92
  FROM events${i}
93
93
  ORDER BY ts, stream_id, stream_offset
94
- LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(ay);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===ut?null:s,repair_needed:s===null&&!await ny(e)}}function uy(e,t){let n=Object.create(null);for(let r of e){if(!t.has(r.stream_id)||Tn(r.entry)!=="substantive")continue;let o=n[r.stream_id];(o===void 0||ld(o,r)<0)&&(n[r.stream_id]=r)}return n}async function fd(e,t){if(z.basename(t)!==t)return null;try{let n=z.join(e,"history",`${t}.jsonl`),r=await $.stat(n),o=await $.readFile(n);return r.size!==o.length?null:{byte_size:o.length,content_hash:Hi("sha256").update(o).digest("hex")}}catch(n){if(Z(n))return{byte_size:0,content_hash:Hi("sha256").digest("hex")};throw n}}async function WT(e,t,n){for(let r=0;r<n.length;r+=W_){let o=n.slice(r,r+W_),i=await Promise.all(o.map(s=>fd(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a.byte_size===0&&d===void 0)&&(a.byte_size!==d?.byte_size||a.content_hash!==d.content_hash))return!1}}return!0}async function GT(e,t,n){if(n&&n.length>0)return[...new Set(n.filter(o=>o.trim().length>0))];let r=await $.readdir(z.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(Z(o))return[];throw o});return[...new Set([...e,...r])]}async function Q_(e,t,n,r){return e?ly(t,e,n,o=>{let i=[];for(let s=0;s<n.length;s+=500){let a=n.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
94
+ LIMIT ?`).all(...o,Math.max(0,Math.floor(t.limit))+1),d=c.slice(0,t.limit).map(fy);return d.includes(null)?null:{events:d,has_more:c.length>t.limit}});return{result:s===ut?null:s,repair_needed:s===null&&!await ay(e)}}function yy(e,t){let n=Object.create(null);for(let r of e){if(!t.has(r.stream_id)||Cn(r.entry)!=="substantive")continue;let o=n[r.stream_id];(o===void 0||pd(o,r)<0)&&(n[r.stream_id]=r)}return n}async function yd(e,t){if(z.basename(t)!==t)return null;try{let n=z.join(e,"history",`${t}.jsonl`),r=await j.stat(n),o=await j.readFile(n);return r.size!==o.length?null:{byte_size:o.length,content_hash:qi("sha256").update(o).digest("hex")}}catch(n){if(Q(n))return{byte_size:0,content_hash:qi("sha256").digest("hex")};throw n}}async function tC(e,t,n){for(let r=0;r<n.length;r+=J_){let o=n.slice(r,r+J_),i=await Promise.all(o.map(s=>yd(t,s)));for(let[s,a]of i.entries()){if(a===null)return!1;let c=o[s],d=e.get(c);if(!(a.byte_size===0&&d===void 0)&&(a.byte_size!==d?.byte_size||a.content_hash!==d.content_hash))return!1}}return!0}async function nC(e,t,n){if(n&&n.length>0)return[...new Set(n.filter(o=>o.trim().length>0))];let r=await j.readdir(z.join(t,"history"),{withFileTypes:!0}).then(o=>o.filter(i=>i.isFile()&&i.name.endsWith(".jsonl")).map(i=>i.name.slice(0,-6))).catch(o=>{if(Q(o))return[];throw o});return[...new Set([...e,...r])]}async function ry(e,t,n,r){return e?_y(t,e,n,o=>{let i=[];for(let s=0;s<n.length;s+=500){let a=n.slice(s,s+500),c=o.prepare(`SELECT stream_id, stream_offset, entry_json
95
95
  FROM (
96
96
  SELECT stream_id, stream_offset, entry_json,
97
97
  ROW_NUMBER() OVER (
@@ -102,15 +102,15 @@ ${N_(t,n+1)}`}function MI(e,t,n){let r=e.map(o=>Wt(o,t,n||t.preserveRowFacts&&x(
102
102
  WHERE event_class = 'substantive'
103
103
  AND stream_id IN (${a.map(()=>"?").join(", ")})
104
104
  )
105
- WHERE recency_rank = 1`).all(...a).map(ay);if(c.includes(null))return null;i.push(...c)}return uy(i,r)}):null}async function DU(e,t){let n=[...new Set(t.filter(a=>a.trim().length>0&&z.basename(a)===a))];if(n.length===0)return{};let r=new Set(n),o=Gi(),i=await Q_(o,e,n,r);if(i!==null&&i!==ut)return i;if(o&&i!==ut&&!await ny(e))try{if(await jT(e,{lockWaitMs:0})){let a=await Q_(o,e,n,r);if(a!==null&&a!==ut)return a}}catch{}let s=[];return await Promise.all(n.map(async a=>{let c=z.join(e,"history",`${a}.jsonl`);(await PT(c,a).catch(d=>{if(d instanceof g&&d.code==="history_timestamp_invalid")return[];throw d})).forEach((d,l)=>{s.push({stream_id:a,stream_offset:l,entry:d})})})),uy(s,r)}import md from"node:fs/promises";import Ln 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]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var KT=Ln.join("runtime","history-drift-cache.json"),fy={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function my(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function YT(e){let t=Ln.join(e,KT),n=!1,r="invalid_cache_path";try{n=(await md.stat(await md.realpath(e))).isDirectory()}catch(o){let i=my(o);r=i===void 0?"unknown":fy[i]??"filesystem_error"}if(!n){Ur(`[pm] warning: history_drift_cache_invalidation_failed:${r}
106
- `);return}try{await md.rm(t,{force:!0})}catch(o){let i=my(o);if(Z(o))return;let s=i===void 0?"unknown":fy[i]??"filesystem_error";Ur(`[pm] warning: history_drift_cache_invalidation_failed:${s}
107
- `)}}async function Ki(e){let t=Ln.dirname(Ln.resolve(e));Ln.basename(t)==="history"&&await YT(Ln.dirname(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();var JT={front_matter:{},body:""},Gt=3,zr=[1,2,3],QT=1,ZT=[1];function by(e){return Je(R(e),e.hash_algorithm)}function Fn(e){return to(R(e))}function rz(e){return to(R(e))}function hd(e){let t={...e,record_hash_version:QT},{record_hash:n,...r}=t;return{...t,record_hash:by(r)}}function Mi(e){try{Tt(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!ZT.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return by(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function eC(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Fn(e.patch)};return e.hash_algorithm!==void 0&&(n.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function $_(e,t,n={}){let r=Mi(e);if(!r.ok)throw new TypeError(r.error);let o=Fn(e.patch),i=n.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Fn(t.patch),s=hd({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],eC(e,n)]}:{}}),a=ed(s);if(!a.ok)throw new TypeError(a.error);return s}function wy(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Qt(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function tC(e){return Qt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&wy(e.patch)}function nC(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function rC(e){return!Qt(e)||!nC(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!wy(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||tC(e.record)}function oC(e){try{for(let t of e){if(!rC(t))return!1;Tt(t.hash_algorithm)}return!0}catch{return!1}}function iC(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Fn(t.patch)===e.patch_hash}function sC(e,t,n){if(t.patch&&Fn(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return iC(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(Fn(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...n.length===0?{}:{reanchor_evidence:n}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,n.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function ed(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!oC(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r],i=sC(n,o,t.slice(0,r));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!Mi(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function Yi(e,t){return(e??"").localeCompare(t??"")}function _y(e,t){return(e??0)-(t??0)}function ft(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function aC(e,t){return[e.scope.localeCompare(t.scope),Yi(e.path,t.path),Yi(e.command,t.command),_y(e.timeout_seconds,t.timeout_seconds),Yi(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,ft(e.env_clear,t.env_clear,[]),ft(e.env_set,t.env_set,{}),ft(e.assert_stdout_contains,t.assert_stdout_contains,[]),ft(e.assert_stdout_regex,t.assert_stdout_regex,[]),ft(e.assert_stderr_contains,t.assert_stderr_contains,[]),ft(e.assert_stderr_regex,t.assert_stderr_regex,[]),_y(e.assert_stdout_min_lines,t.assert_stdout_min_lines),ft(e.assert_json_field_equals,t.assert_json_field_equals,{}),ft(e.assert_json_field_gte,t.assert_json_field_gte,{}),Yi(e.note,t.note)].find(n=>n!==0)??0}function cC(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function dC(e,t){let n=cC(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:Qt(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function lC(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!dC(r,o.path)?{...o,op:"add"}:o;n.push(i),r=gy.applyPatch(r,[i],!0,!0).newDocument}return n}function Xi(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=Sn(e),o=t===1||t===2&&n?{...r.metadata,...r.metadata.dependencies===void 0?{}:{dependencies:r.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...r.metadata.tests===void 0?{}:{tests:r.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...r.metadata.test_runs===void 0?{}:{test_runs:r.metadata.test_runs.map(({executions:s,...a})=>a)}}:r.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(aC)}:o;return{front_matter:A(i,Ve),body:r.body}}function yy(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=Sn(e);return{metadata:A(t.metadata,Ve),body:t.body}}function oz(e){return vy(e,Gt)}function vy(e,t,n){if(!zr.some(r=>r===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Je(R(Xi(e,t)),n)}function L_(e,t,n){let r=vy(e,t,n);return t===2?[r,Je(R(Xi(e,t,!0)),n)]:[r]}function iz(){return to(R(JT))}function qr(e){let t=tm(e.op),n=Xi(e.before,Gt),r=Xi(e.after,Gt),o=yy(e.before),i=yy(e.after),s=gy.compare(o,i),a=lC(o,s),c=zm(e.author),d=c.harness?Object.fromEntries(Object.entries(Fm().provenance_outcomes).filter(([m,_])=>_.resolver!==void 0&&(_.status!=="resolved"||c.provenance?.[m]?.source==="probe"))):void 0,l=d===void 0||Object.keys(d).length===0?e.context:{...e.context,agent_provenance_outcomes:d},u=e.hashAlgorithm??mf,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??Um(e.author),...c.harness?{agent_harness:c.harness}:{},...c.model?{agent_model:c.model}:{},...c.model_source?{agent_model_source:c.model_source}:{},...c.instance?{agent_instance:c.instance}:{},...c.provenance?{agent_provenance:c.provenance}:{},...c.episode?{agent_episode:c.episode}:{},op:t,patch:a,before_hash:Je(R(n),u),after_hash:Je(R(r),u),item_hash_version:Gt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return hd({...f,event_class:Tn(f)})}function Qt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function pd(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function Ey(e){let t=e.ts.trim();if(t.length===0)return Te();if(!ln(t))throw pd("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw pd("History timestamp must not contain surrounding whitespace");return e.ts}function hy(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!ln(n))throw pd("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function _d(e,t){let n=Ey(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return Qt(r)?JSON.stringify(hy(r,n)):e}return Qt(e)?JSON.stringify(hy(e,n)):JSON.stringify(e)}async function uC(e,t,n){if(n===!1)return!0;if(typeof n=="string"){let s=_d(n,t);return await yd(e,s),await Ki(e),await ud(e),!0}if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e,i=_d(typeof r.line=="string"?r.line:r.entry??t,t);return await yd(o,i),await Ki(o),await ud(o),!0}async function yd(e,t){let n;try{n=JSON.parse(t)}catch{n=null}if(!Qt(n)||n.op!=="create"){await Yd(e,t);return}await py.mkdir(XT.dirname(e),{recursive:!0});try{await py.writeFile(e,`${t}
108
- `,{encoding:"utf8",flag:"wx"})}catch(r){throw r.code!=="EEXIST"?r:new g("This item identity is reserved by an existing history stream.",h.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function Vr(e,t){let n=await bn("history_append",{history_path:e,entry:t});if(n.handled&&await uC(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:Ey(t)},o=hd({...r,hash_algorithm:Tt(r.hash_algorithm),event_class:Tn(r)});await dy(e,o,async()=>{await yd(e,_d(o,o))}),await Ki(e)}import ky from"node:fs/promises";import Un 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]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();var mt="_workspace";function Zt(e){return Un.join(e,"history",`${mt}.jsonl`)}function gd(e,t){return{metadata:{id:mt,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function en(e,t=e.length){let n=ji();for(let r of e.slice(0,t))n=Li(n,r.patch).document;return $i(n)}function zn(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function Hn(e){throw new g(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Ji(e,t){let n=Un.resolve(t),r=Un.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||Un.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function gz(e){let t=await Mt(Zt(e),mt),n=Kt(t);n.ok||Hn(n.errors);let r=zn(t.length===0?Bn:en(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let d;try{let l=Ji(e,Un.resolve(e,c));if(d=await Ae(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Sy(e){let t=Zt(e.pmRoot),n=await Mt(t,mt),r=Kt(n);r.ok||Hn(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Te(),s=n.length===0?Bn:en(n),a=zn(s),c=a[e.documentPath];if(c!==void 0&&R(c)!==R(e.before))throw new g(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=gd({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=qr({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:d,message:e.message});return await Vr(t,l),{entry:l,historyPath:t}}async function bz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Sy(e)}finally{await t()}}async function wz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=Zt(e.pmRoot),r=await Mt(n,mt),o=Kt(r);o.ok||Hn(o.errors);let i=r.length===0?Bn:en(r),s=qr({nowIso:Te(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Vr(n,s),{entry:s,historyPath:n}}finally{await t()}}async function Oy(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await bt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Sy({pmRoot:e.pmRoot,documentPath:Un.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await ky.rm(e.filePath,{force:!0}):await bt(e.filePath,t),o}return!0}async function Ay(e){let{documentPath:t}=Ji(e.pmRoot,e.filePath),n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await Ae(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Mt(Zt(e.pmRoot),mt),s=Kt(i);s.ok||Hn(s.errors);let a=zn(i.length===0?Bn:en(i))[t];if(a!==void 0&&R(a)!==R(r===null?null:JSON.parse(r)))throw new g(`Workspace history state for "${t}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(c=>c.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await Oy({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function vz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Oy(e,await Ae(e.filePath))}finally{await t()}}async function Ez(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Ji(e.pmRoot,e.filePath),i=Zt(e.pmRoot),s=await Mt(i,mt),a=Kt(s);a.ok||Hn(a.errors);let c=en(s),d=zn(c);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let l=await Ae(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(l);if(R(d[r])===R(u))return{changed:!1,historyPath:i};let f=Te(),m=qr({nowIso:f,author:e.author,op:e.op,before:c,after:gd({...d,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Vr(i,m),{changed:!0,entry:m,historyPath:i}}finally{await n()}}async function kz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Ji(e.pmRoot,e.filePath),o=await Mt(Zt(e.pmRoot),mt),i=Kt(o);if(i.ok||Hn(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=zn(en(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Ae(r),c=`${JSON.stringify(s,null,2)}
109
- `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let d=en(o),l=Te(),u=qr({nowIso:l,author:e.author,op:e.op,before:d,after:gd({...zn(d),[n]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await bt(r,c);try{await Vr(Zt(e.pmRoot),u)}catch(f){throw a===null?await ky.rm(r,{force:!0}):await bt(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78651211-fe4b-564e-a872-23bf25265243")}catch{}})();var Pe={ok:!1,path:[]};function wd(e,t){return{ok:!1,path:[e,...t.path]}}var w=e=>typeof e=="string"?{ok:!0,value:e}:Pe,N=e=>typeof e=="boolean"?{ok:!0,value:e}:Pe;function F(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?Pe:{ok:!0,value:t}}function D(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:Pe}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return Pe;let r=[];for(let[o,i]of n.entries()){let s=e(i);if(!s.ok)return wd(String(o),s);r.push(s.value)}return{ok:!0,value:r}}}function vd(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:Pe}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Qi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Pe;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return wd(r,i);n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Pe;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return wd(o,s);s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var fC=I({key:w,values:k(w),required:p(N),aliases:p(k(w)),description:p(w)}),mC=I({command:D("create","update"),option:w,required:p(N),visible:p(N),enabled:p(N)}),pC=I({name:w,description:p(w),default_status:p(w),execution_role:p(D("agent","human","gate")),folder:p(w),aliases:p(k(w)),required_create_fields:p(k(w)),required_create_repeatables:p(k(w)),options:p(k(fC)),command_option_policies:p(k(mC))}),_C=I({id:w,aliases:p(k(w)),roles:p(k(D(...io))),description:p(w),order:p(F())}),yC=I({key:w,metadata_key:p(w),front_matter_key:p(w),cli_flag:p(w),cli_aliases:p(k(w)),description:p(w),type:p(D(...cn)),commands:p(k(D(...so))),repeatable:p(N),required:p(N),required_on_create:p(N),required_types:p(k(w)),allow_unset:p(N)}),hC=e=>{if(!Array.isArray(e)||e.length!==2)return Pe;let[t,n]=e;return typeof t!="string"||typeof n!="string"?Pe:{ok:!0,value:[t,n]}},gC=I({type:w,allowed_transitions:k(hC)}),bC=p(I({version:p(F({int:!0})),files:p(I({types:p(w),statuses:p(w),fields:p(w),workflows:p(w)})),statuses:p(k(_C)),fields:p(k(yC)),workflow:p(I({draft_status:p(w),open_status:p(w),in_progress_status:p(w),blocked_status:p(w),close_status:p(w),canceled_status:p(w)})),type_workflows:p(k(gC)),unknown_field_policy:p(D(...ao))})),wC=p(I({preset:p(D(...rl)),ownership_enforcement:p(D("none","warn","strict")),create_mode_default:p(D("progressive","strict")),close_validation_default:p(D("off","warn","strict")),require_close_reason:p(N),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),force_required_for_stale_lock:p(N),create_default_type:p(w),workflow_enforcement:p(D("off","warn","strict")),start_blocker_enforcement:p(D("off","warn","strict")),duplicate_detection_mode:p(D("off","advisory","strict")),duplicate_detection_threshold:p(F({min:0,max:1})),duplicate_detection_limit:p(F({int:!0,min:0,max:20}))})),vC=I({name:w,disabled:p(N),require_trusted:p(N),require_provenance:p(N),sandbox_profile:p(D("none","restricted","strict")),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w))}),bd=D("block","warn"),EC=e=>typeof e=="string"?bd(e):I({global:p(bd),project:p(bd)})(e),kC=p(I({mode:p(D("off","warn","enforce")),trust_mode:p(D("off","warn","enforce")),pm_max_version_exceeded_mode:p(EC),require_provenance:p(N),trusted_extensions:p(k(w)),default_sandbox_profile:p(D("none","restricted","strict")),allowed_extensions:p(k(w)),blocked_extensions:p(k(w)),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w)),extension_overrides:p(k(vC))})),tn=vd(128),SC=I({harness:vd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(tn,64)),model_environment_keys:p(k(tn,64)),session_environment_keys:p(k(tn,64)),provenance_environment_keys:p(Qi(k(tn,64))),provenance_resolvers:p(Qi(D("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(tn,64)),argv_markers:p(k(tn,64)),client_names:p(k(tn,64))}),Iy={version:F({int:!0}),id_prefix:w,ids:p(I({token_length:p(F({int:!0,min:4,max:12}))})),author_default:w,agent_identity:p(I({probes_enabled:p(N),identity_vocabulary:p(I({version:F({int:!0,positive:!0}),aliases:Qi(vd(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(SC)})),mutation_guard:p(I({require_attributed_author:p(N),secret_guard:p(D("off","advise","block")),stale_in_progress_hours:p(F({int:!0,positive:!0}))})),item_format:p(D("toon","json_markdown")),locks:I({ttl_seconds:F({int:!0}),wait_ms:p(F({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(F({int:!0,positive:!0}))})),output:I({default_format:D("toon","json")}),ux:p(I({deprecation_hints:p(N)})),history:p(I({missing_stream:D("auto_create","strict_error"),compact_policy:p(I({enabled:p(N),max_entries:p(F({int:!0,positive:!0})),trigger:p(D("health_warn","auto"))}))})),validation:p(I({sprint_release_format:D("warn","strict_error"),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),metadata_required_fields:p(k(w)),lifecycle_stale_blocker_reason_patterns:p(k(w)),lifecycle_closure_like_blocked_reason_patterns:p(k(w)),lifecycle_closure_like_resolution_patterns:p(k(w)),lifecycle_closure_like_actual_result_patterns:p(k(w)),estimate_defaults_by_type:p(Qi(F({int:!0,positive:!0})))})),governance:wC,workflow:p(I({definition_of_done:k(w)})),testing:p(I({record_results_to_items:N,allow_untrusted_linked_tests:p(N)})),telemetry:p(I({enabled:N,first_run_prompt_completed:p(N),capture_level:p(D("minimal","redacted","max")),endpoint:p(w),installation_id:p(w),retention_days:p(F({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(N),declined:p(N),declined_at:p(w),template_version:p(F({int:!0,positive:!0})),last_checked_files:p(k(w))})),item_types:p(I({definitions:k(pC)})),schema:bC,context:p(I({default_depth:p(D(...sl)),activity_limit:p(F({int:!0,positive:!0})),stale_threshold_days:p(F({int:!0,positive:!0})),next_ranking_policy:p(D("priority_floor","weighted")),sections:p(I({hierarchy:p(N),activity:p(N),progress:p(N),recently_created:p(N),unparented:p(N),blockers:p(N),files:p(N),workload:p(N),staleness:p(N),tests:p(N)}))})),extensions:I({enabled:k(w),disabled:k(w),policy:kC}),search:I({score_threshold:F(),hybrid_semantic_weight:p(F()),max_results:F({int:!0}),embedding_model:w,embedding_corpus_max_characters:p(F()),embedding_batch_size:F({int:!0}),embedding_timeout_ms:p(F({int:!0})),scanner_max_batch_retries:F({int:!0}),provider:p(w),default_mode:p(D("auto","keyword","semantic","hybrid")),corpus_fields:p(k(w)),mutation_refresh_policy:p(D("cache_only","semantic_configured","semantic_auto")),query_expansion:p(I({enabled:p(N),provider:p(w)})),rerank:p(I({enabled:p(N),model:p(w),top_k:p(F({int:!0,positive:!0}))})),bm25:p(I({k1:p(F()),b:p(F())}))}),providers:I({openai:I({base_url:w,api_key:w,model:w}),ollama:I({base_url:w,model:w})}),vector_store:I({adapter:p(w),collection_name:p(w),qdrant:I({url:w,api_key:w}),lancedb:I({path:w})})},OC=I(Iy),Ty=Object.freeze(Object.keys(Iy));function Zi(e){let t=OC(e);return t.ok?{success:!0,data:t.value}:{success:!1,path:t.path.join(".")}}import{AsyncLocalStorage as xC}from"node:async_hooks";import{lstat as NC,realpath as Fy}from"node:fs/promises";import Uy 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]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function es(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ed(e,t,n,r=[]){if(B(e,t)&&(r.length>0||es(n)))return n;if(B(e,n)||B(t,n))return t;if((e===void 0||es(e))&&es(t)&&es(n)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(n)]);return Object.fromEntries([...i].flatMap(s=>{let a=Ed(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(n,s)?n[s]:void 0,[...r,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${r.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,h.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}(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]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();var AC={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Cy=120;function kd(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function xy(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var IC=xy(AC),Ry=new WeakMap;function TC(e){let t=Ry.get(e);if(t)return t;let n=xy(e);return Ry.set(e,n),n}function xz(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Cy;if(t){let o=TC(t).get(n);if(kd(o))return Math.floor(o)}let r=IC.get(n);return kd(r)?Math.floor(r):Cy}function Sd(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!kd(r)||(t[o]=Math.floor(r))}return t}import{stat as CC}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();var ts=new Map;function Ny(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function RC(e){try{let t=await CC(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function pt(e){let t=Ny(e),n=await Promise.all(t.map(r=>RC(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Br(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function Dy(e){return ts.get(e)}function ns(e,t){let n=Ny(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));ts.set(e,{tracked_paths:n,signatures:r,value:t.value})}function nn(e){if(e){ts.delete(e);return}ts.clear()}(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]="6e01cb2d-2ff0-54f2-abdb-2d16f36487c1")}catch{}})();var Td=new xC;async function Zz(e,t,n=()=>!0){let r=new Set([Uy.resolve(e)]);try{r.add(await Fy(e))}catch{}return Td.run([...Td.getStore()??[],[r,n]],t)}function DC(e){let t=Uy.resolve(e);return Td.getStore()?.some(([n,r])=>n.has(t)&&r())??!1}var PC="settings:write",zy=Symbol("pm.settings.persist_source"),Hy=Symbol("pm.settings.fallback_origin"),qy=Symbol("pm.settings.fallback_baseline"),MC=128,jC=new Set(["off","advisory","strict"]);function Py(e){return structuredClone(Gd[e])}function $C(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}var LC=new Set(ol);function Vy(e){return LC.has(e)}function My(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),Vy(t.start_blocker_enforcement)&&(e.start_blocker_enforcement=t.start_blocker_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function FC(e){return e.preset==="custom"?My({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):My({preset:e.preset},e)}function UC(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),Vy(e.start_blocker_enforcement)&&(n.start_blocker_enforcement=e.start_blocker_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),jC.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function By(e){let t=e.governance??{},n=$C(t.preset),r=UC(t);if(n==="custom"){let s=Py("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Py(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function xd(){return structuredClone(S)}function Wy(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function Gy(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function Ky(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function Yy(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function Xy(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function Jy(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function Qy(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function Zy(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,MC);return t.length>0?t:S.vector_store.collection_name}function Od(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function eh(e,t){let n=e.schema,r=Od(n?.statuses),o=Od(n?.fields),i=Od(n?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:qn(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:qn(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function is(e,t){Object.defineProperty(e,zy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Nd(e){let t=e[zy];if(!(!t||typeof t!="object"))return t}function e2(e){let t=Nd(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,is(e,n)}}function rs(e){let t=structuredClone(e.settings),n=Nd(e.settings);n&&is(t,n);let r=Dd(e.settings);return r!==void 0&&th(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function zC(e,t,n){let r=Ce(t);return[n,ue(e,r.files.types,ie.types),ue(e,r.files.statuses,ie.statuses),ue(e,r.files.fields,ie.fields),ue(e,r.files.workflows,ie.workflows)]}async function HC(e,t,n){let r=await pt(t);ns(e,{tracked_paths:t,signatures:r,value:rs(n)})}async function qC(e,t,n){try{await HC(e,t,n)}catch{nn(e)}}function jy(e,t){return e.find(n=>n.path===t)}function VC(e,t,n){for(let r of n){let o=jy(e,r),i=jy(t,r);if(!o||!i||!Br([o],[i]))return!1}return!0}async function Ad(e,t,n,r,o){try{let i=await pt(t);if(!VC(r,i,o)){nn(e);return}ns(e,{tracked_paths:t,signatures:i,value:rs(n)})}catch{nn(e)}}function BC(e,t){let n=Ce(e.schema),r=qn(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=B(r,t.runtime_item_type_definitions),s=B(n.statuses,t.runtime_schema_statuses),a=B(n.fields,t.runtime_schema_fields),c=B(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?qn(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function th(e,t){Object.defineProperty(e,Hy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function t2(e){return Dd(e)!==void 0}function Dd(e){let t=e[Hy];return typeof t=="string"?t:void 0}function WC(e){return e[qy]}function GC(e,t){Object.defineProperty(e,qy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Me(e){let t=xd();return e!==void 0&&th(t,e),{settings:t,metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function nh(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Cd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function rh(e){let t=S.agent_guidance,n=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:Cd(e?.last_checked_files??t.last_checked_files)}}function Oe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function KC(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function YC(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function oh(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function XC(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=oh(e.sandbox_profile));let r=Oe(e.allowed_capabilities),o=Oe(e.blocked_capabilities),i=Oe(e.allowed_surfaces),s=Oe(e.blocked_surfaces),a=Oe(e.allowed_commands),c=Oe(e.blocked_commands),d=Oe(e.allowed_actions),l=Oe(e.blocked_actions),u=Oe(e.allowed_services),f=Oe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function JC(e){let t=new Map;for(let n of e??[]){let r=XC(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function Id(e){return e==="block"||e==="warn"?e:void 0}function QC(e){if(typeof e=="string")return Id(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=Id(e.global),n=Id(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function he(e,t){return Oe(e?.[t]??S.extensions.policy[t])}function ih(e){let t=QC(e?.pm_max_version_exceeded_mode);return{mode:KC(e?.mode),trust_mode:YC(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:he(e,"trusted_extensions"),default_sandbox_profile:oh(e?.default_sandbox_profile),allowed_extensions:he(e,"allowed_extensions"),blocked_extensions:he(e,"blocked_extensions"),allowed_capabilities:he(e,"allowed_capabilities"),blocked_capabilities:he(e,"blocked_capabilities"),allowed_surfaces:he(e,"allowed_surfaces"),blocked_surfaces:he(e,"blocked_surfaces"),allowed_commands:he(e,"allowed_commands"),blocked_commands:he(e,"blocked_commands"),allowed_actions:he(e,"allowed_actions"),blocked_actions:he(e,"blocked_actions"),allowed_services:he(e,"allowed_services"),blocked_services:he(e,"blocked_services"),extension_overrides:JC(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function sh(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,n)=>t.localeCompare(n)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function _t(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function W(e,t){return e===void 0?t:e}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Rd(e){return Array.isArray(e)?e:[]}function ZC(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:sh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:_t(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:_t(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:_t(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:_t(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Sd(e.validation?.estimate_defaults_by_type)}}function eR(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function tR(e,t){return{...t.search,...e.search,default_mode:Gy(e.search?.default_mode),mutation_refresh_policy:Wy(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Ky(e.search?.query_expansion?.enabled),provider:Yy(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:Xy(e.search?.rerank?.enabled),model:Jy(e.search?.rerank?.model),top_k:Qy(e.search?.rerank?.top_k)}}}function nR(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:Zy(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function rR(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function oR(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??t.context.next_ranking_policy,sections:{...t.context.sections,...e.context?.sections}}}function iR(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function qn(e){let t=(e??[]).map(r=>fo(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function os(e){let t=xd(),n=By({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:rR(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:ZC(e,t,n),governance:n,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:eR(e,t),agent_guidance:rh(e.agent_guidance??t.agent_guidance),item_types:{definitions:qn(e.item_types?.definitions)},schema:Ce(e.schema??t.schema),context:oR(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:ih(e.extensions.policy??t.extensions.policy)},search:tR(e,t),providers:iR(e,t),vector_store:nR(e,t)}}function sR(e){e.agent_identity=A(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=A(ge(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Rd(e.agent_identity.harness_signals).map(n=>A(ge(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=A(e.locks,["ttl_seconds","wait_ms"]),e.ids=A(e.ids,["token_length"]),e.mutation_guard=A(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=A(e.checkpoints,["retention_days"]),e.output=A(e.output,["default_format"]),e.ux=A(e.ux,["deprecation_hints"]),e.history=A(e.history,["missing_stream","compact_policy"]),e.validation=A(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=A(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=A(e.workflow,["definition_of_done"]),e.testing=A(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=A(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=A(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=A(e.item_types,["definitions"]),e.schema=A(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=A(ge(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(ge(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=A(e.context,["default_depth","activity_limit","stale_threshold_days","next_ranking_policy","sections"]),e.context.sections=A(ge(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(ge(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),e.extensions.policy.extension_overrides=Rd(e.extensions.policy.extension_overrides).map(n=>A(ge(n),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=A(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=A(ge(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(ge(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(ge(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(ge(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(ge(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(ge(e.vector_store.lancedb),["path"])}function aR(e){return{...e,locks:W(e.locks,S.locks),ids:W(e.ids,S.ids),agent_identity:W(e.agent_identity,S.agent_identity),mutation_guard:W(e.mutation_guard,S.mutation_guard),checkpoints:W(e.checkpoints,S.checkpoints),output:W(e.output,S.output),ux:W(e.ux,S.ux),history:W(e.history,S.history),validation:W(e.validation,S.validation),workflow:W(e.workflow,S.workflow),testing:W(e.testing,S.testing),telemetry:W(e.telemetry,S.telemetry),agent_guidance:W(e.agent_guidance,S.agent_guidance),item_types:W(e.item_types,S.item_types),schema:W(e.schema,S.schema),context:W(e.context,S.context),extensions:W(e.extensions,S.extensions),search:W(e.search,S.search),providers:W(e.providers,S.providers),vector_store:W(e.vector_store,S.vector_store)}}function cR(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:sh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:_t(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:_t(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:_t(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:_t(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Sd(e.validation?.estimate_defaults_by_type)}}function dR(e){return{...S.search,...e.search,default_mode:Gy(e.search?.default_mode),mutation_refresh_policy:Wy(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:Ky(e.search?.query_expansion?.enabled),provider:Yy(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:Xy(e.search?.rerank?.enabled),model:Jy(e.search?.rerank?.model),top_k:Qy(e.search?.rerank?.top_k)}}}function lR(e){return{default_depth:e.context?.default_depth??S.context.default_depth,activity_limit:e.context?.activity_limit??S.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??S.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??S.context.next_ranking_policy,sections:{...S.context.sections,...e.context?.sections}}}function uR(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:Zy(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function fR(e,t,n,r){return{...e,item_format:"toon",validation:cR(e,t),governance:t,agent_guidance:rh(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:dR(e),context:lR(e),extensions:{enabled:Cd(e.extensions?.enabled),disabled:Cd(e.extensions?.disabled),policy:ih(e.extensions?.policy)},vector_store:uR(e)}}function ah(e,t){for(let n of Object.keys(t)){let r=Reflect.get(t,n),o=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?ah(o,r):e[n]=structuredClone(r)}}function Pd(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!B(i,s)){if(s===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=e[o],c=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};Pd(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var ss=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function $y(e,t){let n=aR(e),r=By(n),o=Ce(n.schema),i=BC(n,t),s=fR(n,r,o,i),a=A({...s,governance:FC(r)},ss);return sR(a),a}function ch(e,t={}){let n=t.source===void 0?t.persist_source:eh(t.source.validated,os(t.source.validated)),r=$y(e,n);if(n){let o=os(n.source_settings);o.item_types={definitions:structuredClone(n.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(n.runtime_schema_statuses),fields:structuredClone(n.runtime_schema_fields),type_workflows:structuredClone(n.runtime_schema_type_workflows)};let i=$y(o,n);t.source!==void 0&&ah(i,t.source.validated);let s=structuredClone(t.source===void 0?n.source_settings:t.source.raw);return Pd(s,i,r),`${JSON.stringify(A(s,ss),null,2)}
105
+ WHERE recency_rank = 1`).all(...a).map(fy);if(c.includes(null))return null;i.push(...c)}return yy(i,r)}):null}async function YU(e,t){let n=[...new Set(t.filter(a=>a.trim().length>0&&z.basename(a)===a))];if(n.length===0)return{};let r=new Set(n),o=Ki(),i=await ry(o,e,n,r);if(i!==null&&i!==ut)return i;if(o&&i!==ut&&!await ay(e))try{if(await BT(e,{lockWaitMs:0})){let a=await ry(o,e,n,r);if(a!==null&&a!==ut)return a}}catch{}let s=[];return await Promise.all(n.map(async a=>{let c=z.join(e,"history",`${a}.jsonl`);(await qT(c,a).catch(d=>{if(d instanceof g&&d.code==="history_timestamp_invalid")return[];throw d})).forEach((d,l)=>{s.push({stream_id:a,stream_offset:l,entry:d})})})),yy(s,r)}import hd from"node:fs/promises";import Fn 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]="687cbe24-6d5c-5322-962d-455048eb84b5")}catch{}})();var rC=Fn.join("runtime","history-drift-cache.json"),hy={EINVAL:"invalid_cache_path",EISDIR:"cache_path_is_directory",ENOENT:"invalid_cache_path",ENOTDIR:"invalid_cache_path",ERR_FS_EISDIR:"cache_path_is_directory"};function gy(e){return typeof e=="object"&&e!==null&&"code"in e&&typeof e.code=="string"?e.code:void 0}async function oC(e){let t=Fn.join(e,rC),n=!1,r="invalid_cache_path";try{n=(await hd.stat(await hd.realpath(e))).isDirectory()}catch(o){let i=gy(o);r=i===void 0?"unknown":hy[i]??"filesystem_error"}if(!n){zr(`[pm] warning: history_drift_cache_invalidation_failed:${r}
106
+ `);return}try{await hd.rm(t,{force:!0})}catch(o){let i=gy(o);if(Q(o))return;let s=i===void 0?"unknown":hy[i]??"filesystem_error";zr(`[pm] warning: history_drift_cache_invalidation_failed:${s}
107
+ `)}}async function Yi(e){let t=Fn.dirname(Fn.resolve(e));Fn.basename(t)==="history"&&await oC(Fn.dirname(t))}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="4a3c3c82-0398-549c-8910-fdc69d971cb2")}catch{}})();var sC={front_matter:{},body:""},Gt=3,Hr=[1,2,3],aC=1,cC=[1];function Sy(e){return Je(R(e),e.hash_algorithm)}function Un(e){return no(R(e))}function bz(e){return no(R(e))}function vd(e){let t={...e,record_hash_version:aC},{record_hash:n,...r}=t;return{...t,record_hash:Sy(r)}}function $i(e){try{Tt(e.hash_algorithm)}catch{return{ok:!1,error:"unsupported_history_hash_algorithm"}}if(e.record_hash_version===void 0&&e.record_hash===void 0)return{ok:!0,coverage:"item_state_only"};if(e.record_hash_version===void 0||e.record_hash===void 0)return{ok:!1,error:"incomplete_record_hash_envelope"};if(!cC.includes(e.record_hash_version))return{ok:!1,error:"unsupported_record_hash_version"};let{record_hash:t,...n}=e;return Sy(n)===e.record_hash?{ok:!0,coverage:"record_and_item_state"}:{ok:!1,error:"record_hash_mismatch"}}function dC(e,t){let n={before_hash:e.before_hash,after_hash:e.after_hash,patch_hash:Un(e.patch)};return e.hash_algorithm!==void 0&&(n.hash_algorithm=e.hash_algorithm),e.item_hash_version!==void 0&&(n.item_hash_version=e.item_hash_version),t.retainOriginalPatch&&(n.patch=structuredClone(e.patch)),t.retainPriorRecordHash!==!1&&e.record_hash_version!==void 0&&e.record_hash!==void 0&&(n.record_hash_version=e.record_hash_version,n.record_hash=e.record_hash,n.record=structuredClone(e)),n}function H_(e,t,n={}){let r=$i(e);if(!r.ok)throw new TypeError(r.error);let o=Un(e.patch),i=n.retainPriorRecord===!0||e.before_hash!==t.before_hash||e.after_hash!==t.after_hash||e.item_hash_version!==t.item_hash_version||e.hash_algorithm!==t.hash_algorithm||o!==Un(t.patch),s=vd({...t,...i?{reanchor_evidence:[...t.reanchor_evidence??[],dC(e,n)]}:{}}),a=od(s);if(!a.ok)throw new TypeError(a.error);return s}function Oy(e){return!Array.isArray(e)||Object.keys(e).length!==e.length?!1:e.every(t=>!Zt(t)||typeof t.path!="string"?!1:t.op==="move"||t.op==="copy"?typeof t.from=="string":["add","replace","test"].includes(t.op)?Object.hasOwn(t,"value"):t.op==="remove")}function lC(e){return Zt(e)&&typeof e.ts=="string"&&typeof e.author=="string"&&typeof e.op=="string"&&typeof e.before_hash=="string"&&typeof e.after_hash=="string"&&Oy(e.patch)}function uC(e){let t=e.record_hash_version!==void 0,n=e.record_hash!==void 0;return t===n}function fC(e){return!Zt(e)||!uC(e)||typeof e.before_hash!="string"||typeof e.after_hash!="string"||typeof e.patch_hash!="string"||!/^[a-f0-9]{64}$/u.test(e.patch_hash)||e.patch!==void 0&&!Oy(e.patch)||e.record_hash_version!==void 0&&typeof e.record_hash_version!="number"||e.record_hash!==void 0&&(typeof e.record_hash!="string"||!/^(?:[a-f0-9]{64}|[a-f0-9]{128})$/u.test(e.record_hash))?!1:e.record===void 0||lC(e.record)}function mC(e){try{for(let t of e){if(!fC(t))return!1;Tt(t.hash_algorithm)}return!0}catch{return!1}}function pC(e){let t=e.record;return t!==void 0&&t.before_hash===e.before_hash&&t.after_hash===e.after_hash&&t.item_hash_version===e.item_hash_version&&t.hash_algorithm===e.hash_algorithm&&t.record_hash_version===e.record_hash_version&&t.record_hash===e.record_hash&&Un(t.patch)===e.patch_hash}function _C(e,t,n){if(t.patch&&Un(t.patch)!==t.patch_hash)return{kind:"patch_hash_mismatch"};if(t.record)return pC(t)?{kind:"record",entry:t.record}:{kind:"record_hash_mismatch"};let r=t.patch??e.patch;if(Un(r)!==t.patch_hash)return{kind:"digest_only"};let o={...e,before_hash:t.before_hash,after_hash:t.after_hash,patch:r,hash_algorithm:t.hash_algorithm,...t.item_hash_version===void 0?{}:{item_hash_version:t.item_hash_version},...t.record_hash_version===void 0?{}:{record_hash_version:t.record_hash_version},...t.record_hash===void 0?{}:{record_hash:t.record_hash},...n.length===0?{}:{reanchor_evidence:n}};return t.hash_algorithm===void 0&&delete o.hash_algorithm,n.length===0&&delete o.reanchor_evidence,t.item_hash_version===void 0&&delete o.item_hash_version,t.record_hash_version===void 0||t.record_hash===void 0?{kind:"legacy",entry:o}:{kind:"record",entry:o}}function od(e){let t=e.reanchor_evidence;if(t===void 0)return{ok:!0,coverage:"none"};if(!Array.isArray(t)||!mC(t))return{ok:!1,error:"rewrite_evidence_invalid"};if(t.length===0)return{ok:!0,coverage:"none"};let n=e;for(let r=t.length-1;r>=0;r-=1){let o=t[r],i=_C(n,o,t.slice(0,r));if(i.kind==="patch_hash_mismatch")return{ok:!1,error:"rewrite_evidence_patch_hash_mismatch"};if(i.kind==="record_hash_mismatch")return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};if(i.kind==="digest_only")return{ok:!0,coverage:"digest_only"};if(i.kind==="legacy")return{ok:!0,coverage:"legacy_anchor_only"};if(!$i(i.entry).ok)return{ok:!1,error:"rewrite_evidence_record_hash_mismatch"};n=i.entry}return{ok:!0,coverage:"complete"}}function Xi(e,t){return(e??"").localeCompare(t??"")}function wy(e,t){return(e??0)-(t??0)}function ft(e,t,n){return JSON.stringify(e??n).localeCompare(JSON.stringify(t??n))}function yC(e,t){return[e.scope.localeCompare(t.scope),Xi(e.path,t.path),Xi(e.command,t.command),wy(e.timeout_seconds,t.timeout_seconds),Xi(e.pm_context_mode,t.pm_context_mode),+!!e.shared_host_safe-+!!t.shared_host_safe,ft(e.env_clear,t.env_clear,[]),ft(e.env_set,t.env_set,{}),ft(e.assert_stdout_contains,t.assert_stdout_contains,[]),ft(e.assert_stdout_regex,t.assert_stdout_regex,[]),ft(e.assert_stderr_contains,t.assert_stderr_contains,[]),ft(e.assert_stderr_regex,t.assert_stderr_regex,[]),wy(e.assert_stdout_min_lines,t.assert_stdout_min_lines),ft(e.assert_json_field_equals,t.assert_json_field_equals,{}),ft(e.assert_json_field_gte,t.assert_json_field_gte,{}),Xi(e.note,t.note)].find(n=>n!==0)??0}function hC(e){return!e||e==="/"?[]:e.startsWith("/")?e.slice(1).split("/").map(t=>t.replaceAll("~1","/").replaceAll("~0","~")):[]}function gC(e,t){let n=hC(t);if(n.length===0)return!0;let r=e;for(let o of n){let i=/^(0|[1-9]\d*)$/.test(o)?Number(o):-1,s=Array.isArray(r)?i>=0&&i<r.length?r[i]:void 0:Zt(r)&&Object.prototype.hasOwnProperty.call(r,o)?r[o]:void 0;if(s===void 0)return!1;r=s}return!0}function bC(e,t){let n=[],r=structuredClone(e);for(let o of t){let i=o.op==="replace"&&!gC(r,o.path)?{...o,op:"add"}:o;n.push(i),r=ky.applyPatch(r,[i],!0,!0).newDocument}return n}function Ji(e,t,n=!1){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{front_matter:{},body:e.body??""};let r=On(e),o=t===1||t===2&&n?{...r.metadata,...r.metadata.dependencies===void 0?{}:{dependencies:r.metadata.dependencies.map(s=>({...s,id:s.id.toLowerCase()}))},...r.metadata.tests===void 0?{}:{tests:r.metadata.tests.map(({workspace_context_mode:s,provenance:a,provenance_invalid:c,...d})=>d)},...r.metadata.test_runs===void 0?{}:{test_runs:r.metadata.test_runs.map(({executions:s,...a})=>a)}}:r.metadata,i=t===1&&o.tests?{...o,tests:[...o.tests].sort(yC)}:o;return{front_matter:A(i,Ve),body:r.body}}function vy(e){if(!(e.metadata&&Object.keys(e.metadata).length>0))return{metadata:{},body:e.body??""};let t=On(e);return{metadata:A(t.metadata,Ve),body:t.body}}function wz(e){return Ay(e,Gt)}function Ay(e,t,n){if(!Hr.some(r=>r===t))throw new TypeError(`unsupported_item_hash_version:${String(t)}`);return Je(R(Ji(e,t)),n)}function q_(e,t,n){let r=Ay(e,t,n);return t===2?[r,Je(R(Ji(e,t,!0)),n)]:[r]}function vz(){return no(R(sC))}function Vr(e){let t=sm(e.op),n=Ji(e.before,Gt),r=Ji(e.after,Gt),o=vy(e.before),i=vy(e.after),s=ky.compare(o,i),a=bC(o,s),c=Wm(e.author),d=c.harness?Object.fromEntries(Object.entries(Vm().provenance_outcomes).filter(([m,_])=>_.resolver!==void 0&&(_.status!=="resolved"||c.provenance?.[m]?.source==="probe"))):void 0,l=d===void 0||Object.keys(d).length===0?e.context:{...e.context,agent_provenance_outcomes:d},u=e.hashAlgorithm??gf,f={hash_algorithm:u,ts:e.nowIso,author:e.author,author_source:e.authorSource??Bm(e.author),...c.harness?{agent_harness:c.harness}:{},...c.model?{agent_model:c.model}:{},...c.model_source?{agent_model_source:c.model_source}:{},...c.instance?{agent_instance:c.instance}:{},...c.provenance?{agent_provenance:c.provenance}:{},...c.episode?{agent_episode:c.episode}:{},op:t,patch:a,before_hash:Je(R(n),u),after_hash:Je(R(r),u),item_hash_version:Gt,message:e.message===void 0?void 0:e.message,...l===void 0?{}:{context:l}};return vd({...f,event_class:Cn(f)})}function Zt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function gd(e){return new g(e,h.GENERIC_FAILURE,{code:"history_timestamp_invalid"})}function Iy(e){let t=e.ts.trim();if(t.length===0)return Te();if(!un(t))throw gd("History timestamp must be a valid RFC 3339 date-time with millisecond precision");if(t!==e.ts)throw gd("History timestamp must not contain surrounding whitespace");return e.ts}function Ey(e,t){let n=e.ts;if(typeof n=="string"&&n.trim().length>0){if(!un(n))throw gd("History timestamp must be a valid RFC 3339 date-time with millisecond precision");return e}return{...e,ts:t}}function bd(e,t){let n=Iy(t);if(typeof e=="string"){let r;try{r=JSON.parse(e)}catch{return e}return Zt(r)?JSON.stringify(Ey(r,n)):e}return Zt(e)?JSON.stringify(Ey(e,n)):JSON.stringify(e)}async function wC(e,t,n){if(n===!1)return!0;if(typeof n=="string"){let s=bd(n,t);return await wd(e,s),await Yi(e),await _d(e),!0}if(typeof n!="object"||n===null)return!1;let r=n;if(r.skip===!0)return!0;let o=typeof r.history_path=="string"?r.history_path:e,i=bd(typeof r.line=="string"?r.line:r.entry??t,t);return await wd(o,i),await Yi(o),await _d(o),!0}async function wd(e,t){let n;try{n=JSON.parse(t)}catch{n=null}if(!Zt(n)||n.op!=="create"){await Qd(e,t);return}await by.mkdir(iC.dirname(e),{recursive:!0});try{await by.writeFile(e,`${t}
108
+ `,{encoding:"utf8",flag:"wx"})}catch(r){throw r.code!=="EEXIST"?r:new g("This item identity is reserved by an existing history stream.",h.CONFLICT,{code:"item_identity_reserved",required:"Choose a new item ID or restore the original item from its history.",nextSteps:["Run pm history <id> --full, then pm restore <id> <version> to recover the original item."]})}}async function Br(e,t){let n=await wn("history_append",{history_path:e,entry:t});if(n.handled&&await wC(e,t,n.result))return;let r=t.ts.trim().length>0?t:{...t,ts:Iy(t)},o=vd({...r,hash_algorithm:Tt(r.hash_algorithm),event_class:Cn(r)});await py(e,o,async()=>{await wd(e,bd(o,o))}),await Yi(e)}import Ty from"node:fs/promises";import zn 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]="af606b47-d071-5724-b1e7-de4e1e5d7385")}catch{}})();var mt="_workspace";function Qt(e){return zn.join(e,"history",`${mt}.jsonl`)}function Ed(e,t){return{metadata:{id:mt,title:"Workspace state",description:"Audited singleton workspace document state.",type:"Chore",status:"open",priority:2,tags:["workspace-history"],created_at:t,updated_at:t,documents:e},body:""}}function en(e,t=e.length){let n=ji();for(let r of e.slice(0,t))n=Fi(n,r.patch).document;return Li(n)}function Hn(e){return"documents"in e.metadata&&typeof e.metadata.documents=="object"&&e.metadata.documents!==null&&!Array.isArray(e.metadata.documents)?e.metadata.documents:{}}function qn(e){throw new g(`Workspace history verification failed: ${e.join(", ")}`,h.CONFLICT,{code:"workspace_history_chain_invalid",reason:"workspace_history_chain_verification_failed",verification_errors:[...e],required:"Repair the _workspace history chain before reading, reconciling, restoring, or appending audited singleton state.",why:"Continuing against an unverifiable append-only stream could hide or compound workspace state corruption.",examples:["pm history _workspace --verify --json","pm validate --check-history-drift --fix-hints --json"],nextSteps:["Inspect the exact verification_errors and preserve the corrupt stream as evidence.","Use the history-drift remediation returned by validate before retrying the refused operation."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify --json"}})}function Zi(e,t){let n=zn.resolve(t),r=zn.relative(e,n).replaceAll("\\","/");if(r.length===0||r===".."||r.startsWith("../")||zn.isAbsolute(r))throw new TypeError("Workspace history document path must stay inside the tracker root");return{documentPath:r,absolutePath:n}}async function Pz(e){let t=await Mt(Qt(e),mt),n=Kt(t);n.ok||qn(n.errors);let r=Hn(t.length===0?Wn:en(t)),o=[],i=[],s=[],a=[];for(let c of Object.keys(r).sort()){let d;try{let l=Zi(e,zn.resolve(e,c));if(d=await Ae(l.absolutePath),d===null){s.push(c);continue}let u=JSON.parse(d);(R(u)===R(r[c])?o:i).push(c)}catch{a.push(c)}}return{ok:i.length===0&&s.length===0&&a.length===0,document_count:Object.keys(r).length,matching_documents:o,mismatched_documents:i,missing_documents:s,unreadable_documents:a}}async function Cy(e){let t=Qt(e.pmRoot),n=await Mt(t,mt),r=Kt(n);r.ok||qn(r.errors);let o=e.idempotencyKey===void 0?void 0:n.find(u=>u.op===`${e.op}:${e.idempotencyKey}`);if(o)return{entry:o,historyPath:t};let i=Te(),s=n.length===0?Wn:en(n),a=Hn(s),c=a[e.documentPath];if(c!==void 0&&R(c)!==R(e.before))throw new g(`Workspace history state for "${e.documentPath}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict",reason:"out_of_band_workspace_state",required:"Reconcile the singleton document with its matching _workspace history state before retrying the mutation.",why:"Accepting the write would make the append-only audit stream describe a state that was not actually observed.",examples:["pm history _workspace --verify","pm validate --check-history-drift --fix-hints"],nextSteps:["Review the version-control change that altered the singleton and preserve the intended document plus its matching workspace history.","Rerun the original mutation only after the on-disk singleton agrees with the latest audited workspace state."],recovery:{recovery_mode:"compact",next_best_command:"pm history _workspace --verify"}});let d=Ed({...a,[e.documentPath]:e.after},n.length===0?i:s.metadata.created_at),l=Vr({nowIso:i,author:e.author,op:e.idempotencyKey===void 0?e.op:`${e.op}:${e.idempotencyKey}`,before:s,after:d,message:e.message});return await Br(t,l),{entry:l,historyPath:t}}async function Mz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Cy(e)}finally{await t()}}async function $z(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let n=Qt(e.pmRoot),r=await Mt(n,mt),o=Kt(r);o.ok||qn(o.errors);let i=r.length===0?Wn:en(r),s=Vr({nowIso:Te(),author:e.author,op:e.op,before:i,after:i,message:e.message,context:e.context});return await Br(n,s),{entry:s,historyPath:n}}finally{await t()}}async function Ry(e,t){if(t===e.raw)return!1;let n=t===null?null:JSON.parse(t),r=JSON.parse(e.raw);await bt(e.filePath,e.raw);try{(t!==null||e.recordCreation!==!1)&&await Cy({pmRoot:e.pmRoot,documentPath:zn.relative(e.pmRoot,e.filePath).replaceAll("\\","/"),before:n,after:r,op:e.op,idempotencyKey:e.idempotencyKey,author:e.author,lockTtlSeconds:e.lockTtlSeconds,lockWaitMs:e.lockWaitMs,message:e.message})}catch(o){throw t===null?await Ty.rm(e.filePath,{force:!0}):await bt(e.filePath,t),o}return!0}async function xy(e){let{documentPath:t}=Zi(e.pmRoot,e.filePath),n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let r=await Ae(e.filePath);if(e.dryRun===!0||e.idempotencyKey!==void 0){let i=await Mt(Qt(e.pmRoot),mt),s=Kt(i);s.ok||qn(s.errors);let a=Hn(i.length===0?Wn:en(i))[t];if(a!==void 0&&R(a)!==R(r===null?null:JSON.parse(r)))throw new g(`Workspace history state for "${t}" changed outside the audited mutation path.`,h.CONFLICT,{code:"workspace_history_state_conflict"});if(e.idempotencyKey!==void 0&&i.some(c=>c.op===`${e.op}:${e.idempotencyKey}`))return{changed:!1,result:void 0,replayed:!0}}let o=await e.mutate(r);return JSON.parse(o.raw),e.dryRun===!0?{changed:r!==o.raw,result:o.result}:{changed:await Ry({...e,raw:o.raw},r),result:o.result}}finally{await n()}}async function jz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{return await Ry(e,await Ae(e.filePath))}finally{await t()}}async function Lz(e){let t=e.authorizationDecision.trim();if(!t)throw new TypeError("Workspace history reconciliation requires an authorization decision");let n=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:r,absolutePath:o}=Zi(e.pmRoot,e.filePath),i=Qt(e.pmRoot),s=await Mt(i,mt),a=Kt(s);a.ok||qn(a.errors);let c=en(s),d=Hn(c);if(!Object.hasOwn(d,r))throw new TypeError(`Workspace history does not govern document ${r}`);let l=await Ae(o);if(l===null)throw new TypeError(`Workspace history document is missing: ${r}`);let u=JSON.parse(l);if(R(d[r])===R(u))return{changed:!1,historyPath:i};let f=Te(),m=Vr({nowIso:f,author:e.author,op:e.op,before:c,after:Ed({...d,[r]:u},c.metadata.created_at),message:e.message,context:{reason:"out_of_band_workspace_state_reconciliation",document_path:r,authorization_decision:t}});return await Br(i,m),{changed:!0,entry:m,historyPath:i}}finally{await n()}}async function Fz(e){let t=await fe(e.pmRoot,"workspace-history",e.lockTtlSeconds,e.author,!1,!1,e.lockWaitMs);try{let{documentPath:n,absolutePath:r}=Zi(e.pmRoot,e.filePath),o=await Mt(Qt(e.pmRoot),mt),i=Kt(o);if(i.ok||qn(i.errors),!Number.isInteger(e.targetVersion)||e.targetVersion<1||e.targetVersion>o.length)throw new TypeError(`Invalid workspace history target version: ${String(e.targetVersion)}`);let s=Hn(en(o,e.targetVersion))[n];if(s===void 0)throw new TypeError(`Workspace history version ${e.targetVersion} does not contain ${n}`);let a=await Ae(r),c=`${JSON.stringify(s,null,2)}
109
+ `;if(a===c)return{document_path:n,restored_from_version:e.targetVersion,changed:!1};let d=en(o),l=Te(),u=Vr({nowIso:l,author:e.author,op:e.op,before:d,after:Ed({...Hn(d),[n]:s},d.metadata.created_at),message:e.message,context:{reason:"workspace_state_restore",document_path:n,restored_from_version:e.targetVersion,replaced_out_of_band_state:!0}});await bt(r,c);try{await Br(Qt(e.pmRoot),u)}catch(f){throw a===null?await Ty.rm(r,{force:!0}):await bt(r,a),f}return{document_path:n,restored_from_version:e.targetVersion,changed:!0}}finally{await t()}}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78651211-fe4b-564e-a872-23bf25265243")}catch{}})();var Pe={ok:!1,path:[]};function Sd(e,t){return{ok:!1,path:[e,...t.path]}}var w=e=>typeof e=="string"?{ok:!0,value:e}:Pe,N=e=>typeof e=="boolean"?{ok:!0,value:e}:Pe;function F(e={}){return t=>typeof t!="number"||!Number.isFinite(t)||e.int&&(!Number.isInteger(t)||!Number.isSafeInteger(t))||e.positive&&t<=0||typeof e.min=="number"&&t<e.min||typeof e.max=="number"&&t>e.max?Pe:{ok:!0,value:t}}function D(...e){return t=>typeof t=="string"&&e.includes(t)?{ok:!0,value:t}:Pe}function k(e,t){return n=>{if(!Array.isArray(n)||t!==void 0&&n.length>t)return Pe;let r=[];for(let[o,i]of n.entries()){let s=e(i);if(!s.ok)return Sd(String(o),s);r.push(s.value)}return{ok:!0,value:r}}}function Od(e,t){return n=>typeof n=="string"&&n.length>0&&n.length<=e&&n===n.trim()&&(t===void 0||t.test(n))?{ok:!0,value:n}:Pe}function p(e){return t=>t===void 0?{ok:!0,value:void 0}:e(t)}function Qi(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Pe;let n={};for(let[r,o]of Object.entries(t)){let i=e(o);if(!i.ok)return Sd(r,i);n[r]=i.value}return{ok:!0,value:n}}}function I(e){return t=>{if(typeof t!="object"||t===null||Array.isArray(t))return Pe;let n=t,r={};for(let[o,i]of Object.entries(e)){let s=i(n[o]);if(!s.ok)return Sd(o,s);s.value!==void 0&&(r[o]=s.value)}return{ok:!0,value:r}}}var vC=I({key:w,values:k(w),required:p(N),aliases:p(k(w)),description:p(w)}),EC=I({command:D("create","update"),option:w,required:p(N),visible:p(N),enabled:p(N)}),kC=I({name:w,description:p(w),default_status:p(w),execution_role:p(D("agent","human","gate")),folder:p(w),aliases:p(k(w)),required_create_fields:p(k(w)),required_create_repeatables:p(k(w)),options:p(k(vC)),command_option_policies:p(k(EC))}),SC=I({id:w,aliases:p(k(w)),roles:p(k(D(...so))),description:p(w),order:p(F())}),OC=I({key:w,metadata_key:p(w),front_matter_key:p(w),cli_flag:p(w),cli_aliases:p(k(w)),description:p(w),type:p(D(...cn)),commands:p(k(D(...ao))),repeatable:p(N),required:p(N),required_on_create:p(N),required_types:p(k(w)),allow_unset:p(N)}),AC=e=>{if(!Array.isArray(e)||e.length!==2)return Pe;let[t,n]=e;return typeof t!="string"||typeof n!="string"?Pe:{ok:!0,value:[t,n]}},IC=I({type:w,allowed_transitions:k(AC)}),TC=p(I({version:p(F({int:!0})),files:p(I({types:p(w),statuses:p(w),fields:p(w),workflows:p(w)})),statuses:p(k(SC)),fields:p(k(OC)),workflow:p(I({draft_status:p(w),open_status:p(w),in_progress_status:p(w),blocked_status:p(w),close_status:p(w),canceled_status:p(w)})),type_workflows:p(k(IC)),unknown_field_policy:p(D(...co))})),CC=p(I({preset:p(D(...al)),ownership_enforcement:p(D("none","warn","strict")),create_mode_default:p(D("progressive","strict")),close_validation_default:p(D("off","warn","strict")),require_close_reason:p(N),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),force_required_for_stale_lock:p(N),create_default_type:p(w),workflow_enforcement:p(D("off","warn","strict")),start_blocker_enforcement:p(D("off","warn","strict")),duplicate_detection_mode:p(D("off","advisory","strict")),duplicate_detection_threshold:p(F({min:0,max:1})),duplicate_detection_limit:p(F({int:!0,min:0,max:20}))})),RC=I({name:w,disabled:p(N),require_trusted:p(N),require_provenance:p(N),sandbox_profile:p(D("none","restricted","strict")),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w))}),kd=D("block","warn"),xC=e=>typeof e=="string"?kd(e):I({global:p(kd),project:p(kd)})(e),NC=p(I({mode:p(D("off","warn","enforce")),trust_mode:p(D("off","warn","enforce")),pm_max_version_exceeded_mode:p(xC),require_provenance:p(N),trusted_extensions:p(k(w)),default_sandbox_profile:p(D("none","restricted","strict")),allowed_extensions:p(k(w)),blocked_extensions:p(k(w)),allowed_capabilities:p(k(w)),blocked_capabilities:p(k(w)),allowed_surfaces:p(k(w)),blocked_surfaces:p(k(w)),allowed_commands:p(k(w)),blocked_commands:p(k(w)),allowed_actions:p(k(w)),blocked_actions:p(k(w)),allowed_services:p(k(w)),blocked_services:p(k(w)),extension_overrides:p(k(RC))})),tn=Od(128),DC=I({harness:Od(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u),environment_keys:p(k(tn,64)),model_environment_keys:p(k(tn,64)),session_environment_keys:p(k(tn,64)),provenance_environment_keys:p(Qi(k(tn,64))),provenance_resolvers:p(Qi(D("ai_agent_version","claude_session_file"))),provenance_unavailable_dimensions:p(k(tn,64)),argv_markers:p(k(tn,64)),client_names:p(k(tn,64))}),Ny={version:F({int:!0}),id_prefix:w,ids:p(I({token_length:p(F({int:!0,min:4,max:12}))})),author_default:w,agent_identity:p(I({probes_enabled:p(N),identity_vocabulary:p(I({version:F({int:!0,positive:!0}),aliases:Qi(Od(128,/^[a-z0-9]+(?:-[a-z0-9]+)*$/u))})),harness_signals:k(DC)})),mutation_guard:p(I({require_attributed_author:p(N),secret_guard:p(D("off","advise","block")),stale_in_progress_hours:p(F({int:!0,positive:!0}))})),item_format:p(D("toon","json_markdown")),locks:I({ttl_seconds:F({int:!0}),wait_ms:p(F({int:!0,min:0}))}),checkpoints:p(I({retention_days:p(F({int:!0,positive:!0}))})),output:I({default_format:D("toon","json")}),ux:p(I({deprecation_hints:p(N)})),history:p(I({missing_stream:D("auto_create","strict_error"),compact_policy:p(I({enabled:p(N),max_entries:p(F({int:!0,positive:!0})),trigger:p(D("health_warn","auto"))}))})),validation:p(I({sprint_release_format:D("warn","strict_error"),parent_reference:p(D("warn","strict_error")),metadata_profile:p(D("core","strict","custom")),metadata_required_fields:p(k(w)),lifecycle_stale_blocker_reason_patterns:p(k(w)),lifecycle_closure_like_blocked_reason_patterns:p(k(w)),lifecycle_closure_like_resolution_patterns:p(k(w)),lifecycle_closure_like_actual_result_patterns:p(k(w)),estimate_defaults_by_type:p(Qi(F({int:!0,positive:!0})))})),governance:CC,workflow:p(I({definition_of_done:k(w)})),testing:p(I({record_results_to_items:N,allow_untrusted_linked_tests:p(N)})),telemetry:p(I({enabled:N,first_run_prompt_completed:p(N),capture_level:p(D("minimal","redacted","max")),endpoint:p(w),installation_id:p(w),retention_days:p(F({int:!0,positive:!0}))})),agent_guidance:p(I({prompt_completed:p(N),declined:p(N),declined_at:p(w),template_version:p(F({int:!0,positive:!0})),last_checked_files:p(k(w))})),item_types:p(I({definitions:k(kC)})),schema:TC,context:p(I({default_depth:p(D(...ll)),activity_limit:p(F({int:!0,positive:!0})),stale_threshold_days:p(F({int:!0,positive:!0})),next_ranking_policy:p(D("priority_floor","weighted")),sections:p(I({hierarchy:p(N),activity:p(N),progress:p(N),recently_created:p(N),unparented:p(N),blockers:p(N),files:p(N),workload:p(N),staleness:p(N),tests:p(N)}))})),extensions:I({enabled:k(w),disabled:k(w),policy:NC}),search:I({score_threshold:F(),hybrid_semantic_weight:p(F()),max_results:F({int:!0}),embedding_model:w,embedding_corpus_max_characters:p(F()),embedding_batch_size:F({int:!0}),embedding_timeout_ms:p(F({int:!0})),scanner_max_batch_retries:F({int:!0}),provider:p(w),default_mode:p(D("auto","keyword","semantic","hybrid")),corpus_fields:p(k(w)),mutation_refresh_policy:p(D("cache_only","semantic_configured","semantic_auto")),query_expansion:p(I({enabled:p(N),provider:p(w)})),rerank:p(I({enabled:p(N),model:p(w),top_k:p(F({int:!0,positive:!0}))})),bm25:p(I({k1:p(F()),b:p(F())}))}),providers:I({openai:I({base_url:w,api_key:w,model:w}),ollama:I({base_url:w,model:w})}),vector_store:I({adapter:p(w),collection_name:p(w),qdrant:I({url:w,api_key:w}),lancedb:I({path:w})})},PC=I(Ny),Dy=Object.freeze(Object.keys(Ny));function es(e){let t=PC(e);return t.ok?{success:!0,data:t.value}:{success:!1,path:t.path.join(".")}}import{AsyncLocalStorage as UC}from"node:async_hooks";import{lstat as zC,realpath as Vy}from"node:fs/promises";import By 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]="a0ca9902-540c-50fe-a4e2-9c234c4a01f3")}catch{}})();function ts(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ad(e,t,n,r=[]){if(B(e,t)&&(r.length>0||ts(n)))return n;if(B(e,n)||B(t,n))return t;if((e===void 0||ts(e))&&ts(t)&&ts(n)){let o=e??{},i=new Set([...Object.keys(o),...Object.keys(t),...Object.keys(n)]);return Object.fromEntries([...i].flatMap(s=>{let a=Ad(Object.hasOwn(o,s)?o[s]:void 0,Object.hasOwn(t,s)?t[s]:void 0,Object.hasOwn(n,s)?n[s]:void 0,[...r,s]);return a===void 0?[]:[[s,a]]}))}throw new g(`Settings changed concurrently at ${r.join(".")||"<root>"}; read the latest settings and reapply the intended change.`,h.CONFLICT,{reason:"stale_settings_snapshot",required:"Read a fresh settings snapshot and reapply the intended change.",why:"Another writer changed the same setting after this snapshot was read.",examples:["pm config project export --json"],nextSteps:["Read the current settings, then retry the original config operation."]})}(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]="de43e8e6-d7ef-53cc-94b0-ccdf1c4f94a3")}catch{}})();var MC={Epic:2880,Feature:480,Story:480,Milestone:2880,Task:120,Issue:60,Bug:60,Chore:30,Decision:15,Plan:120},Py=120;function Id(e){return typeof e=="number"&&Number.isFinite(e)&&e>0}function $y(e){let t=new Map;for(let[n,r]of Object.entries(e))t.set(n.toLowerCase(),r);return t}var $C=$y(MC),My=new WeakMap;function jC(e){let t=My.get(e);if(t)return t;let n=$y(e);return My.set(e,n),n}function Gz(e,t){let n=(e??"").trim().toLowerCase();if(n.length===0)return Py;if(t){let o=jC(t).get(n);if(Id(o))return Math.floor(o)}let r=$C.get(n);return Id(r)?Math.floor(r):Py}function Td(e){let t={};if(e===null||typeof e!="object"||Array.isArray(e))return t;for(let[n,r]of Object.entries(e)){let o=n.trim();o.length===0||!Id(r)||(t[o]=Math.floor(r))}return t}import{stat as LC}from"node:fs/promises";(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="78c79deb-5cf0-54fe-b98c-a0d5b3671ab2")}catch{}})();var ns=new Map;function jy(e){return[...new Set(e.map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}async function FC(e){try{let t=await LC(e);return{path:e,mtime_ms:t.mtimeMs,size:t.size}}catch{return{path:e,mtime_ms:null,size:null}}}async function pt(e){let t=jy(e),n=await Promise.all(t.map(r=>FC(r)));return n.sort((r,o)=>r.path.localeCompare(o.path)),n}function Wr(e,t){if(e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1){let r=e[n],o=t[n];if(r.path!==o.path||r.mtime_ms!==o.mtime_ms||r.size!==o.size)return!1}return!0}function Ly(e){return ns.get(e)}function rs(e,t){let n=jy(t.tracked_paths),r=[...t.signatures].map(o=>({path:o.path,mtime_ms:o.mtime_ms,size:o.size})).sort((o,i)=>o.path.localeCompare(i.path));ns.set(e,{tracked_paths:n,signatures:r,value:t.value})}function nn(e){if(e){ns.delete(e);return}ns.clear()}(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]="6e01cb2d-2ff0-54f2-abdb-2d16f36487c1")}catch{}})();var Nd=new UC;async function _2(e,t,n=()=>!0){let r=new Set([By.resolve(e)]);try{r.add(await Vy(e))}catch{}return Nd.run([...Nd.getStore()??[],[r,n]],t)}function HC(e){let t=By.resolve(e);return Nd.getStore()?.some(([n,r])=>n.has(t)&&r())??!1}var qC="settings:write",Wy=Symbol("pm.settings.persist_source"),Gy=Symbol("pm.settings.fallback_origin"),Ky=Symbol("pm.settings.fallback_baseline"),VC=128,BC=new Set(["off","advisory","strict"]);function Fy(e){return structuredClone(Jd[e])}function WC(e){return e==="minimal"||e==="default"||e==="strict"||e==="custom"?e:S.governance.preset}var GC=new Set(cl);function Yy(e){return GC.has(e)}function Uy(e,t){let n=typeof t.create_default_type=="string"?t.create_default_type.trim():void 0;return n&&n.length>0&&(e.create_default_type=n),(t.workflow_enforcement==="off"||t.workflow_enforcement==="warn"||t.workflow_enforcement==="strict")&&(e.workflow_enforcement=t.workflow_enforcement),Yy(t.start_blocker_enforcement)&&(e.start_blocker_enforcement=t.start_blocker_enforcement),t.require_close_reason===!1&&(e.require_close_reason=!1),e.duplicate_detection_mode=t.duplicate_detection_mode,e.duplicate_detection_threshold=t.duplicate_detection_threshold,e.duplicate_detection_limit=t.duplicate_detection_limit,e}function KC(e){return e.preset==="custom"?Uy({preset:"custom",ownership_enforcement:e.ownership_enforcement,create_mode_default:e.create_mode_default,close_validation_default:e.close_validation_default,parent_reference:e.parent_reference,metadata_profile:e.metadata_profile,force_required_for_stale_lock:e.force_required_for_stale_lock},e):Uy({preset:e.preset},e)}function YC(e){let t=typeof e.create_default_type=="string"?e.create_default_type.trim():void 0,n={};t&&t.length>0&&(n.create_default_type=t),(e.workflow_enforcement==="off"||e.workflow_enforcement==="warn"||e.workflow_enforcement==="strict")&&(n.workflow_enforcement=e.workflow_enforcement),Yy(e.start_blocker_enforcement)&&(n.start_blocker_enforcement=e.start_blocker_enforcement),typeof e.require_close_reason=="boolean"&&(n.require_close_reason=e.require_close_reason),BC.has(String(e.duplicate_detection_mode))&&(n.duplicate_detection_mode=e.duplicate_detection_mode);let r=e.duplicate_detection_threshold;[typeof r=="number",Number.isFinite(r),Number(r)>=0,Number(r)<=1].every(Boolean)&&(n.duplicate_detection_threshold=r);let o=e.duplicate_detection_limit;return[typeof o=="number",Number.isSafeInteger(o),Number(o)>=0,Number(o)<=20].every(Boolean)&&(n.duplicate_detection_limit=o),n}function Xy(e){let t=e.governance??{},n=WC(t.preset),r=YC(t);if(n==="custom"){let s=Fy("default"),a=r.require_close_reason??s.require_close_reason;return{preset:n,ownership_enforcement:t.ownership_enforcement??s.ownership_enforcement,create_mode_default:t.create_mode_default??s.create_mode_default,close_validation_default:t.close_validation_default??s.close_validation_default,parent_reference:t.parent_reference??s.parent_reference,metadata_profile:t.metadata_profile??s.metadata_profile,force_required_for_stale_lock:t.force_required_for_stale_lock??s.force_required_for_stale_lock,...r,require_close_reason:a,duplicate_detection_mode:r.duplicate_detection_mode??s.duplicate_detection_mode,duplicate_detection_threshold:r.duplicate_detection_threshold??s.duplicate_detection_threshold,duplicate_detection_limit:r.duplicate_detection_limit??s.duplicate_detection_limit}}let o=Fy(n),i=r.require_close_reason??o.require_close_reason;return{preset:n,...o,...r,require_close_reason:i}}function Md(){return structuredClone(S)}function Jy(e){return e==="cache_only"||e==="semantic_configured"||e==="semantic_auto"?e:S.search.mutation_refresh_policy}function Zy(e){return e==="auto"||e==="keyword"||e==="semantic"||e==="hybrid"?e:"auto"}function Qy(e){return typeof e=="boolean"?e:S.search.query_expansion.enabled}function eh(e){return typeof e!="string"?S.search.query_expansion.provider:e.trim()}function th(e){return typeof e=="boolean"?e:S.search.rerank.enabled}function nh(e){return typeof e!="string"?S.search.rerank.model:e.trim()}function rh(e){return typeof e=="number"&&Number.isFinite(e)&&Number.isInteger(e)&&e>0?e:S.search.rerank.top_k}function oh(e){if(typeof e!="string")return S.vector_store.collection_name;let t=e.trim().replaceAll(/[^a-zA-Z0-9_-]/g,"_").slice(0,VC);return t.length>0?t:S.vector_store.collection_name}function Cd(e){return{present:Array.isArray(e),values:Array.isArray(e)?structuredClone(e):[]}}function ih(e,t){let n=e.schema,r=Cd(n?.statuses),o=Cd(n?.fields),i=Cd(n?.type_workflows);return{persisted_settings:structuredClone(e),source_settings:structuredClone(e),has_source_item_type_definitions:Array.isArray(e.item_types?.definitions),source_item_type_definitions:Vn(e.item_types?.definitions),has_source_schema_statuses:r.present,source_schema_statuses:r.values,has_source_schema_fields:o.present,source_schema_fields:o.values,has_source_schema_type_workflows:i.present,source_schema_type_workflows:i.values,runtime_item_type_definitions:Vn(t.item_types?.definitions),runtime_schema_statuses:structuredClone(t.schema.statuses),runtime_schema_fields:structuredClone(t.schema.fields),runtime_schema_type_workflows:structuredClone(t.schema.type_workflows??[])}}function ss(e,t){Object.defineProperty(e,Wy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function $d(e){let t=e[Wy];if(!(!t||typeof t!="object"))return t}function y2(e){let t=$d(e);if(t){let n=structuredClone(t);n.source_settings.item_format=e.item_format,ss(e,n)}}function os(e){let t=structuredClone(e.settings),n=$d(e.settings);n&&ss(t,n);let r=jd(e.settings);return r!==void 0&&sh(t,r),{settings:t,metadata:{has_explicit_item_format:e.metadata.has_explicit_item_format},warnings:[...e.warnings]}}function XC(e,t,n){let r=Ce(t);return[n,ue(e,r.files.types,ie.types),ue(e,r.files.statuses,ie.statuses),ue(e,r.files.fields,ie.fields),ue(e,r.files.workflows,ie.workflows)]}async function JC(e,t,n){let r=await pt(t);rs(e,{tracked_paths:t,signatures:r,value:os(n)})}async function ZC(e,t,n){try{await JC(e,t,n)}catch{nn(e)}}function zy(e,t){return e.find(n=>n.path===t)}function QC(e,t,n){for(let r of n){let o=zy(e,r),i=zy(t,r);if(!o||!i||!Wr([o],[i]))return!1}return!0}async function Rd(e,t,n,r,o){try{let i=await pt(t);if(!QC(r,i,o)){nn(e);return}rs(e,{tracked_paths:t,signatures:i,value:os(n)})}catch{nn(e)}}function eR(e,t){let n=Ce(e.schema),r=Vn(e.item_types?.definitions);if(!t)return{item_type_definitions:r,schema_statuses:n.statuses,schema_fields:n.fields,schema_type_workflows:n.type_workflows};let o=n.type_workflows??[],i=B(r,t.runtime_item_type_definitions),s=B(n.statuses,t.runtime_schema_statuses),a=B(n.fields,t.runtime_schema_fields),c=B(o,t.runtime_schema_type_workflows);return{item_type_definitions:i?t.has_source_item_type_definitions?Vn(t.source_item_type_definitions):[]:r,schema_statuses:s?t.has_source_schema_statuses?structuredClone(t.source_schema_statuses):[]:n.statuses,schema_fields:a?t.has_source_schema_fields?structuredClone(t.source_schema_fields):[]:n.fields,schema_type_workflows:c?t.has_source_schema_type_workflows?structuredClone(t.source_schema_type_workflows):void 0:n.type_workflows}}function sh(e,t){Object.defineProperty(e,Gy,{value:t,writable:!0,configurable:!0,enumerable:!1})}function h2(e){return jd(e)!==void 0}function jd(e){let t=e[Gy];return typeof t=="string"?t:void 0}function tR(e){return e[Ky]}function nR(e,t){Object.defineProperty(e,Ky,{value:t,writable:!0,configurable:!0,enumerable:!1})}function Me(e){let t=Md();return e!==void 0&&sh(t,e),{settings:t,metadata:{has_explicit_item_format:!1},warnings:e?[e]:[]}}function ah(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e.item_format;return t==="toon"||t==="json_markdown"}function Dd(e){return[...new Set((e??[]).map(t=>t.trim()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function ch(e){let t=S.agent_guidance,n=e?.template_version;return{prompt_completed:e?.prompt_completed===!0,declined:e?.declined===!0,declined_at:typeof e?.declined_at=="string"?e.declined_at:t.declined_at,template_version:typeof n=="number"&&Number.isInteger(n)&&n>0?n:t.template_version,last_checked_files:Dd(e?.last_checked_files??t.last_checked_files)}}function Oe(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function rR(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.mode}function oR(e){return e==="off"||e==="warn"||e==="enforce"?e:S.extensions.policy.trust_mode}function dh(e){return e==="none"||e==="restricted"||e==="strict"?e:S.extensions.policy.default_sandbox_profile}function iR(e){let t=e.name.trim().toLowerCase();if(t.length===0)return null;let n={name:t};e.disabled===!0&&(n.disabled=!0),e.require_trusted===!0&&(n.require_trusted=!0),e.require_provenance===!0&&(n.require_provenance=!0),e.sandbox_profile!==void 0&&(n.sandbox_profile=dh(e.sandbox_profile));let r=Oe(e.allowed_capabilities),o=Oe(e.blocked_capabilities),i=Oe(e.allowed_surfaces),s=Oe(e.blocked_surfaces),a=Oe(e.allowed_commands),c=Oe(e.blocked_commands),d=Oe(e.allowed_actions),l=Oe(e.blocked_actions),u=Oe(e.allowed_services),f=Oe(e.blocked_services);return r.length>0&&(n.allowed_capabilities=r),o.length>0&&(n.blocked_capabilities=o),i.length>0&&(n.allowed_surfaces=i),s.length>0&&(n.blocked_surfaces=s),a.length>0&&(n.allowed_commands=a),c.length>0&&(n.blocked_commands=c),d.length>0&&(n.allowed_actions=d),l.length>0&&(n.blocked_actions=l),u.length>0&&(n.allowed_services=u),f.length>0&&(n.blocked_services=f),n}function sR(e){let t=new Map;for(let n of e??[]){let r=iR(n);r&&t.set(r.name,r)}return[...t.values()].sort((n,r)=>n.name.localeCompare(r.name))}function xd(e){return e==="block"||e==="warn"?e:void 0}function aR(e){if(typeof e=="string")return xd(e);if(typeof e=="object"&&e!==null&&!Array.isArray(e)){let t=xd(e.global),n=xd(e.project);return t===void 0&&n===void 0?void 0:{...t!==void 0?{global:t}:{},...n!==void 0?{project:n}:{}}}}function he(e,t){return Oe(e?.[t]??S.extensions.policy[t])}function lh(e){let t=aR(e?.pm_max_version_exceeded_mode);return{mode:rR(e?.mode),trust_mode:oR(e?.trust_mode),...t!==void 0?{pm_max_version_exceeded_mode:t}:{},require_provenance:e?.require_provenance===!0,trusted_extensions:he(e,"trusted_extensions"),default_sandbox_profile:dh(e?.default_sandbox_profile),allowed_extensions:he(e,"allowed_extensions"),blocked_extensions:he(e,"blocked_extensions"),allowed_capabilities:he(e,"allowed_capabilities"),blocked_capabilities:he(e,"blocked_capabilities"),allowed_surfaces:he(e,"allowed_surfaces"),blocked_surfaces:he(e,"blocked_surfaces"),allowed_commands:he(e,"allowed_commands"),blocked_commands:he(e,"blocked_commands"),allowed_actions:he(e,"allowed_actions"),blocked_actions:he(e,"blocked_actions"),allowed_services:he(e,"allowed_services"),blocked_services:he(e,"blocked_services"),extension_overrides:sR(e?.extension_overrides??S.extensions.policy.extension_overrides)}}function uh(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase().replaceAll("-","_")))].filter(t=>t.length>0).sort((t,n)=>t.localeCompare(n)).filter(t=>["author","acceptance_criteria","estimated_minutes","close_reason","reviewer","risk","confidence","sprint","release"].includes(t))}function _t(e){return[...new Set((e??[]).map(t=>t.trim().toLowerCase()).filter(t=>t.length>0))].sort((t,n)=>t.localeCompare(n))}function W(e,t){return e===void 0?t:e}function ge(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{}}function Pd(e){return Array.isArray(e)?e:[]}function cR(e,t,n){return{...t.validation,...e.validation,parent_reference:n.parent_reference,metadata_profile:n.metadata_profile,metadata_required_fields:uh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:_t(e.validation?.lifecycle_stale_blocker_reason_patterns??t.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:_t(e.validation?.lifecycle_closure_like_blocked_reason_patterns??t.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:_t(e.validation?.lifecycle_closure_like_resolution_patterns??t.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:_t(e.validation?.lifecycle_closure_like_actual_result_patterns??t.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Td(e.validation?.estimate_defaults_by_type)}}function dR(e,t){return{enabled:e.telemetry?.enabled??t.telemetry.enabled,first_run_prompt_completed:e.telemetry?.first_run_prompt_completed??t.telemetry.first_run_prompt_completed,capture_level:e.telemetry?.capture_level??t.telemetry.capture_level,endpoint:e.telemetry?.endpoint??t.telemetry.endpoint,installation_id:e.telemetry?.installation_id??t.telemetry.installation_id,retention_days:e.telemetry?.retention_days??t.telemetry.retention_days}}function lR(e,t){return{...t.search,...e.search,default_mode:Zy(e.search?.default_mode),mutation_refresh_policy:Jy(e.search?.mutation_refresh_policy),query_expansion:{...t.search.query_expansion,...e.search?.query_expansion,enabled:Qy(e.search?.query_expansion?.enabled),provider:eh(e.search?.query_expansion?.provider)},rerank:{...t.search.rerank,...e.search?.rerank,enabled:th(e.search?.rerank?.enabled),model:nh(e.search?.rerank?.model),top_k:rh(e.search?.rerank?.top_k)}}}function uR(e,t){return{adapter:e.vector_store.adapter??t.vector_store.adapter,collection_name:oh(e.vector_store.collection_name),qdrant:{...t.vector_store.qdrant,...e.vector_store.qdrant},lancedb:{...t.vector_store.lancedb,...e.vector_store.lancedb}}}function fR(e,t){return e.item_format==="json_markdown"?"toon":e.item_format??t.item_format}function mR(e,t){return{default_depth:e.context?.default_depth??t.context.default_depth,activity_limit:e.context?.activity_limit??t.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??t.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??t.context.next_ranking_policy,sections:{...t.context.sections,...e.context?.sections}}}function pR(e,t){return{openai:{...t.providers.openai,...e.providers.openai},ollama:{...t.providers.ollama,...e.providers.ollama}}}function Vn(e){let t=(e??[]).map(r=>mo(r)).filter(r=>r!==null),n=new Map;for(let r of t)n.set(r.name.toLowerCase(),r);return[...n.values()].sort((r,o)=>r.name.localeCompare(o.name))}function is(e){let t=Md(),n=Xy({governance:e.governance??{preset:"default"}});return{...t,...e,item_format:fR(e,t),locks:{...t.locks,...e.locks},ids:{...t.ids,...e.ids},agent_identity:structuredClone(e.agent_identity??t.agent_identity),mutation_guard:{...t.mutation_guard,...e.mutation_guard},checkpoints:{...t.checkpoints,...e.checkpoints},output:{...t.output,...e.output},ux:{...t.ux,...e.ux},history:{...t.history,...e.history,compact_policy:{...t.history.compact_policy,...e.history?.compact_policy}},validation:cR(e,t,n),governance:n,workflow:{definition_of_done:[...e.workflow?.definition_of_done??t.workflow.definition_of_done]},testing:{record_results_to_items:e.testing?.record_results_to_items??t.testing.record_results_to_items,allow_untrusted_linked_tests:e.testing?.allow_untrusted_linked_tests??t.testing.allow_untrusted_linked_tests},telemetry:dR(e,t),agent_guidance:ch(e.agent_guidance??t.agent_guidance),item_types:{definitions:Vn(e.item_types?.definitions)},schema:Ce(e.schema??t.schema),context:mR(e,t),extensions:{enabled:[...e.extensions.enabled],disabled:[...e.extensions.disabled],policy:lh(e.extensions.policy??t.extensions.policy)},search:lR(e,t),providers:pR(e,t),vector_store:uR(e,t)}}function _R(e){e.agent_identity=A(e.agent_identity,["probes_enabled","identity_vocabulary","harness_signals"]);let t=e.agent_identity;Object.hasOwn(t,"identity_vocabulary")&&(t.identity_vocabulary=A(ge(t.identity_vocabulary),["version","aliases"])),e.agent_identity.harness_signals=Pd(e.agent_identity.harness_signals).map(n=>A(ge(n),["harness","environment_keys","model_environment_keys","session_environment_keys","provenance_environment_keys","provenance_resolvers","provenance_unavailable_dimensions","argv_markers","client_names"])),e.locks=A(e.locks,["ttl_seconds","wait_ms"]),e.ids=A(e.ids,["token_length"]),e.mutation_guard=A(e.mutation_guard,["require_attributed_author","secret_guard","stale_in_progress_hours"]),e.checkpoints=A(e.checkpoints,["retention_days"]),e.output=A(e.output,["default_format"]),e.ux=A(e.ux,["deprecation_hints"]),e.history=A(e.history,["missing_stream","compact_policy"]),e.validation=A(e.validation,["sprint_release_format","parent_reference","metadata_profile","metadata_required_fields","lifecycle_stale_blocker_reason_patterns","lifecycle_closure_like_blocked_reason_patterns","lifecycle_closure_like_resolution_patterns","lifecycle_closure_like_actual_result_patterns","estimate_defaults_by_type"]),e.governance=A(e.governance,["preset","ownership_enforcement","create_mode_default","close_validation_default","require_close_reason","parent_reference","metadata_profile","force_required_for_stale_lock","create_default_type","workflow_enforcement","duplicate_detection_mode","duplicate_detection_threshold","duplicate_detection_limit"]),e.workflow=A(e.workflow,["definition_of_done"]),e.testing=A(e.testing,["record_results_to_items","allow_untrusted_linked_tests"]),e.telemetry=A(e.telemetry,["enabled","first_run_prompt_completed","capture_level","endpoint","installation_id","retention_days"]),e.agent_guidance=A(e.agent_guidance,["prompt_completed","declined","declined_at","template_version","last_checked_files"]),e.item_types=A(e.item_types,["definitions"]),e.schema=A(e.schema,["version","files","statuses","fields","workflow","type_workflows","unknown_field_policy"]),e.schema.files=A(ge(e.schema.files),["types","statuses","fields","workflows"]),e.schema.workflow=A(ge(e.schema.workflow),["draft_status","open_status","in_progress_status","blocked_status","close_status","canceled_status"]),e.context=A(e.context,["default_depth","activity_limit","stale_threshold_days","next_ranking_policy","sections"]),e.context.sections=A(ge(e.context.sections),["hierarchy","activity","progress","blockers","files","workload","staleness","tests"]),e.extensions=A(e.extensions,["enabled","disabled","policy"]),e.extensions.policy=A(ge(e.extensions.policy),["mode","trust_mode","pm_max_version_exceeded_mode","require_provenance","trusted_extensions","default_sandbox_profile","allowed_extensions","blocked_extensions","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services","extension_overrides"]),e.extensions.policy.extension_overrides=Pd(e.extensions.policy.extension_overrides).map(n=>A(ge(n),["name","disabled","require_trusted","require_provenance","sandbox_profile","allowed_capabilities","blocked_capabilities","allowed_surfaces","blocked_surfaces","allowed_commands","blocked_commands","allowed_actions","blocked_actions","allowed_services","blocked_services"])),e.search=A(e.search,["score_threshold","hybrid_semantic_weight","max_results","embedding_model","embedding_corpus_max_characters","embedding_batch_size","embedding_timeout_ms","scanner_max_batch_retries","provider","default_mode","mutation_refresh_policy","query_expansion","rerank"]),e.search.query_expansion=A(ge(e.search.query_expansion),["enabled","provider"]),e.search.rerank=A(ge(e.search.rerank),["enabled","model","top_k"]),e.providers=A(e.providers,["openai","ollama"]),e.providers.openai=A(ge(e.providers.openai),["base_url","api_key","model"]),e.providers.ollama=A(ge(e.providers.ollama),["base_url","model"]),e.vector_store=A(e.vector_store,["adapter","collection_name","qdrant","lancedb"]),e.vector_store.qdrant=A(ge(e.vector_store.qdrant),["url","api_key"]),e.vector_store.lancedb=A(ge(e.vector_store.lancedb),["path"])}function yR(e){return{...e,locks:W(e.locks,S.locks),ids:W(e.ids,S.ids),agent_identity:W(e.agent_identity,S.agent_identity),mutation_guard:W(e.mutation_guard,S.mutation_guard),checkpoints:W(e.checkpoints,S.checkpoints),output:W(e.output,S.output),ux:W(e.ux,S.ux),history:W(e.history,S.history),validation:W(e.validation,S.validation),workflow:W(e.workflow,S.workflow),testing:W(e.testing,S.testing),telemetry:W(e.telemetry,S.telemetry),agent_guidance:W(e.agent_guidance,S.agent_guidance),item_types:W(e.item_types,S.item_types),schema:W(e.schema,S.schema),context:W(e.context,S.context),extensions:W(e.extensions,S.extensions),search:W(e.search,S.search),providers:W(e.providers,S.providers),vector_store:W(e.vector_store,S.vector_store)}}function hR(e,t){return{...e.validation,parent_reference:t.parent_reference,metadata_profile:t.metadata_profile,metadata_required_fields:uh(e.validation?.metadata_required_fields),lifecycle_stale_blocker_reason_patterns:_t(e.validation?.lifecycle_stale_blocker_reason_patterns??S.validation.lifecycle_stale_blocker_reason_patterns),lifecycle_closure_like_blocked_reason_patterns:_t(e.validation?.lifecycle_closure_like_blocked_reason_patterns??S.validation.lifecycle_closure_like_blocked_reason_patterns),lifecycle_closure_like_resolution_patterns:_t(e.validation?.lifecycle_closure_like_resolution_patterns??S.validation.lifecycle_closure_like_resolution_patterns),lifecycle_closure_like_actual_result_patterns:_t(e.validation?.lifecycle_closure_like_actual_result_patterns??S.validation.lifecycle_closure_like_actual_result_patterns),estimate_defaults_by_type:Td(e.validation?.estimate_defaults_by_type)}}function gR(e){return{...S.search,...e.search,default_mode:Zy(e.search?.default_mode),mutation_refresh_policy:Jy(e.search?.mutation_refresh_policy),query_expansion:{...S.search.query_expansion,...e.search?.query_expansion,enabled:Qy(e.search?.query_expansion?.enabled),provider:eh(e.search?.query_expansion?.provider)},rerank:{...S.search.rerank,...e.search?.rerank,enabled:th(e.search?.rerank?.enabled),model:nh(e.search?.rerank?.model),top_k:rh(e.search?.rerank?.top_k)}}}function bR(e){return{default_depth:e.context?.default_depth??S.context.default_depth,activity_limit:e.context?.activity_limit??S.context.activity_limit,stale_threshold_days:e.context?.stale_threshold_days??S.context.stale_threshold_days,next_ranking_policy:e.context?.next_ranking_policy??S.context.next_ranking_policy,sections:{...S.context.sections,...e.context?.sections}}}function wR(e){return{...e.vector_store,adapter:e.vector_store?.adapter??S.vector_store.adapter,collection_name:oh(e.vector_store?.collection_name),qdrant:{...e.vector_store?.qdrant},lancedb:{...e.vector_store?.lancedb}}}function vR(e,t,n,r){return{...e,item_format:"toon",validation:hR(e,t),governance:t,agent_guidance:ch(e.agent_guidance),item_types:{definitions:r.item_type_definitions},schema:{...n,statuses:r.schema_statuses,fields:r.schema_fields,type_workflows:r.schema_type_workflows},search:gR(e),context:bR(e),extensions:{enabled:Dd(e.extensions?.enabled),disabled:Dd(e.extensions?.disabled),policy:lh(e.extensions?.policy)},vector_store:wR(e)}}function fh(e,t){for(let n of Object.keys(t)){let r=Reflect.get(t,n),o=e[n];typeof r=="object"&&r!==null&&!Array.isArray(r)&&typeof o=="object"&&o!==null&&!Array.isArray(o)?fh(o,r):e[n]=structuredClone(r)}}function Ld(e,t,n){let r=new Set([...Object.keys(t),...Object.keys(n)]);for(let o of r){let i=t[o],s=n[o];if(!B(i,s)){if(s===void 0){delete e[o];continue}if(typeof i=="object"&&i!==null&&!Array.isArray(i)&&typeof s=="object"&&s!==null&&!Array.isArray(s)){let a=e[o],c=typeof a=="object"&&a!==null&&!Array.isArray(a)?a:{};Ld(c,i,s),Object.keys(c).length>0?e[o]=c:delete e[o];continue}e[o]=structuredClone(s)}}}var as=["version","id_prefix","ids","author_default","agent_identity","mutation_guard","item_format","locks","checkpoints","output","ux","history","validation","governance","workflow","testing","telemetry","agent_guidance","item_types","schema","context","extensions","search","providers","vector_store"];function Hy(e,t){let n=yR(e),r=Xy(n),o=Ce(n.schema),i=eR(n,t),s=vR(n,r,o,i),a=A({...s,governance:KC(r)},as);return _R(a),a}function mh(e,t={}){let n=t.source===void 0?t.persist_source:ih(t.source.validated,is(t.source.validated)),r=Hy(e,n);if(n){let o=is(n.source_settings);o.item_types={definitions:structuredClone(n.runtime_item_type_definitions)},o.schema={...o.schema,statuses:structuredClone(n.runtime_schema_statuses),fields:structuredClone(n.runtime_schema_fields),type_workflows:structuredClone(n.runtime_schema_type_workflows)};let i=Hy(o,n);t.source!==void 0&&fh(i,t.source.validated);let s=structuredClone(t.source===void 0?n.source_settings:t.source.raw);return Ld(s,i,r),`${JSON.stringify(A(s,as),null,2)}
110
110
  `}return`${JSON.stringify(r,null,2)}
111
- `}async function mR(e){let t;try{t=await Fy(e)}catch(a){if(be(a))return Me();throw a}let n=Ie(t),r;try{r=await NC(n)}catch(a){if(be(a))return Me();throw a}if(!r.isFile())throw _s("settings.json");let o;try{o=await Kd(n,_s("settings.json"))}catch(a){if(be(a))return Me();throw a}let i;try{i=JSON.parse(o)}catch{return Me("settings_read_invalid_json")}let s=Zi(i);return s.success?{settings:os(s.data),metadata:{has_explicit_item_format:nh(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:Me("settings_read_invalid_schema")}async function dh(e){if(DC(e))return mR(e);let t=Ie(e),n=[t];await gn({path:t,scope:"project"});let r=Dy(e);if(r){let d=await pt(r.tracked_paths);if(Br(d,r.signatures))return rs(r.value)}let o=await pt([t]),i;try{i=await Ae(t)}catch{return Me("settings_read_fs_error")}if(i===null){let d=Me();return await Ad(e,[t],d,o,[t]),d}let s=await pt([t]);if(!Br(o,s))return nn(e),dh(e);let a;try{a=JSON.parse(i)}catch{let d=Me("settings_read_invalid_json");return await Ad(e,[t],d,s,[t]),d}let c=Zi(a);if(!c.success){let d=Me("settings_read_invalid_schema");return await Ad(e,[t],d,s,[t]),d}try{let d=os(c.data),l=zC(e,d.schema,t);n=l;let u=await pt(l),f=await Sf(e,d.schema),m=await pt(l),_={...d,item_types:{definitions:qn([...d.item_types.definitions,...Rd(f.type_definitions_from_file)])},schema:f.schema};is(_,eh(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:nh(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.warnings]};return Br(u,m)?ns(e,{tracked_paths:l,signatures:m,value:rs(y)}):nn(e),y}catch{let d=Me("settings_read_merge_failed");return await qC(e,n,d),d}}function pR(e,t=[],n=null){let r=Md(n)??{},o=t.filter(s=>!Object.hasOwn(r,s));if(o.length===0)return e;let i=JSON.parse(e);for(let s of o)Reflect.deleteProperty(i,s);return`${JSON.stringify(i,null,2)}
112
- `}var _R=/^[A-Za-z0-9_-]+$/u,yR=new Set(["__proto__","constructor","prototype"]);function Md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function hR(e){for(let t of e)if(t.split(".").find(n=>!_R.test(n)||yR.has(n))!==void 0)throw new g(`Settings write assignedPaths entry "${t}" is not a dotted settings path.`,h.USAGE,{code:"settings_write_assigned_path_invalid",reason:"assigned_path_segment_invalid",field:t,why:"Assigned paths name settings keys; an empty, reserved or non-identifier segment cannot address one safely.",nextSteps:["Pass dotted settings keys such as context.next_ranking_policy in assignedPaths."]})}function lh(e,t){return Md(Object.hasOwn(e,t)?e[t]:void 0)}function Ly(e,t){let n=e;for(let r of t)if(n=lh(n,r),n===void 0)return;return n}function gR(e,t){let n=e;for(let r of t){let o=lh(n,r);o===void 0&&(o={},n[r]=o),n=o}return n}function bR(e,t,n){for(let r of n){let o=r.split("."),i=o.pop(),s=Ly(t,o);if(s===void 0)continue;if(Object.hasOwn(s,i)){gR(e,o)[i]=structuredClone(s[i]);continue}if(!Ty.includes(o[0]??i))continue;let a=Ly(e,o);a!==void 0&&delete a[i]}}function wR(e,t,n,r,o){let i=o??JSON.parse(ch(xd())),s=structuredClone(Md(e)??{});Pd(s,i,t),bR(s,t,r);let a=Zi(s);if(!a.success){let c=a.path;throw new g(`Existing settings.json fails validation at ${c}; the settings write was refused and nothing was changed.`,h.USAGE,{code:"settings_write_invalid_existing_schema",reason:"existing_settings_schema_invalid",field:c,original_code:n,why:"The stored settings could not be read, so writing would either keep an invalid document or replace intended project configuration with defaults.",nextSteps:[`Fix or remove ${c} in settings.json, then retry the original command.`,"A configurable setting can also be repaired explicitly, even to its default value, with pm config <scope> set <dotted.key> <value>.","Run pm health to confirm the settings warning has cleared."]})}return`${JSON.stringify(A(s,ss),null,2)}
113
- `}function vR(e){try{return JSON.parse(e)}catch{throw new g("Existing settings.json is malformed; the settings write was refused.",h.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}}async function n2(e){return(await dh(e)).settings}async function r2(e,t,n=PC,r={}){let o=r.assignedPaths??[];hR(o);let i=Ie(e),s=Nd(t),a=s?void 0:Dd(t),c=ch(t,{persist_source:s}),d=JSON.parse(c),l=!1;try{if(await Ay({pmRoot:e,filePath:i,mutate:u=>{let f=u===null?null:vR(u);return u!==null&&r.skipIfStored?.(f)===!0?(l=!0,{raw:u,result:void 0}):a!==void 0&&u!==null?{raw:wR(f,d,a,o,WC(t)),result:void 0}:{raw:s?`${JSON.stringify(A(Ed(s.persisted_settings,d,f),ss),null,2)}
114
- `:pR(c,r.omitSections,f),result:void 0}},op:n,author:Hm(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),l)return;s?is(t,{...s,persisted_settings:structuredClone(d)}):a!==void 0&&GC(t,structuredClone(d)),await zo({path:i,scope:"project",op:n})}finally{nn(e)}}import uh from"node:fs";import Wr from"node:path";import{createRequire as ER}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]="2b3d7667-1c63-565a-b314-3a74cc8d6b7d")}catch{}})();var Gr="@unbrained/pm-cli",kR=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),fh=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),$d=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,ls="2026.8.31";function ae(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function jd(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ae(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var SR={changelog:(e,t)=>{if(t[0]==="generate")return!ae(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(ae(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ae(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:jd,files:(e,t)=>ae(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ae(e,["--apply"]),health:e=>!ae(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),package:jd,packages:jd,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(ae(e,["--infer"])&&!ae(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>ae(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ae(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function cs(e){let t=e.match($d);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function yt(e,t){let n=cs(e),r=cs(t);if(!n||!r)return null;for(let o=0;o<n.length;o+=1){let i=n[o]-r[o];if(i!==0)return Math.sign(i)}return 0}function as(e){return yt(e,ls)!==-1?3:2}function OR(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>yt(n.version,r.version))[0]}function ds(e){try{let t=JSON.parse(uh.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function AR(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function IR(e){let t=e.split("||").map(n=>AR(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let o=yt(ls,r.version);return o!==null&&(r.inclusive?o!==1:o===-1)}))}}function mh(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[Gr];return typeof r=="string"?[r.trim()]:[]})}function TR(e){return mh(e).flatMap(t=>{let n=/^[<!]/u.test(t)?void 0:t.match($d)?.[0];if(!n)return[];let r=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=IR(t);return[{version:n,constraint:r?"exact":o.bounded?"range":"minimum",...r?{}:{declaration:t},history_epoch_compatible:r?yt(n,ls)!==-1:o.compatible}]})}function CR(e){let t=ds(Wr.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function RR(e,t){try{let n=uh.readFileSync(Wr.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(s=>s.includes(Gr));if(r<0)return;let o=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let s=r+1;s<n.length;s+=1){let a=n[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
115
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match($d)?.[0]}catch{return}}function ph(e){let t=[],n=ds(Wr.join(e,"package.json"));n&&t.push(...TR(n).map(i=>({...i,source:"package.json"})));let r=ds(Wr.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&cs(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:as(r)===3});let o=CR(e);o&&cs(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:as(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=RR(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:as(s)===3})}return t}function l2(e,t){if(t<=1)return;let{minVersion:n,lt:r}=ER(import.meta.url)("semver"),o=mh(ds(Wr.join(e,"package.json"))??{}).find(s=>{try{let a=n(s);return a!==null&&r(a,"2026.10.10")}catch{return!1}}),i=o===void 0?ph(e).find(s=>yt(s.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new g(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,h.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function _h(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(fh.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function xR(e){let t=_h(e);if(!t||ae(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,o=[];for(let s=r+1;s<e.length;s+=1){let a=e[s];if(fh.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=SR[n];return i?i(e,o):kR.has(n)}function NR(e){let t=_h(e.argv)?.command,n=xR(e.argv),r=ph(e.projectRoot).filter(l=>yt(l.version,e.executingVersion)!==null).sort((l,u)=>yt(u.version,l.version)),o=r[0],i=o!==void 0&&yt(e.executingVersion,o.version)===-1,s=as(e.executingVersion),a=OR(r,s),c=n&&a!==void 0,d=i&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:o.version,source:o.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${Gr} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:n,stale:i,history_epoch_incompatible:c,writer_item_hash_version:s,...a?{incompatible_project_version:a.declaration,incompatible_source:a.source}:{},...d?{warning:d}:{},override_applied:n&&(i||c)&&e.allowStale===!0}}function u2(e){let t=NR(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new g(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${Gr} pin to ${ls} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new g(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${Gr} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import Fd from"node:fs/promises";import us 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]="658ab1c3-da92-5af6-a170-85ed7befaad6")}catch{}})();function ht(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function yh(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:dn(t),suggested_retry_args:t}}function fs(e){return new g(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function Ld(e){return new g(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function DR(e){let t=us.resolve(e),n=us.parse(t).root,r=us.dirname(t);for(;r!==n;){let o;try{o=await Fd.stat(r)}catch(i){if(ht(i,"ENOTDIR"))throw fs(e);if(!ht(i,"ENOENT"))throw i;r=us.dirname(r);continue}if(!o.isDirectory())throw fs(e);return}}async function PR(e){let t;try{t=await Fd.stat(e)}catch(n){throw ht(n,"ENOENT")?(await DR(e),new g(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:yh(e)})):ht(n,"ENOTDIR")?fs(e):ht(n,"EACCES")||ht(n,"EPERM")?Ld(e):n}if(!t.isDirectory())throw fs(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Ld(e);try{await(await Fd.opendir(e)).close()}catch(n){throw ht(n,"EACCES")||ht(n,"EPERM")?Ld(e):n}}async function w2(e){if(await PR(e),!await gt(Ie(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:yh(e)})}export{R as a,B as b,to as c,Ch as d,Jd as e,ys as f,Nh as g,Dh as h,no as i,Zd as j,Mh as k,Lh as l,zR as m,HR as n,Hh as o,qh as p,Vh as q,Bh as r,hs as s,VR as t,Wh as u,Gn as v,ro as w,BR as x,WR as y,GR as z,Gh as A,Kh as B,Yh as C,QR as D,ZR as E,Xh as F,oo as G,ex as H,tx as I,Jh as J,Qh as K,Zh as L,tl as M,sn as N,eg as O,nx as P,rx as Q,ox as R,ix as S,sx as T,ax as U,cx as V,dx as W,Il as X,lb as Y,ub as Z,fb as _,yo as $,nN as aa,tg as ba,nl as ca,an as da,io as ea,cn as fa,so as ga,ux as ha,fx as ia,mx as ja,co as ka,lo as la,px as ma,_x as na,yx as oa,hx as pa,uo as qa,Kn as ra,gs as sa,gx as ta,il as ua,bx as va,wx as wa,sl as xa,vx as ya,ag as za,ll as Aa,_l as Ba,Rx as Ca,Es as Da,bg as Ea,xx as Fa,Dg as Ga,Pg as Ha,Nx as Ia,Dx as Ja,Hx as Ka,ks as La,qx as Ma,bl as Na,wl as Oa,vl as Pa,Ie as Qa,Vx as Ra,Bx as Sa,Wx as Ta,Ss as Ua,Os as Va,mo as Wa,Jg as Xa,Gx as Ya,Qg as Za,Zg as _a,Kx as $a,Yx as ab,eb as bb,Xx as cb,Jn as db,po as eb,El as fb,dn as gb,As as hb,Sl as ib,ab as jb,cb as kb,db as lb,fN as mb,mN as nb,pN as ob,hb as pb,Cs as qb,gN as rb,Rl as sb,xl as tb,_f as ub,bb as vb,wN as wb,vN as xb,EN as yb,Dl as zb,kN as Ab,SN as Bb,ON as Cb,Nl as Db,Pl as Eb,AN as Fb,bo as Gb,Eb as Hb,kb as Ib,xN as Jb,NN as Kb,Te as Lb,Le as Mb,Qn as Nb,ln as Ob,re as Pb,LN as Qb,FN as Rb,vo as Sb,HN as Tb,Fl as Ub,qN as Vb,Eo as Wb,Ps as Xb,$s as Yb,Ls as Zb,YN as _b,XN as $b,JN as ac,Qb as bc,zl as cc,QN as dc,Fs as ec,Hl as fc,Ao as gc,Io as hc,oD as ic,iD as jc,To as kc,Co as lc,Et as mc,U as nc,Ro as oc,lD as pc,ql as qc,Us as rc,mw as sc,pw as tc,tr as uc,zs as vc,Hs as wc,qs as xc,Vs as yc,Bs as zc,Ws as Ac,da as Bc,yw as Cc,hw as Dc,vw as Ec,Ew as Fc,Xl as Gc,Au as Hc,qu as Ic,Vu as Jc,Ee as Kc,vD as Lc,ED as Mc,Ow as Nc,Gs as Oc,Iw as Pc,Ks as Qc,Ys as Rc,Xs as Sc,Js as Tc,Qs as Uc,Zs as Vc,ta as Wc,na as Xc,ra as Yc,_v as Zc,hv as _c,gv as $c,Av as ad,t1 as bd,n1 as cd,r1 as dd,a1 as ed,d1 as fd,Bv as gd,Wv as hd,ya as id,Yv as jd,Xv as kd,h1 as ld,Fo as md,g1 as nd,b1 as od,w1 as pd,v1 as qd,E1 as rd,k1 as sd,S1 as td,cf as ud,O1 as vd,A1 as wd,df as xd,I1 as yd,Uo as zd,T1 as Ad,C1 as Bd,R1 as Cd,x1 as Dd,N1 as Ed,zo as Fd,D1 as Gd,gn as Hd,P1 as Id,M1 as Jd,j1 as Kd,$1 as Ld,L1 as Md,bn as Nd,B1 as Od,tE as Pd,mf as Qd,Tt as Rd,Je as Sd,pf as Td,Qe as Ud,ie as Vd,wa as Wd,Ce as Xd,ue as Yd,iM as Zd,sM as _d,Sf as $d,Of as ae,va as be,Af as ce,If as de,aM as ee,pM as fe,ME as ge,_M as he,Pf as ie,Mf as je,br as ke,yM as le,hM as me,Ea as ne,ka as oe,bM as pe,Sa as qe,$f as re,qE as se,wM as te,Ko as ue,BE as ve,SM as we,Yo as xe,qM as ye,E0 as ze,F0 as Ae,Qo as Be,ok as Ce,VM as De,BM as Ee,Sn as Fe,Xf as Ge,Jf as He,Qf as Ie,$a as Je,Zf as Ke,KM as Le,em as Me,YM as Ne,tm as Oe,Rt as Pe,Fa as Qe,QM as Re,ZM as Se,ti as Te,ni as Ue,$k as Ve,di as We,qk as Xe,fe as Ye,Wk as Ze,Ka as _e,Am as $e,Xa as af,Nj as bf,Dj as cf,Pj as df,Mj as ef,jj as ff,$j as gf,ic as hf,sc as if,Pm as jf,Gj as kf,Kj as lf,Yj as mf,Xj as nf,Jj as of,Qj as pf,lc as qf,Fm as rf,Zj as sf,e$ as tf,t$ as uf,kS as vf,n$ as wf,Hm as xf,pi as yf,Mt as zf,u$ as Af,OS as Bf,AS as Cf,Tn as Df,V_ as Ef,jT as Ff,zT as Gf,NU as Hf,DU as If,Rr as Jf,_$ as Kf,_i as Lf,xS as Mf,NS as Nf,y$ as Of,xe as Pf,h$ as Qf,$S as Rf,US as Sf,GS as Tf,Gm as Uf,op as Vf,hc as Wf,fc as Xf,hi as Yf,YS as Zf,rt as _f,Cn as $f,Ir as ag,Rn as bg,Tr as cg,Ym as dg,b$ as eg,Cr as fg,Dr as gg,it as hg,uO as ig,M$ as jg,sp as kg,fO as lg,vO as mg,kO as ng,ap as og,SO as pg,OO as qg,cp as rg,$t as sg,dp as tg,j$ as ug,$$ as vg,wc as wg,L$ as xg,F$ as yg,U$ as zg,z$ as Ag,H$ as Bg,ve as Cg,Lt as Dg,Y$ as Eg,vc as Fg,Ec as Gg,ki as Hg,mp as Ig,kc as Jg,pp as Kg,xr as Lg,J$ as Mg,Ft as Ng,hL as Og,gL as Pg,UO as Qg,at as Rg,bL as Sg,wL as Tg,vL as Ug,Ap as Vg,GO as Wg,EL as Xg,Tp as Yg,Ic as Zg,jp as _g,Ne as $g,hA as ah,$p as bh,Lp as ch,Oi as dh,Tc as eh,Mr as fh,LL as gh,FL as hh,jr as ih,Cc as jh,Nc as kh,UL as lh,IA as mh,zL as nh,HL as oh,qe as ph,X as qh,eF as rh,Ht as sh,LA as th,tF as uh,nF as vh,FA as wh,rF as xh,oF as yh,iF as zh,qA as Ah,n_ as Bh,VA as Ch,gF as Dh,WA as Eh,o_ as Fh,bF as Gh,a_ as Hh,XA as Ih,Zp as Jh,Lc as Kh,p_ as Lh,h_ as Mh,SF as Nh,g_ as Oh,AF as Ph,k_ as Qh,O_ as Rh,NF as Sh,DF as Th,NI as Uh,Ur as Vh,Di as Wh,XF as Xh,JF as Yh,YT as Zh,Ki as _h,Gt as $h,zr as ai,QT as bi,ZT as ci,by as di,Fn as ei,rz as fi,hd as gi,Mi as hi,$_ as ii,ed as ji,oz as ki,vy as li,L_ as mi,iz as ni,qr as oi,Vr as pi,dT as qi,ji as ri,uU as si,Zc as ti,$i as ui,fU as vi,mU as wi,U_ as xi,Li as yi,Fi as zi,Kt as Ai,gT as Bi,pU as Ci,_U as Di,mt as Ei,Zt as Fi,gz as Gi,bz as Hi,wz as Ii,Ay as Ji,vz as Ki,Ez as Li,kz as Mi,Ty as Ni,Zi as Oi,xz as Pi,nn as Qi,Zz as Ri,DC as Si,By as Ti,e2 as Ui,t2 as Vi,os as Wi,ch as Xi,dh as Yi,n2 as Zi,r2 as _i,ls as $i,yt as aj,as as bj,ph as cj,l2 as dj,xR as ej,NR as fj,u2 as gj,yh as hj,PR as ij,w2 as jj};
116
- //# sourceMappingURL=chunk-PZI6CR24.js.map
111
+ `}async function ER(e){let t;try{t=await Vy(e)}catch(a){if(be(a))return Me();throw a}let n=Ie(t),r;try{r=await zC(n)}catch(a){if(be(a))return Me();throw a}if(!r.isFile())throw ys("settings.json");let o;try{o=await Zd(n,ys("settings.json"))}catch(a){if(be(a))return Me();throw a}let i;try{i=JSON.parse(o)}catch{return Me("settings_read_invalid_json")}let s=es(i);return s.success?{settings:is(s.data),metadata:{has_explicit_item_format:ah(i)},warnings:s.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[]}:Me("settings_read_invalid_schema")}async function ph(e){if(HC(e))return ER(e);let t=Ie(e),n=[t];await bn({path:t,scope:"project"});let r=Ly(e);if(r){let d=await pt(r.tracked_paths);if(Wr(d,r.signatures))return os(r.value)}let o=await pt([t]),i;try{i=await Ae(t)}catch{return Me("settings_read_fs_error")}if(i===null){let d=Me();return await Rd(e,[t],d,o,[t]),d}let s=await pt([t]);if(!Wr(o,s))return nn(e),ph(e);let a;try{a=JSON.parse(i)}catch{let d=Me("settings_read_invalid_json");return await Rd(e,[t],d,s,[t]),d}let c=es(a);if(!c.success){let d=Me("settings_read_invalid_schema");return await Rd(e,[t],d,s,[t]),d}try{let d=is(c.data),l=XC(e,d.schema,t);n=l;let u=await pt(l),f=await Cf(e,d.schema),m=await pt(l),_={...d,item_types:{definitions:Vn([...d.item_types.definitions,...Pd(f.type_definitions_from_file)])},schema:f.schema};ss(_,ih(c.data,_));let y={settings:_,metadata:{has_explicit_item_format:ah(a)},warnings:[...c.data.item_format==="json_markdown"?["settings_item_format_legacy_json_markdown_coerced_to_toon"]:[],...f.warnings]};return Wr(u,m)?rs(e,{tracked_paths:l,signatures:m,value:os(y)}):nn(e),y}catch{let d=Me("settings_read_merge_failed");return await ZC(e,n,d),d}}function kR(e,t=[],n=null){let r=Fd(n)??{},o=t.filter(s=>!Object.hasOwn(r,s));if(o.length===0)return e;let i=JSON.parse(e);for(let s of o)Reflect.deleteProperty(i,s);return`${JSON.stringify(i,null,2)}
112
+ `}var SR=/^[A-Za-z0-9_-]+$/u,OR=new Set(["__proto__","constructor","prototype"]);function Fd(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:void 0}function AR(e){for(let t of e)if(t.split(".").find(n=>!SR.test(n)||OR.has(n))!==void 0)throw new g(`Settings write assignedPaths entry "${t}" is not a dotted settings path.`,h.USAGE,{code:"settings_write_assigned_path_invalid",reason:"assigned_path_segment_invalid",field:t,why:"Assigned paths name settings keys; an empty, reserved or non-identifier segment cannot address one safely.",nextSteps:["Pass dotted settings keys such as context.next_ranking_policy in assignedPaths."]})}function _h(e,t){return Fd(Object.hasOwn(e,t)?e[t]:void 0)}function qy(e,t){let n=e;for(let r of t)if(n=_h(n,r),n===void 0)return;return n}function IR(e,t){let n=e;for(let r of t){let o=_h(n,r);o===void 0&&(o={},n[r]=o),n=o}return n}function TR(e,t,n){for(let r of n){let o=r.split("."),i=o.pop(),s=qy(t,o);if(s===void 0)continue;if(Object.hasOwn(s,i)){IR(e,o)[i]=structuredClone(s[i]);continue}if(!Dy.includes(o[0]??i))continue;let a=qy(e,o);a!==void 0&&delete a[i]}}function CR(e,t,n,r,o){let i=o??JSON.parse(mh(Md())),s=structuredClone(Fd(e)??{});Ld(s,i,t),TR(s,t,r);let a=es(s);if(!a.success){let c=a.path;throw new g(`Existing settings.json fails validation at ${c}; the settings write was refused and nothing was changed.`,h.USAGE,{code:"settings_write_invalid_existing_schema",reason:"existing_settings_schema_invalid",field:c,original_code:n,why:"The stored settings could not be read, so writing would either keep an invalid document or replace intended project configuration with defaults.",nextSteps:[`Fix or remove ${c} in settings.json, then retry the original command.`,"A configurable setting can also be repaired explicitly, even to its default value, with pm config <scope> set <dotted.key> <value>.","Run pm health to confirm the settings warning has cleared."]})}return`${JSON.stringify(A(s,as),null,2)}
113
+ `}function RR(e){try{return JSON.parse(e)}catch{throw new g("Existing settings.json is malformed; the settings write was refused.",h.USAGE,{code:"settings_write_invalid_existing_json",reason:"existing_settings_json_malformed",why:"Writing defaults over malformed settings could destroy intended project configuration.",nextSteps:["Repair the syntax in .agents/pm/settings.json, then retry the original command.","Run pm health to confirm the settings warning has cleared."]})}}async function g2(e){return(await ph(e)).settings}async function b2(e,t,n=qC,r={}){let o=r.assignedPaths??[];AR(o);let i=Ie(e),s=$d(t),a=s?void 0:jd(t),c=mh(t,{persist_source:s}),d=JSON.parse(c),l=!1;try{if(await xy({pmRoot:e,filePath:i,mutate:u=>{let f=u===null?null:RR(u);return u!==null&&r.skipIfStored?.(f)===!0?(l=!0,{raw:u,result:void 0}):a!==void 0&&u!==null?{raw:CR(f,d,a,o,tR(t)),result:void 0}:{raw:s?`${JSON.stringify(A(Ad(s.persisted_settings,d,f),as),null,2)}
114
+ `:kR(c,r.omitSections,f),result:void 0}},op:n,author:Gm(void 0,t.author_default),lockTtlSeconds:t.locks.ttl_seconds,lockWaitMs:t.locks.wait_ms,recordCreation:!1}),l)return;s?ss(t,{...s,persisted_settings:structuredClone(d)}):a!==void 0&&nR(t,structuredClone(d)),await Ho({path:i,scope:"project",op:n})}finally{nn(e)}}import yh from"node:fs";import Gr from"node:path";import{createRequire as xR}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]="2b3d7667-1c63-565a-b314-3a74cc8d6b7d")}catch{}})();var Kr="@unbrained/pm-cli",NR=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),hh=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),zd=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,us="2026.8.31";function ae(e,t){return e.some(n=>t.includes(n.split("=",1)[0]))}function Ud(e,t){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(t[0]??"")||ae(e,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}var DR={changelog:(e,t)=>{if(t[0]==="generate")return!ae(e,["--check"]);let n=e.indexOf("export");return t[0]==="export"&&(ae(e,["--output"])||n>=0&&e[n+1]!==void 0&&!e[n+1].startsWith("-"))},comments:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),config:(e,t)=>(t[0]==="project"||t[0]==="global"?t[1]:t[0])==="set",deps:()=>!1,docs:e=>ae(e,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:Ud,files:(e,t)=>ae(e,["--add","--add-glob","--migrate","--remove"])||t[0]==="discover"&&ae(e,["--apply"]),health:e=>!ae(e,["--check-only","--no-refresh","--skip-vectors"]),learnings:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),merge:(e,t)=>t[0]!=="report",notes:e=>ae(e,["--add","--delete","--edit","--file","--stdin"]),package:Ud,packages:Ud,profile:(e,t)=>t[0]==="apply",schema:(e,t)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(t[0]??"")&&!(ae(e,["--infer"])&&!ae(e,["--apply"])),telemetry:(e,t)=>t.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(e,t)=>t[0]==="save",test:e=>ae(e,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:e=>ae(e,["--auto-fix","--prune-missing"]),vcs:(e,t)=>["abandon","create","merge","propose","ref-create"].includes(t[0]??""),workspace:(e,t)=>t[0]==="snapshot"&&["create","delete","restore"].includes(t[1]??"")};function ds(e){let t=e.match(zd);return t?[Number(t[1]),Number(t[2]),Number(t[3]),Number(t[4]??0)]:null}function yt(e,t){let n=ds(e),r=ds(t);if(!n||!r)return null;for(let o=0;o<n.length;o+=1){let i=n[o]-r[o];if(i!==0)return Math.sign(i)}return 0}function cs(e){return yt(e,us)!==-1?3:2}function PR(e,t){if(t===3)return e.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,r)=>yt(n.version,r.version))[0]}function ls(e){try{let t=JSON.parse(yh.readFileSync(e,"utf8"));return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function MR(e){let t=[...e.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(r=>({inclusive:r[1]==="<=",version:r[2]})),n=e.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...t,{inclusive:!0,version:n[1]}]:t}function $R(e){let t=e.split("||").map(n=>MR(n));return{bounded:t.some(n=>n.length>0),compatible:t.some(n=>n.every(r=>{let o=yt(us,r.version);return o!==null&&(r.inclusive?o!==1:o===-1)}))}}function gh(e){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(t=>{let n=e[t];if(typeof n!="object"||n===null)return[];let r=n[Kr];return typeof r=="string"?[r.trim()]:[]})}function jR(e){return gh(e).flatMap(t=>{let n=/^[<!]/u.test(t)?void 0:t.match(zd)?.[0];if(!n)return[];let r=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(t),o=$R(t);return[{version:n,constraint:r?"exact":o.bounded?"range":"minimum",...r?{}:{declaration:t},history_epoch_compatible:r?yt(n,us)!==-1:o.compatible}]})}function LR(e){let t=ls(Gr.join(e,"package-lock.json"))?.packages;if(typeof t!="object"||t===null)return;let n=t["node_modules/@unbrained/pm-cli"];if(typeof n!="object"||n===null)return;let r=n.version;return typeof r=="string"?r:void 0}function FR(e,t){try{let n=yh.readFileSync(Gr.join(e,t),"utf8").split(/\r?\n/u),r=n.findIndex(s=>s.includes(Kr));if(r<0)return;let o=n[r].match(/^\s*/u)[0].length,i=[n[r]];for(let s=r+1;s<n.length;s+=1){let a=n[s],c=a.trim(),d=a.match(/^\s*/u)[0].length;if(c.length>0&&d<=o)break;i.push(a)}return i.join(`
115
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(zd)?.[0]}catch{return}}function bh(e){let t=[],n=ls(Gr.join(e,"package.json"));n&&t.push(...jR(n).map(i=>({...i,source:"package.json"})));let r=ls(Gr.join(e,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&ds(r)&&t.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:cs(r)===3});let o=LR(e);o&&ds(o)&&t.push({version:o,source:"package-lock.json",constraint:"exact",history_epoch_compatible:cs(o)===3});for(let i of["pnpm-lock.yaml","yarn.lock"]){let s=FR(e,i);s&&t.push({version:s,source:i,constraint:"exact",history_epoch_compatible:cs(s)===3})}return t}function A2(e,t){if(t<=1)return;let{minVersion:n,lt:r}=xR(import.meta.url)("semver"),o=gh(ls(Gr.join(e,"package.json"))??{}).find(s=>{try{let a=n(s);return a!==null&&r(a,"2026.10.10")}catch{return!1}}),i=o===void 0?bh(e).find(s=>yt(s.version,"2026.10.10")===-1):{version:o,source:"package.json"};if(i)throw new g(`The project selects pm ${i.version}, which cannot safely refuse item format ${t}.`,h.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function wh(e){for(let t=0;t<e.length;t+=1){let n=e[t];if(hh.has(n)){t+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:t}}}function UR(e){let t=wh(e);if(!t||ae(e,["--help","-h","--dry-run"]))return!1;let{command:n,index:r}=t,o=[];for(let s=r+1;s<e.length;s+=1){let a=e[s];if(hh.has(a)){s+=1;continue}a.startsWith("-")||o.push(a.toLowerCase())}let i=DR[n];return i?i(e,o):NR.has(n)}function zR(e){let t=wh(e.argv)?.command,n=UR(e.argv),r=bh(e.projectRoot).filter(l=>yt(l.version,e.executingVersion)!==null).sort((l,u)=>yt(u.version,l.version)),o=r[0],i=o!==void 0&&yt(e.executingVersion,o.version)===-1,s=cs(e.executingVersion),a=PR(r,s),c=n&&a!==void 0,d=i&&!n?{code:"project_runtime_stale_read",executing_version:e.executingVersion,project_version:o.version,source:o.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${Kr} ${o.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!c||e.allowStale===!0,executing_version:e.executingVersion,...o?{project_version:o.version,source:o.source}:{},...t?{command:t}:{},mutating:n,stale:i,history_epoch_incompatible:c,writer_item_hash_version:s,...a?{incompatible_project_version:a.declaration,incompatible_source:a.source}:{},...d?{warning:d}:{},override_applied:n&&(i||c)&&e.allowStale===!0}}function I2(e){let t=zR(e);if(t.compatible)return t;throw t.history_epoch_incompatible?new g(`pm ${t.executing_version} cannot write item-hash epoch ${t.writer_item_hash_version} into a project pinned to pm ${t.incompatible_project_version}.`,h.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:t.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${t.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${Kr} pin to ${us} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new g(`pm ${t.executing_version} cannot mutate a project pinned to newer pm ${t.project_version}.`,h.CONFLICT,{code:"project_runtime_stale_mutation",reason:t.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${Kr} ${t.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}import qd from"node:fs/promises";import fs 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]="658ab1c3-da92-5af6-a170-85ed7befaad6")}catch{}})();function ht(e,t){return typeof e=="object"&&e!==null&&"code"in e&&e.code===t}function vh(e){let t=["--pm-path",e,"init","--defaults","--agent-guidance","skip"];return{suggested_retry:dn(t),suggested_retry_args:t}}function ms(e){return new g(`Tracker root is not a directory at ${e}.`,h.USAGE,{code:"tracker_root_not_directory",reason:"not_a_directory",resolved_path:e,nextSteps:["Pass a tracker directory, usually <workspace>/.agents/pm, rather than a file path."]})}function Hd(e){return new g(`Tracker root is not readable at ${e}.`,h.GENERIC_FAILURE,{code:"tracker_root_unreadable",reason:"unreadable",resolved_path:e,nextSteps:["Grant read and directory-search permission to the tracker root, then retry."]})}async function HR(e){let t=fs.resolve(e),n=fs.parse(t).root,r=fs.dirname(t);for(;r!==n;){let o;try{o=await qd.stat(r)}catch(i){if(ht(i,"ENOTDIR"))throw ms(e);if(!ht(i,"ENOENT"))throw i;r=fs.dirname(r);continue}if(!o.isDirectory())throw ms(e);return}}async function qR(e){let t;try{t=await qd.stat(e)}catch(n){throw ht(n,"ENOENT")?(await HR(e),new g(`Tracker is not initialized at ${e}. Tracker root does not exist. Run pm init first.`,h.NOT_FOUND,{code:"tracker_root_missing",reason:"missing",resolved_path:e,nextSteps:["Confirm the tracker root path or initialize it with the emitted retry."],recovery:vh(e)})):ht(n,"ENOTDIR")?ms(e):ht(n,"EACCES")||ht(n,"EPERM")?Hd(e):n}if(!t.isDirectory())throw ms(e);if(process.platform!=="win32"&&((t.mode&292)===0||(t.mode&73)===0))throw Hd(e);try{await(await qd.opendir(e)).close()}catch(n){throw ht(n,"EACCES")||ht(n,"EPERM")?Hd(e):n}}async function $2(e){if(await qR(e),!await gt(Ie(e)))throw new g(`Tracker is not initialized at ${e}. Run pm init first.`,h.NOT_FOUND,{code:"tracker_not_initialized",reason:"settings_missing",resolved_path:e,nextSteps:["Initialize the selected tracker root with the emitted retry."],recovery:vh(e)})}export{R as a,B as b,no as c,Ph as d,tl as e,hs as f,jh as g,Lh as h,ro as i,rl as j,Uh as k,qh as l,XR as m,JR as n,Gh as o,Kh as p,Yh as q,Xh as r,gs as s,QR as t,Jh as u,Kn as v,oo as w,ex as x,tx as y,nx as z,Zh as A,Qh as B,eg as C,ax as D,cx as E,tg as F,io as G,dx as H,lx as I,ng as J,rg as K,og as L,il as M,sn as N,ig as O,ux as P,fx as Q,mx as R,px as S,_x as T,yx as U,hx as V,gx as W,Nl as X,bb as Y,wb as Z,vb as _,ho as $,yN as aa,sg as ba,sl as ca,an as da,so as ea,cn as fa,ao as ga,wx as ha,vx as ia,Ex as ja,lo as ka,uo as la,kx as ma,Sx as na,Ox as oa,Ax as pa,fo as qa,Yn as ra,bs as sa,Ix as ta,dl as ua,Tx as va,Cx as wa,ll as xa,Rx as ya,fg as za,pl as Aa,bl as Ba,Fx as Ca,ks as Da,Sg as Ea,Ux as Fa,Lg as Ga,Fg as Ha,zx as Ia,Hx as Ja,Jx as Ka,Ss as La,Zx as Ma,kl as Na,Sl as Oa,Ol as Pa,Ie as Qa,Qx as Ra,eN as Sa,tN as Ta,Os as Ua,As as Va,po as Wa,nb as Xa,nN as Ya,rb as Za,ob as _a,rN as $a,oN as ab,ib as bb,iN as cb,Zn as db,_o as eb,Al as fb,dn as gb,Ts as hb,Rs as ib,Il as jb,fN as kb,ln as lb,mN as mb,Cl as nb,pN as ob,yb as pb,hb as qb,gb as rb,AN as sb,IN as tb,TN as ub,Ab as vb,Ds as wb,NN as xb,Ml as yb,$l as zb,wf as Ab,Tb as Bb,PN as Cb,MN as Db,$N as Eb,Ll as Fb,jN as Gb,LN as Hb,FN as Ib,jl as Jb,Fl as Kb,UN as Lb,wo as Mb,xb as Nb,Nb as Ob,BN as Pb,WN as Qb,Te as Rb,Le as Sb,Qn as Tb,un as Ub,re as Vb,ZN as Wb,QN as Xb,Eo as Yb,nD as Zb,Vl as _b,rD as $b,ko as ac,Ls as bc,zs as cc,Hs as dc,dD as ec,lD as fc,uD as gc,aw as hc,Wl as ic,fD as jc,qs as kc,Gl as lc,Io as mc,To as nc,gD as oc,bD as pc,Co as qc,Ro as rc,Et as sc,U as tc,xo as uc,SD as vc,Kl as wc,Vs as xc,Ew as yc,kw as zc,nr as Ac,Bs as Bc,Ws as Cc,Gs as Dc,Ks as Ec,Ys as Fc,Xs as Gc,ma as Hc,Ow as Ic,Aw as Jc,Rw as Kc,xw as Lc,tu as Mc,xu as Nc,Ku as Oc,Yu as Pc,Ee as Qc,MD as Rc,$D as Sc,Pw as Tc,Js as Uc,$w as Vc,Zs as Wc,Qs as Xc,ea as Yc,ta as Zc,na as _c,ra as $c,ia as ad,sa as bd,aa as cd,Sv as dd,Av as ed,Iv as fd,Mv as gd,_1 as hd,y1 as id,h1 as jd,v1 as kd,k1 as ld,eE as md,tE as nd,wa as od,oE as pd,iE as qd,x1 as rd,Uo as sd,N1 as td,D1 as ud,P1 as vd,M1 as wd,$1 as xd,j1 as yd,L1 as zd,mf as Ad,F1 as Bd,U1 as Cd,pf as Dd,z1 as Ed,zo as Fd,H1 as Gd,q1 as Hd,V1 as Id,B1 as Jd,W1 as Kd,Ho as Ld,G1 as Md,bn as Nd,K1 as Od,Y1 as Pd,X1 as Qd,J1 as Rd,Z1 as Sd,wn as Td,iM as Ud,lE as Vd,gf as Wd,Tt as Xd,Je as Yd,bf as Zd,Ze as _d,ie as $d,Sa as ae,Ce as be,ue as ce,bM as de,wM as ee,Cf as fe,Rf as ge,Oa as he,xf as ie,Nf as je,vM as ke,CM as le,VE as me,RM as ne,Ff as oe,Uf as pe,wr as qe,xM as re,NM as se,Aa as te,Ia as ue,PM as ve,Ta as we,Hf as xe,ZE as ye,MM as ze,Yo as Ae,e0 as Be,FM as Ce,Xo as De,o$ as Ee,x0 as Fe,K0 as Ge,Qo as He,mk as Ie,i$ as Je,s$ as Ke,On as Le,tm as Me,nm as Ne,rm as Oe,za as Pe,om as Qe,d$ as Re,im as Se,l$ as Te,sm as Ue,Rt as Ve,qa as We,m$ as Xe,p$ as Ye,ni as Ze,ri as _e,Wk as $e,li as af,Zk as bf,fe as cf,tS as df,Za as ef,xm as ff,ec as gf,G$ as hf,K$ as if,Y$ as jf,X$ as kf,J$ as lf,Z$ as mf,dc as nf,lc as of,Fm as pf,dj as qf,lj as rf,uj as sf,fj as tf,mj as uf,pj as vf,pc as wf,Vm as xf,_j as yf,yj as zf,hj as Af,NS as Bf,gj as Cf,Gm as Df,_i as Ef,Mt as Ff,Ij as Gf,PS as Hf,MS as If,Cn as Jf,Y_ as Kf,BT as Lf,XT as Mf,KU as Nf,YU as Of,xr as Pf,xj as Qf,yi as Rf,US as Sf,zS as Tf,Nj as Uf,xe as Vf,Dj as Wf,WS as Xf,YS as Yf,nO as Zf,Zm as _f,dp as $f,vc as ag,yc as bg,gi as cg,oO as dg,rt as eg,Rn as fg,Tr as gg,xn as hg,Cr as ig,ep as jg,Mj as kg,Rr as lg,Pr as mg,it as ng,wO as og,Jj as pg,up as qg,vO as rg,RO as sg,NO as tg,fp as ug,DO as vg,PO as wg,mp as xg,jt as yg,pp as zg,Zj as Ag,Qj as Bg,Sc as Cg,eL as Dg,tL as Eg,nL as Fg,rL as Gg,oL as Hg,ve as Ig,Lt as Jg,uL as Kg,Oc as Lg,Ac as Mg,Si as Ng,gp as Og,Ic as Pg,bp as Qg,Nr as Rg,mL as Sg,Ft as Tg,DL as Ug,PL as Vg,YO as Wg,at as Xg,ML as Yg,$L as Zg,jL as _g,xp as $g,nA as ah,LL as bh,Dp as ch,xc as dh,zp as eh,Ne as fh,AA as gh,Hp as hh,qp as ih,Ai as jh,Nc as kh,$r as lh,eF as mh,tF as nh,jr as oh,Dc as ph,$c as qh,nF as rh,$A as sh,rF as th,oF as uh,qe as vh,X as wh,yF as xh,Ht as yh,GA as zh,hF as Ah,gF as Bh,KA as Ch,bF as Dh,wF as Eh,vF as Fh,ZA as Gh,a_ as Hh,QA as Ih,PF as Jh,tI as Kh,d_ as Lh,MF as Mh,f_ as Nh,iI as Oh,o_ as Ph,Hc as Qh,b_ as Rh,E_ as Sh,UF as Th,k_ as Uh,HF as Vh,T_ as Wh,R_ as Xh,KF as Yh,YF as Zh,zI as _h,zr as $h,Pi as ai,fU as bi,mU as ci,oC as di,Yi as ei,Gt as fi,Hr as gi,aC as hi,cC as ii,Sy as ji,Un as ki,bz as li,vd as mi,$i as ni,H_ as oi,od as pi,wz as qi,Ay as ri,q_ as si,vz as ti,Vr as ui,Br as vi,gT as wi,ji as xi,IU as yi,rd as zi,Li as Ai,TU as Bi,CU as Ci,B_ as Di,Fi as Ei,Ui as Fi,Kt as Gi,IT as Hi,RU as Ii,xU as Ji,mt as Ki,Qt as Li,Pz as Mi,Mz as Ni,$z as Oi,xy as Pi,jz as Qi,Lz as Ri,Fz as Si,Dy as Ti,es as Ui,Gz as Vi,nn as Wi,_2 as Xi,HC as Yi,Xy as Zi,y2 as _i,h2 as $i,is as aj,mh as bj,ph as cj,g2 as dj,b2 as ej,us as fj,yt as gj,cs as hj,bh as ij,A2 as jj,UR as kj,zR as lj,I2 as mj,vh as nj,qR as oj,$2 as pj};
116
+ //# sourceMappingURL=chunk-HQINCDF6.js.map