@unbrained/pm-cli 2026.11.21 → 2026.11.22

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 (203) hide show
  1. package/.agents/skills/pm-developer/SKILL.md +1 -1
  2. package/.claude-plugin/marketplace.json +1 -1
  3. package/dist/cli/register-history-maintenance.js +2 -2
  4. package/dist/cli-bundle/bundle-manifest.json +1 -1
  5. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +9 -0
  6. package/dist/cli-bundle/chunks/{chunk-PJXKA4QU.js → chunk-4TB5D6HL.js} +37 -37
  7. package/dist/cli-bundle/chunks/{chunk-WELSVDPU.js → chunk-5ZMVLWE3.js} +2 -2
  8. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +33 -0
  9. package/dist/cli-bundle/chunks/{chunk-JVGRFU5H.js → chunk-AR4NP5HI.js} +2 -2
  10. package/dist/cli-bundle/chunks/{chunk-XHJ3H5PL.js → chunk-B4PPFOPY.js} +3 -3
  11. package/dist/cli-bundle/chunks/{chunk-5647LU3A.js → chunk-B76TFRO2.js} +47 -45
  12. package/dist/cli-bundle/chunks/{chunk-YJEBK7HU.js → chunk-CAR2L5NW.js} +2 -2
  13. package/dist/cli-bundle/chunks/{chunk-D6ILFXZY.js → chunk-EIGUKEV6.js} +2 -2
  14. package/dist/cli-bundle/chunks/{chunk-XWHJIRNV.js → chunk-GTPCAJMZ.js} +2 -2
  15. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +2 -0
  16. package/dist/cli-bundle/chunks/{chunk-CASX6SFI.js → chunk-HC2OPETM.js} +2 -2
  17. package/dist/cli-bundle/chunks/{chunk-NCFCBKIP.js → chunk-HKUV74K3.js} +2 -2
  18. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +115 -0
  19. package/dist/cli-bundle/chunks/{chunk-S6HB3WL2.js → chunk-J2LABXBL.js} +2 -2
  20. package/dist/cli-bundle/chunks/{chunk-BKSVHOWI.js → chunk-J52BEBSS.js} +2 -2
  21. package/dist/cli-bundle/chunks/{chunk-NT5AKFE5.js → chunk-OJTMGDON.js} +31 -31
  22. package/dist/cli-bundle/chunks/{chunk-SRVTCYAU.js → chunk-TC6XLIYO.js} +2 -2
  23. package/dist/cli-bundle/chunks/{chunk-AHQB7W2H.js → chunk-U7EL3AYA.js} +2 -2
  24. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +6 -0
  25. package/dist/cli-bundle/chunks/{chunk-CIKGG34F.js → chunk-X6MIWTTT.js} +2 -2
  26. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +2 -0
  27. package/dist/cli-bundle/chunks/{chunk-RMIRNYRG.js → chunk-XFHPKXAE.js} +2 -2
  28. package/dist/cli-bundle/chunks/{chunk-6QLEXRUG.js → chunk-YHVLVSEZ.js} +2 -2
  29. package/dist/cli-bundle/chunks/{item-revision-R5SZPJZ5.js → item-revision-4QBMZXKX.js} +2 -2
  30. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +2 -0
  31. package/dist/cli-bundle/chunks/{mutation-actor-3TG636XG.js → mutation-actor-FWLYWJ37.js} +2 -2
  32. package/dist/cli-bundle/chunks/{mutation-admission-LICSDNNO.js → mutation-admission-7ZDCK3G2.js} +2 -2
  33. package/dist/cli-bundle/chunks/{register-list-query-SPGPS3OS.js → register-list-query-RR5KACJ3.js} +2 -2
  34. package/dist/cli-bundle/chunks/{register-mutation-WWVECKFQ.js → register-mutation-57AJQWFV.js} +2 -2
  35. package/dist/cli-bundle/chunks/{register-operations-L6HFJNWD.js → register-operations-RKWST7CU.js} +2 -2
  36. package/dist/cli-bundle/chunks/{register-setup-K7UFG5TD.js → register-setup-CMI23PC5.js} +2 -2
  37. package/dist/cli-bundle/chunks/{stage-57KH3KAC.js → stage-4KDVXC5Z.js} +2 -2
  38. package/dist/cli-bundle/focused-chunks/{chunk-YOAYY3HE.js → chunk-2ZD7275J.js} +2 -2
  39. package/dist/cli-bundle/focused-chunks/{chunk-532WZV65.js → chunk-324AHXJO.js} +2 -2
  40. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +91 -0
  41. package/dist/cli-bundle/focused-chunks/{chunk-QGKLRXP7.js → chunk-4JZITIJB.js} +2 -2
  42. package/dist/cli-bundle/focused-chunks/{chunk-CU2BRAOX.js → chunk-4KTFKSS3.js} +2 -2
  43. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +78 -0
  44. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +2 -0
  45. package/dist/cli-bundle/focused-chunks/{chunk-MKM5NKD7.js → chunk-BRZV7BFV.js} +2 -2
  46. package/dist/cli-bundle/focused-chunks/{chunk-RPE6IX26.js → chunk-HDEKFSOK.js} +2 -2
  47. package/dist/cli-bundle/focused-chunks/{chunk-LNHUE4VV.js → chunk-IWOXAUDU.js} +2 -2
  48. package/dist/cli-bundle/focused-chunks/{chunk-J63D6QST.js → chunk-ML3JHCC6.js} +2 -2
  49. package/dist/cli-bundle/focused-chunks/{chunk-JMQJBZQ5.js → chunk-OPGOOP25.js} +2 -2
  50. package/dist/cli-bundle/focused-chunks/{chunk-XCJSHNXK.js → chunk-RE7ZWT7D.js} +3 -3
  51. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +3 -0
  52. package/dist/cli-bundle/focused-chunks/{chunk-WXMI4AV5.js → chunk-RQ252B6V.js} +2 -2
  53. package/dist/cli-bundle/focused-chunks/{chunk-7A4QWNZX.js → chunk-URGHTTT3.js} +2 -2
  54. package/dist/cli-bundle/focused-chunks/{chunk-IQK5NPMG.js → chunk-USPYKWQG.js} +2 -2
  55. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +102 -0
  56. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +44 -0
  57. package/dist/cli-bundle/focused-chunks/{chunk-UOC6257J.js → chunk-WZWXGDYY.js} +2 -2
  58. package/dist/cli-bundle/focused-chunks/{chunk-NP72ZDXE.js → chunk-YKSLZPLT.js} +2 -2
  59. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +2 -0
  60. package/dist/cli-bundle/focused-chunks/{item-revision-3V3UIP5X.js → item-revision-2O6MLPEX.js} +2 -2
  61. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +2 -0
  62. package/dist/cli-bundle/focused-chunks/{mutation-actor-62HKR5IO.js → mutation-actor-TCYDPUGG.js} +2 -2
  63. package/dist/cli-bundle/focused-chunks/{mutation-admission-X4PF2SG3.js → mutation-admission-LY73EJWM.js} +2 -2
  64. package/dist/cli-bundle/focused-chunks/{stage-O7T7CXBB.js → stage-DQ7RQQ52.js} +2 -2
  65. package/dist/cli-bundle/main.js +2 -2
  66. package/dist/cli-bundle/sdk-authoring.js +1 -1
  67. package/dist/cli-bundle/sdk-contracts.js +2 -2
  68. package/dist/cli-bundle/sdk-core.js +1 -1
  69. package/dist/cli-bundle/sdk-governance.js +1 -1
  70. package/dist/cli-bundle/sdk-graph.js +1 -1
  71. package/dist/cli-bundle/sdk-merge.js +70 -58
  72. package/dist/cli-bundle/sdk-query.js +1 -1
  73. package/dist/cli-bundle/sdk-runtime.js +1 -1
  74. package/dist/cli-bundle/sdk-testing.js +1 -1
  75. package/dist/cli-bundle/sdk.js +11 -11
  76. package/dist/core/diagnostics/remediation.js +1 -1
  77. package/dist/core/fs/atomic-create.js +1 -1
  78. package/dist/core/fs/file-glob.js +1 -1
  79. package/dist/core/history/bridge.js +2 -0
  80. package/dist/core/history/drift-scan.js +1 -1
  81. package/dist/core/history/history-rewrite.js +1 -1
  82. package/dist/core/history/history.d.ts +12 -0
  83. package/dist/core/history/history.js +2 -2
  84. package/dist/core/history/projection.js +1 -1
  85. package/dist/core/history/read.d.ts +9 -0
  86. package/dist/core/history/read.js +1 -1
  87. package/dist/core/history/replay.d.ts +46 -5
  88. package/dist/core/history/replay.js +2 -2
  89. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  90. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +1 -1
  91. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  92. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  93. package/dist/sdk/cli-contracts/typed-action-inputs.d.ts +2 -2
  94. package/dist/sdk/completion/fish.js +3 -2
  95. package/dist/sdk/completion/zsh.js +3 -2
  96. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  97. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  98. package/dist/sdk/governance/health/history-drift-remedies.js +2 -0
  99. package/dist/sdk/governance/health.js +2 -2
  100. package/dist/sdk/history/append-only-repair.d.ts +30 -0
  101. package/dist/sdk/history/append-only-repair.js +6 -0
  102. package/dist/sdk/history/maintenance.d.ts +8 -2
  103. package/dist/sdk/history/maintenance.js +1 -1
  104. package/dist/sdk/history/reanchor-refusal.js +2 -0
  105. package/dist/sdk/history/reseed.d.ts +15 -0
  106. package/dist/sdk/history/reseed.js +2 -0
  107. package/dist/sdk/history/salvage.d.ts +19 -8
  108. package/dist/sdk/history/salvage.js +5 -3
  109. package/dist/sdk/history-compact.js +1 -1
  110. package/dist/sdk/history-redact.js +1 -1
  111. package/dist/sdk/history-repair.d.ts +8 -2
  112. package/dist/sdk/history-repair.js +1 -1
  113. package/dist/sdk/index.d.ts +1 -1
  114. package/dist/sdk/item-transaction.d.ts +33 -1
  115. package/dist/sdk/item-transaction.js +1 -1
  116. package/dist/sdk/lifecycle/restore.js +1 -1
  117. package/dist/sdk/merge/three-way.d.ts +22 -3
  118. package/dist/sdk/merge/three-way.js +8 -2
  119. package/dist/sdk/public-surface.json +1 -1
  120. package/dist/sdk/runtime/actions.js +1 -1
  121. package/dist/sdk/runtime-input.d.ts +6 -2
  122. package/dist/sdk/runtime-input.js +1 -1
  123. package/dist/sdk/runtime-primitives.d.ts +1 -1
  124. package/dist/sdk/runtime-primitives.js +1 -1
  125. package/dist/sdk/runtime.d.ts +7 -0
  126. package/dist/sdk/runtime.js +1 -1
  127. package/dist/sdk/structured-mutations.d.ts +5 -5
  128. package/dist/sdk/structured-mutations.js +1 -1
  129. package/dist/sdk/transactions/item-finalization.js +2 -0
  130. package/dist/types.d.ts +20 -0
  131. package/dist/types.js +1 -1
  132. package/docs/AGENT_GUIDE.md +1 -1
  133. package/docs/AGENT_RUNTIME_PRIMITIVES.md +1 -1
  134. package/docs/COMMANDS.md +6 -2
  135. package/docs/HISTORY_RECOVERY.md +229 -5
  136. package/docs/README.md +2 -2
  137. package/docs/SDK.md +103 -4
  138. package/docs/SDK_CONTEXT_COORDINATION.md +3 -2
  139. package/marketplace.json +1 -1
  140. package/node_modules/tar/package.json +2 -3
  141. package/package.json +30 -2
  142. package/packages/pm-beads/package.json +1 -1
  143. package/packages/pm-calendar/package.json +1 -1
  144. package/packages/pm-command-kit/package.json +1 -1
  145. package/packages/pm-digital-twin/package.json +1 -1
  146. package/packages/pm-governance-audit/package.json +1 -1
  147. package/packages/pm-guide-shell/package.json +1 -1
  148. package/packages/pm-kanban/package.json +1 -1
  149. package/packages/pm-lifecycle-hooks/package.json +1 -1
  150. package/packages/pm-linked-test-adapters/package.json +1 -1
  151. package/packages/pm-search-advanced/package.json +1 -1
  152. package/packages/pm-templates/package.json +1 -1
  153. package/packages/pm-todos/package.json +1 -1
  154. package/packages/pm-vcs/package.json +1 -1
  155. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  156. package/plugins/pm-claude/package.json +1 -1
  157. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  158. package/plugins/pm-codex/package.json +1 -1
  159. package/plugins/pm-codex/plugin.json +1 -1
  160. package/runtime-dependencies.json +1 -1
  161. package/dist/cli-bundle/chunks/chunk-2DXRTIC6.js +0 -21
  162. package/dist/cli-bundle/chunks/chunk-IUIOTAF6.js +0 -9
  163. package/dist/cli-bundle/chunks/chunk-KVBIMFUG.js +0 -6
  164. package/dist/cli-bundle/chunks/chunk-RULHZRFN.js +0 -2
  165. package/dist/cli-bundle/chunks/chunk-SA4BNP3Q.js +0 -2
  166. package/dist/cli-bundle/chunks/chunk-YKJKQ7DM.js +0 -115
  167. package/dist/cli-bundle/chunks/item-transaction-7DFCG73I.js +0 -2
  168. package/dist/cli-bundle/focused-chunks/chunk-CWWKRI5P.js +0 -2
  169. package/dist/cli-bundle/focused-chunks/chunk-HGFNL5XI.js +0 -2
  170. package/dist/cli-bundle/focused-chunks/chunk-OSLQD5VH.js +0 -102
  171. package/dist/cli-bundle/focused-chunks/chunk-QSJW6NSQ.js +0 -66
  172. package/dist/cli-bundle/focused-chunks/chunk-SRDQSA6M.js +0 -91
  173. package/dist/cli-bundle/focused-chunks/chunk-URJ2E6AS.js +0 -3
  174. package/dist/cli-bundle/focused-chunks/chunk-XQQSSKJI.js +0 -44
  175. package/dist/cli-bundle/focused-chunks/item-transaction-HLBW7B3J.js +0 -2
  176. package/dist/sdk/agent/refusal-closure.js +0 -2
  177. package/dist/sdk/agent/refusal-reachability.js +0 -4
  178. package/dist/sdk/agent/task-transcript-contracts.js +0 -2
  179. package/dist/sdk/agent/tracker-preflight-contracts.js +0 -2
  180. package/dist/sdk/authoring.js +0 -2
  181. package/dist/sdk/compose.js +0 -2
  182. package/dist/sdk/contracts.js +0 -2
  183. package/dist/sdk/core-governance.js +0 -2
  184. package/dist/sdk/core.js +0 -2
  185. package/dist/sdk/corpus-shape.js +0 -2
  186. package/dist/sdk/define.js +0 -2
  187. package/dist/sdk/environment/agent-environment.js +0 -2
  188. package/dist/sdk/governance/artifact-ledgers.js +0 -2
  189. package/dist/sdk/governance/coverage-assurance.js +0 -2
  190. package/dist/sdk/governance/reliability.js +0 -2
  191. package/dist/sdk/governance.js +0 -2
  192. package/dist/sdk/graph/adapter.js +0 -2
  193. package/dist/sdk/graph/conformance.js +0 -2
  194. package/dist/sdk/graph/index.js +0 -2
  195. package/dist/sdk/graph.js +0 -2
  196. package/dist/sdk/index.js +0 -2
  197. package/dist/sdk/query.js +0 -2
  198. package/dist/sdk/relationship-migration.js +0 -2
  199. package/dist/sdk/testing.js +0 -8
  200. package/dist/sdk/workspace-recipe.js +0 -2
  201. package/docs/AGENT_PROVENANCE_ADR.md +0 -206
  202. package/docs/DEFECT_RECURRENCE.md +0 -257
  203. package/docs/PERFORMANCE.md +0 -204
@@ -1,2 +0,0 @@
1
- import{B as Ue,C as je,E as J,H as De,J as Fe,K as Pe,M as Ge,a as Me,p as W}from"./chunk-XQQSSKJI.js";import"./chunk-UOC6257J.js";import"./chunk-CWWKRI5P.js";import{A as K,B as Ie,C as L,D as Ce,y as Re,z as M}from"./chunk-QSJW6NSQ.js";import"./chunk-LNHUE4VV.js";import"./chunk-WXMI4AV5.js";import"./chunk-3V53UBHN.js";import"./chunk-532WZV65.js";import"./chunk-J63D6QST.js";import"./chunk-SVOOGGAK.js";import"./chunk-NP72ZDXE.js";import{T as Ee,W as Oe}from"./chunk-URJ2E6AS.js";import"./chunk-7A4QWNZX.js";import"./chunk-YOAYY3HE.js";import{Ga as Ne}from"./chunk-IQK5NPMG.js";import"./chunk-CU2BRAOX.js";import"./chunk-JMQJBZQ5.js";import{H as x}from"./chunk-XCJSHNXK.js";import{ra as le,xa as me}from"./chunk-HGFNL5XI.js";import"./chunk-RPE6IX26.js";import"./chunk-QGKLRXP7.js";import"./chunk-GHQVM6K6.js";import{L as $e,l as q}from"./chunk-SRDQSA6M.js";import{i as Ae,m as Te,s as ke}from"./chunk-MKM5NKD7.js";import"./chunk-I5LGPUWH.js";import"./chunk-C3O6JJPO.js";import{Ga as pe,Gf as _e,Hf as G,Mf as Se,Nf as be,Od as we,Re as k,Ve as ve,_e as $,ec as fe,gc as P,hc as he,kc as ye,oe as ge,qe as T,ra as F,ya as ue}from"./chunk-OSLQD5VH.js";import"./chunk-EGN2HFRU.js";import"./chunk-CR7CGEB2.js";import{A as p,E as D,G as de,H as O,l as ae,q as E,s as se,x as ce,z as m}from"./chunk-3IRCYJI5.js";import X from"node:crypto";import{constants as V,readFileSync as pt}from"node:fs";import{cp as lt,lstat as Le,mkdir as mt,mkdtemp as We,open as ft,readdir as ht,realpath as Je,rm as ze,stat as Z,writeFile as Be}from"node:fs/promises";import{tmpdir as Ve}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]="01728cbc-2037-50d2-8318-5f106714b8da")}catch{}})();var ot=new Set(["id","title","description","type","status","priority","tags","body","deadline","estimated_minutes","acceptance_criteria","definition_of_ready","order","rank","assignee",...ae,"affected_version","fixed_version","component","regression","customer_impact","close_reason","completed_at","dependencies","comments","notes","learnings","files","tests","docs","reminders","events","type_options"]);(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="6456f85b-e076-5048-9c21-03d477267259")}catch{}})();function z(e,t,n){let r=e?.estimatedMinutes;if(!(r===void 0||typeof r=="string"))throw new p(`Mutation ${n+1} ${t} option "estimatedMinutes" must be a string.`,m.USAGE,{code:"mutation_option_value_invalid",required:'Pass estimatedMinutes as a string, for example "45", in raw mutation options.',why:"Raw options use the create/update command option types; item documents accept numeric estimated_minutes instead.",nextSteps:["Quote the estimatedMinutes value or use an item document with numeric estimated_minutes, then retry the transaction."]})}(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="37abb7b8-a5c3-5bdd-ad3a-9dc5189e834f")}catch{}})();var at=["op","id","reason","options","unique","match"],st=[...at,"ref"],yn=[...st,"item"];var qe="[a-z][a-z0-9._-]{0,63}",wn=new RegExp(`^${qe}$`,"u"),gn=new RegExp(`(^|,)id=@(${qe})(?=,|$)`,"gu"),xe=e=>e.slice(2).replaceAll(/-([a-z])/gu,(t,n)=>n.toUpperCase());var ct=new Set(["created_at","updated_at","closed_at","version","format_version","path","author","collection_counts","notes_count","tests_count","pm_format_version","claim_principal","test_runs","deferred_fields"]),vn=new Set([...ct,"completed_at","id"]),_n={create:Ee.map(e=>e.target),update:Oe.map(e=>e.target),close:le.map(e=>xe(e.flag)).filter(e=>e!=="reason"),release:me.map(e=>xe(e.flag))};function dt(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function ut(e,t){return e<t?-1:+(e!==t)}function B(e){return Array.isArray(e)?e.map(B):dt(e)?Object.fromEntries(Object.entries(e).sort(([t],[n])=>ut(t,n)).map(([t,n])=>[t,B(n)])):e}function S(e){return typeof e=="string"?e.trim():JSON.stringify(B(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]="359a47e6-c7e8-5713-bd07-1e19fb81674a")}catch{}})();async function yt(e,t){if(!Te(e))return{schema:P(t.schema),typeDefinitionsFromFile:[]};let n=await Mt(e,t.schema);return{schema:n.schema,typeDefinitionsFromFile:n.type_definitions_from_file??[]}}async function wt(e,t,n,r){let i=F({...t,item_types:{...t.item_types,definitions:[...t.item_types?.definitions??[],...n.typeDefinitionsFromFile]}},G());return(await $e(e,t.item_format,i.type_to_folder,void 0,n.schema)).flatMap(a=>{let o=a[r];return o==null?[]:[{id:a.id,value:o}]})}function Q(e){let t=new Map,n=async r=>{let i=await ke(e),a=await yt(e,i),o=new Map;for(let s of await wt(e,i,a,r)){let d=S(s.value);o.set(d,[...o.get(d)??[],s.id])}return o};return{lookup(r){let i=t.get(r)??n(r);return t.set(r,i),i},async recordCreate(r){for(let[i,a]of t){let o=r[i];if(o==null)continue;let s=await a,d=S(o);s.set(d,[...s.get(d)??[],String(r.id)])}},invalidate(){t.clear()}}}async function gt(e,t){let n=S(t.value),r=(await e.lookup(t.key)).get(n)??[];if(r.length!==0)throw new p(`Upsert key "${t.key}" value ${JSON.stringify(n)} now matches existing item ${r.join(", ")}; the plan was resolved before it existed.`,m.CONFLICT,{code:"upsert_key_conflict",required:"Re-plan the document so the row updates the existing item instead of creating a duplicate.",why:"Keyed upsert is resolved before the writer lock, so every remaining create is re-checked under the lock; concurrent imports therefore cannot create two items for one key value.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan turns the row into an update of the existing item.","Inspect the existing item first when its content should win over the document row."]})}function vt(e,t,n){let r=e.metadata[n.key],i=S(n.value);if(S(r)!==i)throw new p(`Item ${t} no longer carries upsert key "${n.key}" value ${JSON.stringify(i)}; the plan selected it before the key changed.`,m.CONFLICT,{code:"upsert_match_changed",required:"Re-plan the document so the row is resolved against the current key values.",why:"Keyed upsert selects its target before the writer lock, so the update re-reads the key under the lock instead of updating a mismatched item blindly.",nextSteps:["Re-run pm item mutate with the same document and --upsert-key; the re-plan creates or re-targets the row from the current key values."]})}function Ke(e){if(e===null||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.key=="string"&&t.key.trim().length>0&&t.value!==void 0&&t.value!==null}function N(e,t){let n={...e,...t};return e===void 0?n:x(e,n)}async function _(e,t){try{let n=(await W(t,{},{pmRoot:e})).item;return{id:n.id,closedAt:n.closed_at,updatedAt:n.updated_at,assignee:n.assignee,claimPrincipal:n.claim_principal}}catch(n){if(n instanceof p&&n.exitCode===m.NOT_FOUND)return;throw n}}function ee(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_"),r=X.createHash("sha256").update(pe(e)).digest("hex").slice(0,12);return`${t+1}-${e.op}-${n}-${r}`}function _t(e,t){let n=e.id.replaceAll(/[^a-zA-Z0-9._-]/gu,"_");return`${t+1}-${e.op}-${n}`}function h(e,t,n){return`bulk-item-transaction ${e} ${t} ${n}`}function te(e,t){return e===t||(e?.startsWith(`${t} | `)??!1)}async function A(e,t,n,r){let i=await T(c.join(e,"history",`${t}.jsonl`),t),a=h(n,r,"apply"),o=h(n,r,"compensate");for(let s=i.length-1;s>=0;s-=1){let d=i[s].message;if(te(d,a))return!0;if(d===o)return!1}return!1}async function ne(e,t){let n=await _(e,t.id);if(n?.updatedAt===void 0)throw new p(`Bulk ${t.op} target ${t.id} does not exist or has no restorable version`,m.NOT_FOUND);let r=await T(c.join(e,"history",`${n.id}.jsonl`),n.id);if(r.length===0)throw new p(`Bulk ${t.op} target ${t.id} has no restorable history`,m.NOT_FOUND);return{target_updated_at:n.updatedAt,target_version:String(q(r)+r.length),target_history_hash:k(r),target_history_length:r.length}}function b(e,t,n){return new p(`Transaction ${e.transactionId} cannot safely compensate incomplete step ${n}; review item ${t} history before recovery.`,m.CONFLICT,{code:"transaction_partial_mutation",item_id:t,required:"Reconcile the item's partial or intervening changes before resuming this transaction.",why:"The retained history does not prove exclusive ownership of the changes to undo. The journal remains compensating instead of claiming a rollback or overwriting another writer.",nextSteps:[`Run pm history ${t} and inspect this transaction's retained compensation data before explicitly restoring or reconciling the item.`]})}function He(e,t){let n=`bulk-item-transaction ${t} `;return[e.message,e.context?.item_transaction_step].some(r=>typeof r=="string"&&r.startsWith(n))}function St(e,t,n){let{expectedHistory:r,length:i,version:a}=t;if(k(e)===r)return!1;if(typeof i!="number"||!Number.isSafeInteger(i)||i<1||k(e.slice(0,i))!==r||a!==String(q(e)+i))throw b(n,n.itemId,n.stepId);let o=h(n.transactionId,n.stepId,"apply"),s=e.slice(i),d=f=>te(f.message,o)||f.context?.item_transaction_step===o,u=h(n.transactionId,n.stepId,"compensate");if(s.filter(f=>d(f)||f.message===u).at(-1)?.message===u)return!1;let l=s.filter(d);if(l.length===0)return!1;let g=e.at(-1).after_hash===l.at(-1).after_hash&&s.every(f=>He(f,n.transactionId));if(l.length!==s.length&&!g)throw b(n,n.itemId,n.stepId);return!0}async function Ye(e,t){let n=c.join(e,"history",`${t}.jsonl`),r=await ge(n,t);return{history:r.entries,assertOwnedUnderLock:(i,a)=>{let o;try{o=pt(n).equals(r.raw_bytes)&&ve(i)===r.entries.at(-1).after_hash}catch(s){throw Object.assign(a(),{cause:s})}if(!o)throw a()}}}async function U(e,t,n,r){let i=r!==null&&typeof r=="object"&&!Array.isArray(r)?r:void 0;if(i===void 0||typeof i.target_updated_at!="string")return;let a=i.target_updated_at,o=await _(e.pmRoot,t);if(o===void 0)return;let{history:s,assertOwnedUnderLock:d}=await Ye(e.pmRoot,o.id),u=i.target_history_hash,l=typeof u=="string";if(typeof u=="string"){if(!St(s,{expectedHistory:u,length:i.target_history_length,version:i.target_version},{...e,itemId:o.id,stepId:n}))return}else{if(o.updatedAt===a)return;if(!await A(e.pmRoot,o.id,e.transactionId,n))throw b(e,o.id,n)}let g=()=>Pe(t,typeof i.target_version=="string"?i.target_version:a,{force:!0,author:e.author,message:h(e.transactionId,n,"compensate")},{pmRoot:e.pmRoot});await $({pmRoot:e.pmRoot,id:o.id,validate:f=>{d(f,()=>b(e,o.id,n))},compensation:Ze(e,t,n,"restore",l)},g)}var Xe=new WeakMap;function Ze(e,t,n,r,i){let a=i?Re(e.pmRoot,e.transactionId):void 0,o=a===void 0?void 0:Xe.get(a);if(!(o?.stepId!==n||o.itemId!==t||o.operation!==r))return{transaction_id:e.transactionId,step_id:n,operations:[r],overrides:[]}}function Qe(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);if(r===void 0)return{state:"pending"};if(r.closedAt!==void 0){let i=await T(c.join(e.pmRoot,"history",`${r.id}.jsonl`),r.id),a=`Compensated: interrupted bulk transaction ${e.transactionId}`;if(i.filter(o=>o.op==="close").at(-1)?.patch.some(o=>o.op==="add"||o.op==="replace"?o.path==="/metadata/close_reason"&&o.value===a:!1)??!1)throw new p(`Created item ${r.id} remains closed by transaction compensation; explicitly reopen or reconcile it before retrying.`,m.CONFLICT,{code:"transaction_create_compensated",item_id:r.id,required:"Review the compensated item and explicitly reopen it before retrying the same document.",why:"This item's latest closure belongs to transaction compensation. Automatically reopening it could overwrite later lifecycle decisions.",nextSteps:[`Run pm item reopen ${r.id} "Retry compensated creation" after reviewing its history, then retry the transaction.`]})}return{state:"applied",result:{id:r.id,op:"create"}}},async apply(){t.unique!==void 0&&await gt(e.uniqueIndex,t.unique);let r=await Ue(N(t.options,{author:e.author,id:t.id,message:h(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=r.item;return e.onCreateWarnings?.(String(i.id),r.warnings),await e.uniqueIndex.recordCreate(i),{id:String(i.id),op:"create"}},async compensate(){await bt(e,t.id,n)}}}async function bt(e,t,n){let r=await _(e.pmRoot,t);if(r===void 0||e.createCompensation==="close"&&r.closedAt!==void 0)return;let{history:i,assertOwnedUnderLock:a}=await Ye(e.pmRoot,r.id),o=h(e.transactionId,n,"apply"),s=h(e.transactionId,n,"compensate"),d=i.filter(u=>te(u.message,o)||u.message===s).at(-1);if(d?.message!==s){if(d===void 0||!i.every(u=>He(u,e.transactionId)))throw b(e,r.id,n);await $({pmRoot:e.pmRoot,id:r.id,validate:u=>{a(u,()=>b(e,r.id,n))},compensation:Ze(e,t,n,e.createCompensation==="delete"?"delete":"close",!0)},async()=>{let u={force:!0,author:e.author,message:s};e.createCompensation==="delete"?await Fe(t,u,{pmRoot:e.pmRoot}):await J(t,`Compensated: interrupted bulk transaction ${e.transactionId}`,{...u,validateClose:"off"},{pmRoot:e.pmRoot})})}}function Et(e,t,n){return{id:n,compensatePending:!0,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await A(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"update"}}:{state:"pending"}},async prepareCompensation(){return ne(e.pmRoot,t)},async apply(){let r=()=>je(t.id,N(t.options,{author:e.author,message:h(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot}),i=t.match,a=i,o=(await $({pmRoot:e.pmRoot,id:String((await W(t.id,{},{pmRoot:e.pmRoot})).item.id),validate:s=>{a!==void 0&&vt(s,t.id,a)},committed:s=>{i!==void 0&&(a={key:i.key,value:structuredClone(s.metadata[i.key])})},historyContext:{item_transaction_step:h(e.transactionId,n,"apply")}},r)).item;return e.uniqueIndex.invalidate(),{id:String(o.id),op:"update"}},async compensate(r){await U(e,t.id,n,r)}}}function Ot(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await A(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"close"}}:r.closedAt===void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"close"}}},async prepareCompensation(){return ne(e.pmRoot,t)},async apply(){let r=(await J(t.id,t.reason,N(t.options,{author:e.author,message:h(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(r.id),op:"close"}},async compensate(r){await U(e,t.id,n,r)}}}function At(e,t,n){return{id:n,async inspect(){let r=await _(e.pmRoot,t.id);return r===void 0?{state:"pending"}:await A(e.pmRoot,r.id,e.transactionId,n)?{state:"applied",result:{id:r.id,op:"release"}}:r.assignee!==void 0||r.claimPrincipal!==void 0?{state:"pending"}:{state:"applied",result:{id:r.id,op:"release"}}},async prepareCompensation(){return ne(e.pmRoot,t)},async apply(){let r=(await De(t.id,N(t.options,{author:e.author,message:h(e.transactionId,n,"apply")}),{pmRoot:e.pmRoot})).item;return e.uniqueIndex.invalidate(),{id:String(r.id),op:"release"}},async compensate(r){await U(e,t.id,n,r)}}}function re(e,t,n){let r=ee(t,n),i=Tt(e,t,r);return Xe.set(i,{transactionId:e.transactionId,stepId:r,itemId:t.id,operation:t.op!=="create"?"restore":e.createCompensation==="delete"?"delete":"close"}),i}function Tt(e,t,n){switch(t.op){case"create":return Qe(e,t,n);case"update":return Et(e,t,n);case"close":return Ot(e,t,n);case"release":return At(e,t,n)}}function kt(e,t){if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError(`Bulk mutation ${t+1} must be an object`);if(!["create","update","close","release"].includes(e.op))throw new TypeError(`Bulk mutation ${t+1} op must be create, update, close, or release`);if(typeof e.id!="string"||e.id.trim().length===0)throw new TypeError(`Bulk mutation ${t+1} requires a non-empty id`);if(e.op==="close"&&(typeof e.reason!="string"||e.reason.trim().length===0))throw new TypeError(`Bulk close mutation ${t+1} requires a non-empty reason`);if(e.op==="create"&&e.unique!==void 0&&!Ke(e.unique))throw new TypeError(`Bulk create mutation ${t+1} unique must be an object with a non-empty key and a value`);if(e.op==="update"&&e.match!==void 0&&!Ke(e.match))throw new TypeError(`Bulk update mutation ${t+1} match must be an object with a non-empty key and a value`);z(e.options,e.op,t)}function et(e){if(e.length===0)throw new TypeError("Bulk item transaction requires at least one mutation");let t=new Map;for(let[n,r]of e.entries()){if(kt(r,n),r.op!=="create"||r.unique===void 0)continue;let{key:i,value:a}=r.unique,o=t.get(i)??new Map,s=S(a),d=o.get(s);if(d!==void 0)throw new p(`Bulk create mutations ${d+1} and ${n+1} share the upsert key value ${JSON.stringify(s)} for "${i}".`,m.USAGE,{code:"upsert_key_duplicate",required:"Each create must carry a distinct unique key value within one batch.",why:"Direct SDK batches must preserve the same uniqueness invariant as planned document rows."});o.set(s,n),t.set(i,o)}}function tt(e){let t=[...e];return et(t),t.map(n=>{let r=structuredClone(n);return n.options!==void 0&&r.options!==void 0&&x(n.options,r.options),r})}function nt(e,t=""){return e===null||typeof e!="object"?[]:Object.entries(e).flatMap(([n,r])=>{let i=`${t}/${n.replaceAll("~","~0").replaceAll("/","~1")}`;return/^(created_at|updated_at|closed_at|completed_at|timestamp)$/u.test(n)?[i]:nt(r,i)})}async function H(e,t,n){try{return await n()}catch(r){throw r instanceof p?new p(r.message,r.exitCode,{...r.context,transaction_operation:{index:t,op:e.op,id:e.id}}):r}}function rt(e,t,n,r){let i=c.relative(e,t),a=i.split(c.sep);return a[0]==="extensions"&&a[2]==="node_modules"&&!r.some(o=>i===o||i.startsWith(`${o}${c.sep}`)||o.startsWith(`${i}${c.sep}`))?!1:["locks","runtime","search"].includes(i.split(c.sep)[0])?r.some(o=>i===o||i.startsWith(`${o}${c.sep}`)||o.startsWith(`${i}${c.sep}`)):i===""||n===void 0||n.some(o=>i===o||i.startsWith(`${o}${c.sep}`)||o.startsWith(`${i}${c.sep}`))}async function I(e,t){let n=await Le(t);if(n.isSymbolicLink())await Z(t);else if(n.isDirectory()||n.isFile())return n;throw O(c.relative(e,t))}async function $t(e,t){let n=await ft(t,V.O_RDONLY|V.O_NOFOLLOW|V.O_NONBLOCK);try{let r=await n.stat();if(!r.isFile())throw O(c.relative(e,t));let i=X.createHash("sha256");if(r.size>0)for await(let a of n.createReadStream({highWaterMark:64*1024,end:r.size-1,autoClose:!1}))i.update(a);return i.digest()}finally{await n.close()}}async function Y(e,t,n){let r=X.createHash("sha256");async function i(a){for(let o of(await ht(a)).sort()){let s=c.join(a,o);rt(e,s,t,n)&&((await I(e,s)).isDirectory()?await i(s):(r.update(JSON.stringify(c.relative(e,s))),r.update(await $t(e,s))))}}return await i(e),r.digest("hex")}function R(){return new p("Tracker changed while preparing the transaction preview; retry against stable state.",m.CONFLICT,{code:"transaction_preview_snapshot_changed"})}async function ie(e){if(!D(e))return!1;let t=e.path;if(typeof t!="string")return!1;let n=c.resolve(t),r=n;for(;;)try{let i=await Le(r);return r!==n&&i.isDirectory()}catch(i){if(!D(i))return!1;let a=c.dirname(r);if(a===r)return!1;r=a}}async function C(e,t){let n=c.join(e,t);try{let r=e;for(let i of t.split(c.sep).slice(0,-1))r=c.join(r,i),await I(e,r);if(!(await I(e,n)).isFile())throw O(t);return await de(n,O(t))}catch(r){if(await ie(r))return;throw r}}async function it(e,t,n,r){let i=P(n);for(let[a,o]of Object.entries(i.files)){let s=c.relative(e,he(e,o,fe[a]));if(s===""||!c.resolve(e,s).startsWith(c.join(e,c.sep)))throw new p("Transaction preview requires schema files inside the selected tracker root; relocate the configured schema file before retrying.",m.USAGE,{code:"transaction_preview_external_schema",field:`schema.files.${a}`});i.files[a]=s;let d=await C(e,s);if(r?.set(s,d),d!==void 0){let u=c.join(t,s);await mt(c.dirname(u),{recursive:!0}),await Be(u,d)}}return ye(t,i)}async function Mt(e,t){await Z(e);let n=await We(c.join(Ve(),"pm-schema-plan-"));try{let r=await Je(e);return await it(r,c.join(n,"configuration"),t)}catch(r){throw await ie(r)?R():r}finally{await ze(n,{recursive:!0,force:!0})}}async function Rt(e,t,n){let r=new Map,i=await C(e,E);r.set(E,i);let a;try{a=JSON.parse(i??"null")}catch{a=null}let o=Ae(a),s=o.success?o.data:void 0,d=await it(e,t,s?.schema,r),u=d.schema,l=c.relative(e,we(e));r.set(l,await C(e,l));let g=F({...ce,item_types:{definitions:[...s?.item_types?.definitions??[],...d.type_definitions_from_file??[]]}},n),f=ue(e)===e?[...se.filter(Boolean),E,Me,"transactions",...g.folders,...r.keys()].map(w=>c.normalize(w)):void 0,y=s===void 0?void 0:JSON.stringify({...a,schema:{...s.schema,files:u.files}});return{configuration:r,ownedPaths:f,stagedSettings:y,registryFolders:g.folders}}async function It(e,t,n){await Z(e);try{let r=await Je(e),i=await Rt(r,c.join(c.dirname(t),"configuration"),n),a=[...i.configuration.keys(),...i.registryFolders].map(u=>c.normalize(u)),o=await Y(r,i.ownedPaths,a);await lt(r,t,{recursive:!0,dereference:!1,filter:async u=>rt(r,u,i.ownedPaths,a)?(await I(r,u),!0):!1});let[s,d]=await Promise.all([Y(r,i.ownedPaths,a),Y(t,i.ownedPaths,a)]);if(o!==s||o!==d)throw R();for(let[u,l]of i.configuration)if(await C(t,u)!==l)throw R();i.stagedSettings!==void 0&&await Be(c.join(t,E),i.stagedSettings)}catch(r){throw await ie(r)?R():r}}async function Zn(e){let t=M(e),n=tt(e.mutations),r=G(),i=be(),a=await We(c.join(Ve(),"pm-transaction-preview-")),o=c.join(a,"tracker");try{await It(t.pmRoot,o,r);let s=!1,d=[],u=[],l=new Set;return await Se(i,()=>Ge({path:o,noExtensions:!0},async()=>{_e(r);let g={...t,pmRoot:o,createCompensation:"close",uniqueIndex:Q(o)},f=n.map((y,w)=>{let v=re({...g,onCreateWarnings:(j,oe)=>{oe.length>0&&d.push({index:w,id:j,op:"create",warnings:oe})}},y,w);return{...v,inspect:()=>H(y,w,()=>v.inspect()),prepareCompensation:()=>H(y,w,async()=>v.prepareCompensation?.()),apply:()=>H(y,w,async()=>{let j=await v.apply();return l.add(w),j})}});if(await K({...t,pmRoot:o,steps:f,onTransition:({transition:y})=>{y==="committed"&&(s=!0)}}),s)for(let[y,w]of n.entries()){let v=(await Ne(w.id,{path:o},{full:!0})).item;u.push({index:y,id:String(v.id),op:w.op,execution:l.has(y)?"applied":"adopted",item:v,commit_time_fields:nt(v)})}})),{records:u,validated:s,state:s?"staged_snapshot":"replayed_committed_plan",warnings:d,unresolved_commit_constraints:["concurrent_tracker_changes","extension_write_hooks","derived_extension_dependencies_excluded","generated_timestamps_and_provenance"]}}finally{await ze(a,{recursive:!0,force:!0})}}async function Ct(e){let t=M(e),n=tt(e.mutations),r=e.createCompensation??"close";if(!["close","delete"].includes(r))throw new TypeError("Bulk item transaction createCompensation must be close or delete");let i={...t,createCompensation:r,uniqueIndex:Q(t.pmRoot)},a=await K({...t,steps:n.map((s,d)=>re(i,s,d)),recoveryData:JSON.parse(JSON.stringify({kind:"item-mutations-v1",mutations:n,createCompensation:r})),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}}),o={};for(let[s,d]of n.entries()){let u=ee(d,s),l=a.results[u];o[_t(d,s)]=l}return{transactionId:a.transactionId,status:"committed",recovered:a.recovered,results:o}}function Nt(e){let t=[];return e.evidence!==void 0&&Object.keys(e.evidence).length>0&&t.push({op:"update",id:e.id,options:e.evidence}),t.push({op:"close",id:e.id,reason:e.reason,...e.closeOptions===void 0?{}:{options:e.closeOptions}},{op:"release",id:e.id,...e.releaseOptions===void 0?{}:{options:e.releaseOptions}}),t}function Qn(e){return Ct({pmRoot:e.pmRoot,transactionId:e.transactionId,author:e.author,mutations:Nt(e),...e.lockTtlSeconds===void 0?{}:{lockTtlSeconds:e.lockTtlSeconds},...e.lockWaitMs===void 0?{}:{lockWaitMs:e.lockWaitMs},...e.onTransition===void 0?{}:{onTransition:e.onTransition}})}var er={buildCreateStep:Qe,bulkHistoryMarker:h,compensateByRestore:U,deriveStepId:ee,isUpdateMarkerApplied:A,readItemSnapshot:_};async function tr(e,t){let n=await Ie(e,t);return n===void 0?void 0:{journal:n,planDigest:L(n)}}function Ut(e,t){let n=t.recoveryData;if(n===null||typeof n!="object"||Array.isArray(n)||n.kind!=="item-mutations-v1"||!Array.isArray(n.mutations)||!["close","delete"].includes(String(n.createCompensation)))throw new p("Transaction has no supported item recovery plan",m.CONFLICT,{code:"transaction_recovery_plan_missing",required:"Resume with the original plan and its original adapter.",why:"Legacy or foreign journals cannot safely reconstruct item compensation."});let r=n.mutations;et(r);let i={...e,createCompensation:n.createCompensation,uniqueIndex:Q(e.pmRoot)};return r.map((a,o)=>re(i,a,o))}async function nr(e){let t=M(e),n=await Ce({...e,...t,resolveSteps:r=>Ut({...e,...t},r)});return{journal:n,planDigest:L(n)}}export{er as _testOnlyItemTransaction,nr as abandonItemTransaction,Nt as buildItemCompletionMutations,Qn as commitItemCompletion,Ct as commitItemMutations,wt as listUpsertKeyCandidates,Mt as loadGuardedRuntimeSchema,Zn as previewItemMutations,tr as readItemTransaction,yt as resolveTransactionSchema};
2
- //# sourceMappingURL=item-transaction-HLBW7B3J.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d252409d-e33e-5c9e-9671-789f0ee87312")}catch{}})();import{EXIT_CODE}from"../../core/shared/constants.js";function listContractObservationFindings(observation){return[observation.expected_error_code!==void 0&&observation.error_code!==observation.expected_error_code?{code:"error_code_mismatch",probe_id:observation.probe_id,detail:`Expected error code ${observation.expected_error_code}, received ${observation.error_code??"<missing>"}.`}:void 0,observation.expected_allowed_values!==void 0&&JSON.stringify([...observation.allowed_values].sort())!==JSON.stringify([...observation.expected_allowed_values].sort())?{code:"incomplete_allowed_values",probe_id:observation.probe_id,detail:"The refusal's accepted domain differs from the SDK-owned domain contract."}:void 0,observation.expected_suggested_retry_args!==void 0&&(observation.suggested_retry_args?.length??0)===0?{code:"missing_suggested_retry_args",probe_id:observation.probe_id,detail:"The refusal omitted shell-free suggested retry arguments."}:void 0,observation.expected_suggested_retry_args!==void 0&&(observation.suggested_retry_args?.length??0)>0&&JSON.stringify(observation.suggested_retry_args)!==JSON.stringify(observation.expected_suggested_retry_args)?{code:"suggested_retry_args_mismatch",probe_id:observation.probe_id,detail:"The refusal's suggested retry arguments differ from the SDK-owned contract."}:void 0]}function listObservationFindings(observation){return[observation.exit_code!==EXIT_CODE.USAGE?{code:"non_refusal_exit",probe_id:observation.probe_id,detail:`${observation.entrypoint} returned exit code ${observation.exit_code}; a structured usage refusal must return ${EXIT_CODE.USAGE}.`}:void 0,observation.allowed_values_required!==!1&&observation.allowed_values.length===0?{code:"missing_allowed_values",probe_id:observation.probe_id,detail:"The refusal omitted its complete accepted value domain."}:void 0,observation.allowed_values.includes(observation.rejected_value)?{code:"accepted_rejected_value",probe_id:observation.probe_id,detail:`${observation.rejected_value} is both rejected and advertised as allowed.`}:void 0,observation.suggested_retry.trim().length===0?{code:"missing_suggested_retry",probe_id:observation.probe_id,detail:"The refusal omitted an executable suggested retry."}:void 0,observation.retry_succeeded?void 0:{code:"retry_failed",probe_id:observation.probe_id,detail:"The advertised suggested retry did not succeed."},...listContractObservationFindings(observation)]}function scorePmRefusalClosure(observations){const findings=[],seen=new Set;let closedProbeCount=0;observations.length===0&&findings.push({code:"empty_corpus",probe_id:"corpus",detail:"At least one real refusal observation is required."});for(const observation of observations){if(seen.has(observation.probe_id)){findings.push({code:"duplicate_probe",probe_id:observation.probe_id,detail:`${observation.probe_id} was supplied more than once.`});continue}seen.add(observation.probe_id);const findingCount=findings.length;for(const finding of listObservationFindings(observation))finding!==void 0&&findings.push(finding);findings.length===findingCount&&(closedProbeCount+=1)}return findings.sort((left,right)=>left.probe_id!==right.probe_id?left.probe_id.localeCompare(right.probe_id):left.code.localeCompare(right.code)),{ok:findings.length===0,probe_count:seen.size,closed_probe_count:closedProbeCount,closure_fraction:seen.size===0?0:closedProbeCount/seen.size,findings}}export{scorePmRefusalClosure};
2
- //# sourceMappingURL=refusal-closure.js.map
@@ -1,4 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7a1d7194-6ff1-5365-ab64-80b47b0176d7")}catch{}})();import*as nodeModule from"node:module";const PM_RECOVERY_REFERENCE_KINDS=["suggested_retry","candidate_command","example","next_step","migration_hint","restore_with"],RECOVERY_REFERENCE_FIELD_CONTRACTS={suggested_retry:{kind:"suggested_retry",semantics:"recovery"},retry_command:{kind:"suggested_retry",semantics:"recovery"},candidate_command:{kind:"candidate_command",semantics:"recovery"},candidate_commands:{kind:"candidate_command",semantics:"recovery"},fallback_candidates:{kind:"candidate_command",semantics:"recovery",nested_value_field:"command"},next_best_command:{kind:"candidate_command",semantics:"recovery"},example:{kind:"example",semantics:"recovery"},examples:{kind:"example",semantics:"recovery"},next_step:{kind:"next_step",semantics:"recovery"},next_steps:{kind:"next_step",semantics:"recovery"},suggested_next_steps:{kind:"next_step",semantics:"recovery"},migration_hint:{kind:"migration_hint",semantics:"replacement"},migration_hints:{kind:"migration_hint",semantics:"replacement"},restore_with:{kind:"restore_with",semantics:"behavior_preserving"}},PM_RECOVERY_REFERENCE_FIELDS=Object.freeze(Object.keys(RECOVERY_REFERENCE_FIELD_CONTRACTS));function recoveryReferenceContract(field){if(Object.hasOwn(RECOVERY_REFERENCE_FIELD_CONTRACTS,field))return RECOVERY_REFERENCE_FIELD_CONTRACTS[field]}const SOURCE_REGEXP_PREFIX_PUNCTUATORS=new Set([..."=([{,:;!?&|+-*%^~<>","=>"]);function compareCodeUnits(left,right){return left<right?-1:left>right?1:0}function skipQuotedSourceToken(source,index){const quote=source[index];let next=index+1,value="";for(;next<source.length&&source[next]!==quote;)source[next]==="\\"?next+=2:(value+=source[next],next+=1);return source[next]===quote&&(next+=1),{next,value}}function canStartRegularExpression(previous){return previous===void 0||previous.kind==="punctuator"&&SOURCE_REGEXP_PREFIX_PUNCTUATORS.has(previous.value)||previous.kind==="identifier"&&["return","case","throw","else","yield"].includes(previous.value)}function sourceTriviaEnd(source,index){if(/\s/u.test(source[index]))return index+1;if(source.startsWith("//",index)){const newline=source.indexOf(`
2
- `,index+2);return newline===-1?source.length:newline+1}if(source.startsWith("/*",index))return source.indexOf("*/",index+2)+2}function regularExpressionEnd(source,index,previous){if(source[index]!=="/"||!canStartRegularExpression(previous))return;let next=index+1,inClass=!1;for(;next<source.length;)if(source[next]==="\\")next+=2;else if(source[next]==="[")inClass=!0,next+=1;else if(source[next]==="]")inClass=!1,next+=1;else if(source[next]==="/"&&!inClass){for(next+=1;/[A-Za-z]/u.test(source.charAt(next));)next+=1;return next}else next+=1;return next}function readSourceSyntaxToken(source,index){const character=source[index];if(character==="'"||character==='"'||character==="`"){const quoted=skipQuotedSourceToken(source,index);return character==="`"?{next:quoted.next}:{next:quoted.next,token:{kind:"string",value:quoted.value,offset:index+1}}}if(/[A-Za-z_$]/u.test(character)){let next=index+1;for(;/[A-Za-z0-9_$]/u.test(source[next]??"");)next+=1;return{next,token:{kind:"identifier",value:source.slice(index,next),offset:index}}}const punctuator=source.startsWith("=>",index)?"=>":character;return{next:index+punctuator.length,token:{kind:"punctuator",value:punctuator,offset:index}}}function tokenizeExecutableSource(source){const tokens=[];let index=0;for(;index<source.length;){const ignoredEnd=sourceTriviaEnd(source,index);if(ignoredEnd!==void 0){index=ignoredEnd;continue}const regexEnd=regularExpressionEnd(source,index,tokens.at(-1));if(regexEnd!==void 0){index=regexEnd;continue}const read=readSourceSyntaxToken(source,index);read.token&&tokens.push(read.token),index=read.next}return tokens}const SOURCE_BRACE_FRAME_KINDS=new Set(["object","block","pattern"]),SOURCE_PATTERN_DECLARATIONS=new Set(["const","let","var"]),SOURCE_CLOSING_TOKENS=new Set(["}",")","]"]),SOURCE_OBJECT_PRECEDERS=new Set(["=","(","[",",",":","?","return"]);function objectFrameKind(tokens,index,stack){if([...stack].reverse().find(frame=>SOURCE_BRACE_FRAME_KINDS.has(frame.kind))?.kind==="pattern"||stack.at(-1)?.kind==="paren"&&stack.at(-1)?.parameter_list)return"pattern";const previous=tokens[index-1];return previous?.kind==="identifier"&&SOURCE_PATTERN_DECLARATIONS.has(previous.value)?"pattern":previous?.value==="=>"||previous?.value===")"?"block":previous&&SOURCE_OBJECT_PRECEDERS.has(previous.value)?"object":"block"}function openingSourceFrame(tokens,index,stack){const token=tokens[index];if(token.value==="{"){const kind=objectFrameKind(tokens,index,stack);return{kind,...kind==="object"?{member_start:!0,candidates:[]}:{}}}if(token.value==="[")return{kind:"array"};if(token.value!=="(")return;const previous=tokens[index-1],beforePrevious=tokens[index-2];return{kind:"paren",...previous?.value==="function"||beforePrevious?.value==="function"?{parameter_list:!0}:{}}}function staticObjectMember(frame,token,next){if(!(frame?.kind!=="object"||!frame.member_start||token.kind!=="identifier"&&token.kind!=="string"||next?.value!==":"||!/^[A-Za-z][A-Za-z0-9_]*$/u.test(token.value)))return{field:token.value,offset:token.offset}}function isPatternLikeObjectClosure(tokens,index){return tokens[index+1]?.value===")"&&tokens[index+2]?.value==="=>"||tokens[index+1]?.value==="="}function scanSourcePropertyTokens(source){const tokens=tokenizeExecutableSource(nodeModule.stripTypeScriptTypes(source,{mode:"strip"})),properties=[],stack=[];for(const[index,token]of tokens.entries()){const frame=stack.at(-1),property=staticObjectMember(frame,token,tokens[index+1]);property&&frame.candidates.push(property);const opening=openingSourceFrame(tokens,index,stack);if(opening)stack.push(opening);else if(SOURCE_CLOSING_TOKENS.has(token.value)){const closed=stack.pop();closed?.kind==="object"&&!isPatternLikeObjectClosure(tokens,index)&&properties.push(...closed.candidates)}else token.value===","&&frame?.kind==="object"?frame.member_start=!0:frame?.kind==="object"&&token.value!==":"&&(frame.member_start=!1)}return properties}function sourceLineStarts(source){const starts=[0];for(let index=0;index<source.length;index+=1)source[index]===`
3
- `&&starts.push(index+1);return starts}function sourceLineAtOffset(starts,offset){let low=0,high=starts.length;for(;low<high;){const middle=Math.floor((low+high)/2);starts[middle]<=offset?low=middle+1:high=middle}return low}function censusPmRecoveryReferenceProducers(sources){const producers=[],findings=[];for(const source of[...sources].sort((left,right)=>compareCodeUnits(left.path,right.path))){const lineStarts=sourceLineStarts(source.content);let properties;try{properties=scanSourcePropertyTokens(source.content)}catch(error){findings.push({kind:"invalid_source",subject:source.path,detail:`${source.path} could not be parsed for recovery producers: ${String(error)}.`});continue}for(const property of properties){const field=property.field,line=sourceLineAtOffset(lineStarts,property.offset),contract=recoveryReferenceContract(field);contract?producers.push({path:source.path,line,field,kind:contract.kind}):/(?:retry_command|candidate_command|fallback_candidate|next_best_command|example|next_step|migration_hint|restore_with)/u.test(field)&&!/(?:_total|_truncated)$/u.test(field)&&findings.push({kind:"unknown_recovery_field",subject:`${source.path}:${line}:${field}`,detail:`${field} resembles a recovery reference but has no typed field contract.`})}}const producerCountByKind=Object.fromEntries(PM_RECOVERY_REFERENCE_KINDS.map(kind=>[kind,producers.filter(producer=>producer.kind===kind).length]));for(const kind of PM_RECOVERY_REFERENCE_KINDS)producerCountByKind[kind]===0&&findings.push({kind:"missing_kind_producer",subject:kind,detail:`No source producer emits the ${kind} recovery-reference kind.`});return producers.sort((left,right)=>left.path!==right.path?compareCodeUnits(left.path,right.path):left.line!==right.line?left.line-right.line:compareCodeUnits(left.field,right.field)),findings.sort((left,right)=>left.subject!==right.subject?compareCodeUnits(left.subject,right.subject):compareCodeUnits(left.kind,right.kind)),{ok:findings.length===0,scanned_file_count:sources.length,producer_count:producers.length,producer_count_by_kind:producerCountByKind,producers,findings}}function derivePmRecoveryReferenceObligations(probeId,envelope){const obligations=[],visit=(value,path)=>{if(Array.isArray(value)){value.forEach((entry,index)=>visit(entry,[...path,String(index)]));return}if(!(typeof value!="object"||value===null))for(const[key,entry]of Object.entries(value).sort(([left],[right])=>compareCodeUnits(left,right))){const baseContract=recoveryReferenceContract(key),contract=baseContract?.kind==="migration_hint"&&value.semantics==="behavior_preserving"?{...baseContract,semantics:"behavior_preserving"}:baseContract,entries=[entry].flat();contract!==void 0&&entries.forEach((candidate,index)=>{const nestedValueField="nested_value_field"in contract&&typeof contract.nested_value_field=="string"?contract.nested_value_field:void 0,resolvedCandidate=nestedValueField&&typeof candidate=="object"&&candidate!==null&&!Array.isArray(candidate)?candidate[nestedValueField]:candidate;if(typeof resolvedCandidate!="string"||resolvedCandidate.trim().length===0)return;const coordinate=[...path,key,String(index)].map(segment=>encodeURIComponent(segment)).join("/");obligations.push({id:`${probeId}:${contract.kind}:${coordinate}`,probe_id:probeId,kind:contract.kind,semantics:contract.semantics,value:resolvedCandidate})}),visit(entry,[...path,key])}};return visit(envelope,[]),obligations}function verifyPmRefusalReachability(catalog,observations){const declarations=catalog.flatMap(contract=>(contract.owned_states??[]).map(state=>({contract,state}))),findings=[],observationsByProbe=new Map;for(const observation of observations){if(observationsByProbe.has(observation.probe_id)){findings.push({kind:"duplicate_probe",probe_id:observation.probe_id,detail:`Observation ${observation.probe_id} was supplied more than once.`});continue}observationsByProbe.set(observation.probe_id,observation)}const declaredProbeIds=new Set(declarations.map(({state})=>state.probe_id));for(const{contract,state}of declarations){const observation=observationsByProbe.get(state.probe_id);if(!observation){findings.push({kind:"missing_probe",probe_id:state.probe_id,detail:`No entrypoint observation was recorded for ${contract.code}.`});continue}observation.code!==contract.code&&findings.push({kind:"wrong_error_code",probe_id:state.probe_id,detail:`Expected ${contract.code}; observed ${observation.code}.`}),observation.exit_class!==state.expected_exit_class&&findings.push({kind:"wrong_exit_class",probe_id:state.probe_id,detail:`Expected ${state.expected_exit_class}; observed ${observation.exit_class}.`}),state.entrypoints.includes(observation.entrypoint)||findings.push({kind:"wrong_entrypoint",probe_id:state.probe_id,detail:`Expected one of ${state.entrypoints.join(", ")}; observed ${observation.entrypoint}.`})}for(const observation of observations)declaredProbeIds.has(observation.probe_id)||findings.push({kind:"undeclared_probe",probe_id:observation.probe_id,detail:`Observation ${observation.probe_id} has no catalog declaration.`});return findings.sort((left,right)=>left.probe_id!==right.probe_id?left.probe_id.localeCompare(right.probe_id):left.kind.localeCompare(right.kind)),{ok:findings.length===0,declared_probe_count:declarations.length,observed_probe_count:observations.length,findings}}function verifyPmRecoveryReferences(obligations,observations){const findings=[],declaredIds=new Set,duplicateIds=new Set;for(const obligation of obligations){if(declaredIds.has(obligation.id)){duplicateIds.add(obligation.id),findings.push({kind:"duplicate_obligation",reference_id:obligation.id,detail:`Recovery obligation ${obligation.id} was declared more than once.`});continue}declaredIds.add(obligation.id)}const observationsById=new Map;for(const observation of observations){if(observationsById.has(observation.id)){findings.push({kind:"duplicate_observation",reference_id:observation.id,detail:`Recovery reference ${observation.id} was observed more than once.`});continue}observationsById.set(observation.id,observation),declaredIds.has(observation.id)||findings.push({kind:"undeclared_observation",reference_id:observation.id,detail:`Recovery observation ${observation.id} has no emitted obligation.`})}for(const obligation of obligations){if(duplicateIds.has(obligation.id))continue;const observation=observationsById.get(obligation.id);observation?observation.reachable?observation.semantics!==obligation.semantics&&findings.push({kind:"wrong_semantics",reference_id:obligation.id,detail:`Recovery reference ${obligation.value} promised ${obligation.semantics}; proof demonstrated ${observation.semantics}.`}):findings.push({kind:"unreachable_reference",reference_id:obligation.id,detail:`Recovery reference ${obligation.value} did not reach its promised target.`}):findings.push({kind:"missing_observation",reference_id:obligation.id,detail:`No reachability proof was recorded for ${obligation.kind} ${obligation.value}.`})}const coverageByKind=PM_RECOVERY_REFERENCE_KINDS.map(kind=>{const kindObligations=obligations.filter(obligation=>obligation.kind===kind),kindObservations=kindObligations.filter(obligation=>!duplicateIds.has(obligation.id)).map(obligation=>observationsById.get(obligation.id)).filter(observation=>observation!==void 0);return{kind,declared:kindObligations.length,observed:kindObservations.length,passed:kindObligations.filter(obligation=>{const observation=observationsById.get(obligation.id);return!duplicateIds.has(obligation.id)&&observation?.reachable===!0&&observation.semantics===obligation.semantics}).length}});findings.sort((left,right)=>left.reference_id!==right.reference_id?left.reference_id.localeCompare(right.reference_id):left.kind.localeCompare(right.kind));const passed=coverageByKind.reduce((total,coverage)=>total+coverage.passed,0);return{ok:findings.length===0,declared_reference_count:obligations.length,observed_reference_count:observations.length,pass_fraction:declaredIds.size===0?1:passed/declaredIds.size,coverage_by_kind:coverageByKind,findings}}function verifyPmRecoveryProducerRuntimeCoverage(census,obligations){const runtimeValuesByKind=new Map(PM_RECOVERY_REFERENCE_KINDS.map(kind=>[kind,new Set]));for(const obligation of obligations)runtimeValuesByKind.get(obligation.kind).add(obligation.value);const coverageByKind=PM_RECOVERY_REFERENCE_KINDS.map(kind=>({kind,source_producers:census.producer_count_by_kind[kind],runtime_values:runtimeValuesByKind.get(kind).size})),missingRuntimeKinds=coverageByKind.filter(({source_producers:sourceProducers,runtime_values:runtimeValues})=>sourceProducers>0&&runtimeValues===0).map(({kind})=>kind);return{ok:census.ok&&missingRuntimeKinds.length===0,source_producer_count:census.producer_count,runtime_value_count:coverageByKind.reduce((total,{runtime_values:runtimeValues})=>total+runtimeValues,0),coverage_by_kind:coverageByKind,missing_runtime_kinds:missingRuntimeKinds}}const verifyPmRecoveryKindRuntimeCoverage=verifyPmRecoveryProducerRuntimeCoverage;export{PM_RECOVERY_REFERENCE_FIELDS,PM_RECOVERY_REFERENCE_KINDS,censusPmRecoveryReferenceProducers,derivePmRecoveryReferenceObligations,verifyPmRecoveryKindRuntimeCoverage,verifyPmRecoveryProducerRuntimeCoverage,verifyPmRecoveryReferences,verifyPmRefusalReachability};
4
- //# sourceMappingURL=refusal-reachability.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="f5567aa1-0268-574d-907b-38d6249538ce")}catch{}})();import{isPmSuccessfulExitCode,resolvePmCommandExitContract}from"../cli-contracts/command-exit-contracts.js";import{findBootstrapCommandTokenIndex,parseBootstrapCommandName}from"../cli-contracts/bootstrap-command-scanner.js";import{resolvePmHistoryOperation}from"../cli-contracts/command-aliases.js";import{PM_OUTPUT_ENVELOPE_KINDS,resolvePmCommandOutputEnvelope}from"../output-contracts.js";const PM_AGENT_TASK_TRANSCRIPT_VERSION=2,PM_AGENT_TASK_ACCOUNTING_MODES=["self_reported","independent_transport"];function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function readTranscriptString(value,field){if(typeof value!="string"||value.trim().length===0)throw new TypeError(`${field} must be a non-empty string`);return value.trim()}function readTranscriptStringArray(value,field,preserveWhitespace=!1){if(!Array.isArray(value)||value.length===0)throw new TypeError(`${field} must be a non-empty string array`);return value.map((entry,index)=>{const normalized=readTranscriptString(entry,`${field}[${String(index)}]`);return preserveWhitespace?entry:normalized})}function readOptionalTranscriptString(value,field){return value===void 0?void 0:readTranscriptString(value,field)}function readExpectedFieldValues(value,field){if(value===void 0)return;if(!isRecord(value)||Object.keys(value).length===0)throw new TypeError(`${field} must be a non-empty object`);const entries=Object.entries(value).map(([path,expectedValue])=>{if(path.length===0||path.split(".").some(segment=>segment.length===0))throw new TypeError(`${field} must use dot-separated own-property paths`);if(expectedValue!==null&&typeof expectedValue!="string"&&typeof expectedValue!="boolean"&&(typeof expectedValue!="number"||!Number.isFinite(expectedValue)))throw new TypeError(`${field} values must be JSON primitives`);return[path,expectedValue]});return Object.fromEntries(entries)}function assertTranscriptStepOutputContract(field,args,exitCode,outputKind,errorCode,refusalSurface){if(outputKind==="refusal"){if(isPmSuccessfulExitCode(exitCode)||errorCode===void 0||refusalSurface===void 0)throw new TypeError(`${field} refusal steps require a non-success exit, error code, and refusal surface`);return}if(errorCode!==void 0||refusalSurface!==void 0)throw new TypeError(`${field} only refusal steps may declare expected_error_code or expected_refusal_surface`);const commandIndex=findBootstrapCommandTokenIndex(args);if(commandIndex===void 0)throw new TypeError(`${field}.args must identify a command after global flags`);let command=args[commandIndex].trim().toLowerCase();if(command==="history"){const operation=parseBootstrapCommandName(args.slice(commandIndex+1));operation!==void 0&&(command=resolvePmHistoryOperation(`history ${operation}`))}const exitContract=resolvePmCommandExitContract(command);if(!isPmSuccessfulExitCode(exitCode)||exitCode!==0&&!exitContract?.exit_codes.some(declaredExitCode=>declaredExitCode===exitCode))throw new TypeError(`${field} successful output must use exit code 0 or a command-declared successful effect exit`);const declaredKind=resolvePmCommandOutputEnvelope(command).kind;if(outputKind!==declaredKind)throw new TypeError(`${field} expected ${outputKind}, but ${command} declares ${declaredKind}`)}function parseAgentTaskTranscriptStep(value,taskId,index){if(!isRecord(value))throw new TypeError(`tasks.${taskId}.steps[${String(index)}] must be an object`);const field=`tasks.${taskId}.steps[${String(index)}]`,id=readTranscriptString(value.id,`${field}.id`),args=readTranscriptStringArray(value.args,`${field}.args`,!0),expectedExitCode=value.expected_exit_code;if(typeof expectedExitCode!="number"||!Number.isSafeInteger(expectedExitCode))throw new TypeError(`${field}.expected_exit_code must be a safe integer`);const rawOutputKind=value.expected_output_kind;if(rawOutputKind!=="refusal"&&!PM_OUTPUT_ENVELOPE_KINDS.includes(rawOutputKind))throw new TypeError(`${field}.expected_output_kind is unsupported`);const expectedOutputKind=rawOutputKind,rawAccountingMode=value.expected_accounting_mode;if(!PM_AGENT_TASK_ACCOUNTING_MODES.includes(rawAccountingMode))throw new TypeError(`${field}.expected_accounting_mode is unsupported`);const expectedAccountingMode=rawAccountingMode;if(expectedAccountingMode==="independent_transport"&&expectedOutputKind!=="refusal")throw new TypeError(`${field} independent_transport accounting is supported only for refusal steps`);const requiredFields=readTranscriptStringArray(value.required_fields,`${field}.required_fields`);if(requiredFields.some(requiredField=>requiredField.split(".").some(segment=>segment.length===0)))throw new TypeError(`${field}.required_fields must contain dot-separated own-property paths`);const expectedFieldValues=readExpectedFieldValues(value.expected_field_values,`${field}.expected_field_values`),expectedErrorCode=readOptionalTranscriptString(value.expected_error_code,`${field}.expected_error_code`),expectedRefusalSurface=readOptionalTranscriptString(value.expected_refusal_surface,`${field}.expected_refusal_surface`),recoveryFor=readOptionalTranscriptString(value.recovery_for,`${field}.recovery_for`);return assertTranscriptStepOutputContract(field,args,expectedExitCode,expectedOutputKind,expectedErrorCode,expectedRefusalSurface),{id,args,expected_exit_code:expectedExitCode,expected_output_kind:expectedOutputKind,expected_accounting_mode:expectedAccountingMode,required_fields:requiredFields,...expectedFieldValues?{expected_field_values:expectedFieldValues}:{},...expectedErrorCode?{expected_error_code:expectedErrorCode}:{},...expectedRefusalSurface?{expected_refusal_surface:expectedRefusalSurface}:{},...recoveryFor?{recovery_for:recoveryFor}:{}}}function parseAgentTaskTranscript(value,index){if(!isRecord(value))throw new TypeError(`tasks[${String(index)}] must be an object`);const id=readTranscriptString(value.id,`tasks[${String(index)}].id`),description=readTranscriptString(value.description,`tasks.${id}.description`);if(!Array.isArray(value.steps)||value.steps.length===0)throw new TypeError(`tasks.${id}.steps must be a non-empty array`);const steps=value.steps.map((step,stepIndex)=>parseAgentTaskTranscriptStep(step,id,stepIndex)),priorSteps=new Map;for(const step of steps){if(priorSteps.has(step.id))throw new TypeError(`tasks.${id} contains duplicate step id ${step.id}`);if(step.recovery_for!==void 0&&(priorSteps.get(step.recovery_for)?.expected_output_kind!=="refusal"||step.expected_output_kind==="refusal"))throw new TypeError(`tasks.${id}.${step.id} recovery_for must reference an earlier refusal and declare successful output`);priorSteps.set(step.id,step)}if(steps.at(-1)?.expected_output_kind==="refusal")throw new TypeError(`tasks.${id} completed task must terminate with successful output`);for(const step of steps)if(step.expected_output_kind==="refusal"&&!steps.some(candidate=>candidate.recovery_for===step.id))throw new TypeError(`tasks.${id}.${step.id} refusal must have a later successful recovery_for step`);return{id,description,steps}}function parsePmAgentTaskTranscriptCorpus(value){if(!isRecord(value))throw new TypeError("agent-task transcript corpus must be an object");if(value.version!==PM_AGENT_TASK_TRANSCRIPT_VERSION)throw new TypeError(`agent-task transcript corpus version must be ${String(PM_AGENT_TASK_TRANSCRIPT_VERSION)}`);if(!Array.isArray(value.tasks)||value.tasks.length===0)throw new TypeError("agent-task transcript corpus tasks must be non-empty");const tasks=value.tasks.map((task,index)=>parseAgentTaskTranscript(task,index)),taskIds=new Set;for(const task of tasks){if(taskIds.has(task.id))throw new TypeError(`duplicate agent-task transcript id ${task.id}`);taskIds.add(task.id)}return{version:PM_AGENT_TASK_TRANSCRIPT_VERSION,tasks}}export{PM_AGENT_TASK_ACCOUNTING_MODES,PM_AGENT_TASK_TRANSCRIPT_VERSION,parsePmAgentTaskTranscriptCorpus};
2
- //# sourceMappingURL=task-transcript-contracts.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d3795bc4-fbe5-5ca4-bc90-b72a2d469dc7")}catch{}})();const TRACKER_PREFLIGHT_RECOVERY_CONTRACTS=[{probe_id:"tracker-root-missing",failure_kind:"missing_root",expected_error_code:"tracker_root_missing",expected_exit_code:3,recovery_kind:"initialize"},{probe_id:"tracker-root-settings-missing",failure_kind:"settings_missing",expected_error_code:"tracker_not_initialized",expected_exit_code:3,recovery_kind:"initialize"},{probe_id:"tracker-root-not-directory",failure_kind:"not_directory",expected_error_code:"tracker_root_not_directory",expected_exit_code:2,recovery_kind:"select_directory"},{probe_id:"tracker-root-unreadable",failure_kind:"unreadable_root",expected_error_code:"tracker_root_unreadable",expected_exit_code:1,recovery_kind:"repair_permissions"}];function listTrackerPreflightRecoveryContracts(){return TRACKER_PREFLIGHT_RECOVERY_CONTRACTS.map(contract=>({...contract}))}function findTrackerPreflightObservationFindings(contract,observation){const findings=[];observation.error_code!==contract.expected_error_code&&findings.push({code:"error_code_mismatch",probe_id:contract.probe_id,detail:`Expected ${contract.expected_error_code}, received ${observation.error_code}.`}),observation.exit_code!==contract.expected_exit_code&&findings.push({code:"exit_code_mismatch",probe_id:contract.probe_id,detail:`Expected exit ${contract.expected_exit_code}, received ${observation.exit_code}.`}),observation.recovery_kind!==contract.recovery_kind&&findings.push({code:"recovery_kind_mismatch",probe_id:contract.probe_id,detail:`Expected ${contract.recovery_kind}, received ${observation.recovery_kind}.`});const initIndex=observation.suggested_retry_args.indexOf("init"),validInitCommand=initIndex===0||initIndex===2&&observation.suggested_retry_args[0]==="--pm-path"&&observation.suggested_retry_args[1]?.length>0;return contract.recovery_kind==="initialize"&&!validInitCommand&&findings.push({code:"missing_init_recovery",probe_id:contract.probe_id,detail:"Missing and uninitialized roots must emit a tokenized init retry."}),(observation.unsafe_init_recommended||contract.recovery_kind!=="initialize"&&observation.suggested_retry_args.includes("init"))&&findings.push({code:"unsafe_init_recovery",probe_id:contract.probe_id,detail:"A tracker root that cannot be initialized safely must not recommend initialization."}),observation.retry_succeeded||findings.push({code:"retry_failed",probe_id:contract.probe_id,detail:"The emitted retry or safe alternate-root recovery did not execute successfully."}),findings}function scoreTrackerPreflightRecoveryClosure(observations){const observationsByProbe=new Map(observations.map(observation=>[observation.probe_id,observation])),findings=[];let closedProbeCount=0;for(const contract of TRACKER_PREFLIGHT_RECOVERY_CONTRACTS){const observation=observationsByProbe.get(contract.probe_id);if(observation===void 0){findings.push({code:"missing_probe",probe_id:contract.probe_id,detail:"No runtime observation was supplied for this contract."});continue}const observationFindings=findTrackerPreflightObservationFindings(contract,observation);findings.push(...observationFindings),observationFindings.length===0&&(closedProbeCount+=1)}return findings.sort((left,right)=>left.probe_id.localeCompare(right.probe_id)||left.code.localeCompare(right.code)),{ok:findings.length===0,probe_count:TRACKER_PREFLIGHT_RECOVERY_CONTRACTS.length,closed_probe_count:closedProbeCount,findings}}export{listTrackerPreflightRecoveryContracts,scoreTrackerPreflightRecoveryClosure};
2
- //# sourceMappingURL=tracker-preflight-contracts.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ce91f520-088c-5a77-9194-78a36c965ff6")}catch{}})();export*from"./compose.js";export*from"./define.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{EXTENSION_CAPABILITY_REGISTRATION_SURFACES,collectUsedExtensionCapabilities,reconcileExtensionCapabilityUsage}from"../core/extensions/capability-usage.js";import{renderExtensionSurfaceMarkdown}from"../core/extensions/activation-summary-markdown.js";import{createExtensionContributionInventory,normalizeExtensionContributionInventory}from"../core/extensions/contribution-inventory.js";import{normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey}from"./extension/command-options.js";export{BUILTIN_PROFILES,EXTENSION_CAPABILITY_REGISTRATION_SURFACES,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,RESERVED_ITEM_FIELD_NAMES,collectPackageExtensionDirectories,collectUsedExtensionCapabilities,createExtensionContributionInventory,describeProfileComposition,describeProjectProfile,lintProjectProfile,listProfiles,normalizeDirectExtensionCommandOptions,normalizeExtensionContributionInventory,normalizeProfileName,planProfileApplication,readPmPackageManifest,reconcileExtensionCapabilityUsage,renderExtensionSurfaceMarkdown,resolveExtensionFlagOptionKey,resolveProfile};
2
- //# sourceMappingURL=authoring.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="52f6eff3-e226-56d9-893a-f16997d11c50")}catch{}})();import{normalizeKnownExtensionCapability,resolveLegacyExtensionCapabilityAlias}from"../core/extensions/extension-capability-aliases.js";import{normalizeCommandName}from"../core/extensions/extension-runtime-helpers.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{describeExtensionLongFlagFailure,findExtensionFlagTokenFailure}from"../core/extensions/flag-definition-validation.js";import{evaluatePmMaxVersionBound,evaluatePmMinVersionBound}from"../core/extensions/version-compat.js";import{inspectExtensionManifestSchema,lintExtensionManifestSchema}from"../core/extensions/manifest-schema.js";function defineExtension(module){return module}function defineExtensionBlueprint(blueprint){return blueprint}function registerBlueprintCommandSurfaces(api,blueprint){for(const command of blueprint.commands??[])api.registerCommand(command);for(const[command,override]of Object.entries(blueprint.commandOverrides??{}))api.registerCommand(command,override);for(const[targetCommand,flags]of Object.entries(blueprint.flags??{}))api.registerFlags(targetCommand,flags);for(const[command,override]of Object.entries(blueprint.parsers??{}))api.registerParser(command,override);for(const[format,renderer]of Object.entries(blueprint.renderers??{}))if(typeof renderer=="function")api.registerRenderer(format,renderer);else{const{run,...ownership}=renderer;api.registerRenderer(format,run,ownership)}for(const[service,override]of Object.entries(blueprint.services??{}))api.registerService(service,override)}function registerBlueprintSchemaSurfaces(api,blueprint){for(const override of blueprint.preflights??[])api.registerPreflight(override);const itemTypes=blueprint.itemTypes??[];itemTypes.length>0&&api.registerItemTypes(itemTypes);const itemFields=blueprint.itemFields??[];itemFields.length>0&&api.registerItemFields(itemFields);const relationshipKinds=blueprint.relationshipKinds??[];relationshipKinds.length>0&&api.registerRelationshipKinds(relationshipKinds);for(const migration of blueprint.migrations??[])api.registerMigration(migration);for(const profile of blueprint.profiles??[])api.registerProfile(profile)}function registerBlueprintRetrievalSurfaces(api,blueprint){for(const provider of blueprint.searchProviders??[])api.registerSearchProvider(provider);for(const adapter of blueprint.vectorStoreAdapters??[])api.registerVectorStoreAdapter(adapter);for(const provider of blueprint.assuranceProviders??[])api.registerAssuranceMeasurementProvider(provider);for(const entry of blueprint.importers??[])api.registerImporter(entry.name,entry.importer,entry.options);for(const entry of blueprint.exporters??[])api.registerExporter(entry.name,entry.exporter,entry.options)}function registerBlueprintHooks(api,hooks){for(const hook of hooks.beforeCommand??[])api.hooks.beforeCommand(hook);for(const hook of hooks.beforeMutation??[])api.hooks.beforeMutation(hook);for(const hook of hooks.afterCommand??[])api.hooks.afterCommand(hook);for(const hook of hooks.onWrite??[])api.hooks.onWrite(hook);for(const hook of hooks.onRead??[])api.hooks.onRead(hook);for(const hook of hooks.onIndex??[])api.hooks.onIndex(hook)}function composeExtension(blueprint){const module={activate:async api=>{registerBlueprintCommandSurfaces(api,blueprint),registerBlueprintSchemaSurfaces(api,blueprint),registerBlueprintRetrievalSurfaces(api,blueprint),registerBlueprintHooks(api,blueprint.hooks??{}),await blueprint.activate?.(api)}};return blueprint.manifest&&(module.manifest=blueprint.manifest),blueprint.deactivate&&(module.deactivate=blueprint.deactivate),module}function mergeArraySurface(surfaces){const merged=surfaces.flatMap(surface=>surface??[]);return merged.length>0?merged:void 0}function mergeHandlerRecord(surfaces){const merged=Object.assign({},...surfaces.map(surface=>surface??{}));return Object.keys(merged).length>0?merged:void 0}function mergeFlagRecord(surfaces){const merged={};for(const surface of surfaces)for(const[command,flags]of Object.entries(surface??{}))merged[command]=[...merged[command]??[],...flags];return Object.keys(merged).length>0?merged:void 0}const EXTENSION_BLUEPRINT_HOOK_KEYS=["beforeCommand","beforeMutation","afterCommand","onWrite","onRead","onIndex"],EXTENSION_BLUEPRINT_HOOK_KEY_COVERAGE={};function assignMergedHookSurface(merged,surfaces,key){const hookArrays=surfaces.map(hooks=>hooks?.[key]),value=mergeArraySurface(hookArrays);if(value!==void 0){const typedMerged=merged;typedMerged[key]=value}}function mergeHookSurfaces(surfaces){const merged={};for(const key of EXTENSION_BLUEPRINT_HOOK_KEYS)assignMergedHookSurface(merged,surfaces,key);return Object.keys(merged).length>0?merged:void 0}function mergeExtensionBlueprints(...blueprints){const merged={},assign=(key,value)=>{value!==void 0&&(merged[key]=value)};assign("commands",mergeArraySurface(blueprints.map(blueprint=>blueprint.commands))),assign("commandOverrides",mergeHandlerRecord(blueprints.map(blueprint=>blueprint.commandOverrides))),assign("flags",mergeFlagRecord(blueprints.map(blueprint=>blueprint.flags))),assign("parsers",mergeHandlerRecord(blueprints.map(blueprint=>blueprint.parsers))),assign("renderers",mergeHandlerRecord(blueprints.map(blueprint=>blueprint.renderers))),assign("services",mergeHandlerRecord(blueprints.map(blueprint=>blueprint.services))),assign("preflights",mergeArraySurface(blueprints.map(blueprint=>blueprint.preflights))),assign("itemTypes",mergeArraySurface(blueprints.map(blueprint=>blueprint.itemTypes))),assign("itemFields",mergeArraySurface(blueprints.map(blueprint=>blueprint.itemFields))),assign("relationshipKinds",mergeArraySurface(blueprints.map(blueprint=>blueprint.relationshipKinds))),assign("migrations",mergeArraySurface(blueprints.map(blueprint=>blueprint.migrations))),assign("profiles",mergeArraySurface(blueprints.map(blueprint=>blueprint.profiles))),assign("searchProviders",mergeArraySurface(blueprints.map(blueprint=>blueprint.searchProviders))),assign("vectorStoreAdapters",mergeArraySurface(blueprints.map(blueprint=>blueprint.vectorStoreAdapters))),assign("assuranceProviders",mergeArraySurface(blueprints.map(blueprint=>blueprint.assuranceProviders))),assign("importers",mergeArraySurface(blueprints.map(blueprint=>blueprint.importers))),assign("exporters",mergeArraySurface(blueprints.map(blueprint=>blueprint.exporters))),assign("hooks",mergeHookSurfaces(blueprints.map(blueprint=>blueprint.hooks)));let manifest;for(const blueprint of blueprints)blueprint.manifest&&(manifest=blueprint.manifest);assign("manifest",manifest);const hasActivates=blueprints.some(blueprint=>blueprint.activate);assign("activate",hasActivates?async api=>{for(const blueprint of blueprints)blueprint.activate&&await blueprint.activate(api)}:void 0);const hasDeactivates=blueprints.some(blueprint=>blueprint.deactivate);return assign("deactivate",hasDeactivates?async()=>{const errors=[];for(const blueprint of[...blueprints].reverse())if(blueprint.deactivate)try{await blueprint.deactivate()}catch(error){errors.push(error)}if(errors.length>0)throw errors.length>1?new AggregateError(errors,"Multiple extension blueprint deactivate hooks failed."):errors[0]}:void 0),merged}const BLUEPRINT_FIELD_CAPABILITIES=[["commands","commands"],["commandOverrides","commands"],["flags","schema"],["itemTypes","schema"],["itemFields","schema"],["relationshipKinds","schema"],["migrations","schema"],["profiles","schema"],["parsers","parser"],["renderers","renderers"],["services","services"],["preflights","preflight"],["searchProviders","search"],["vectorStoreAdapters","search"],["assuranceProviders","services"],["importers","importers"],["exporters","importers"]];function hasEntries(value){return value?Array.isArray(value)?value.length>0:Object.keys(value).length>0:!1}function deriveExtensionCapabilities(blueprint){const capabilities=new Set;for(const[field,capability]of BLUEPRINT_FIELD_CAPABILITIES)hasEntries(blueprint[field])&&capabilities.add(capability);(blueprint.commands??[]).filter(isPresent).some(command=>command.flags!==void 0)&&capabilities.add("schema");const importExportEntries=[...blueprint.importers??[],...blueprint.exporters??[]].filter(isPresent);importExportEntries.some(entry=>entry?.options?.flags!==void 0)&&capabilities.add("schema"),importExportEntries.some(entry=>typeof entry=="object")&&capabilities.add("commands");const hooks=blueprint.hooks??{};return[hooks.beforeCommand,hooks.beforeMutation,hooks.afterCommand,hooks.onWrite,hooks.onRead,hooks.onIndex].some(hasEntries)&&capabilities.add("hooks"),[...capabilities].sort((left,right)=>left.localeCompare(right))}const BLUEPRINT_HOOK_FIELD_TO_KIND=[["beforeCommand","before_command"],["beforeMutation","before_mutation"],["afterCommand","after_command"],["onWrite","on_write"],["onRead","on_read"],["onIndex","on_index"]];function sortUnique(values){return[...new Set(values)].sort((left,right)=>left.localeCompare(right))}function isPresent(value){return value!=null}function importerCommandPath(entry){return normalizeCommandName(`${entry.name} import`)}function exporterCommandPath(entry){return normalizeCommandName(`${entry.name} export`)}function collectBlueprintCommandPaths(commands,importers,exporters){return[...commands.map(command=>normalizeCommandName(command.name)),...importers.filter(entry=>entry.options!==void 0).map(importerCommandPath),...exporters.filter(entry=>entry.options!==void 0).map(exporterCommandPath)]}function collectBlueprintFlagCommands(blueprint,commands,importers,exporters){return[...Object.keys(blueprint.flags??{}).map(command=>normalizeCommandName(command)),...commands.filter(command=>command.flags!==void 0).map(command=>normalizeCommandName(command.name)),...importers.filter(entry=>entry.options?.flags!==void 0).map(importerCommandPath),...exporters.filter(entry=>entry.options?.flags!==void 0).map(exporterCommandPath)]}function collectBlueprintHookKinds(hooks){return BLUEPRINT_HOOK_FIELD_TO_KIND.filter(([field])=>(hooks[field]?.length??0)>0).map(([,kind])=>kind)}function collectBlueprintRendererOwnership(renderers){const ownership=Object.entries(renderers??{}).filter(([,renderer])=>typeof renderer!="function"&&((renderer.commands?.length??0)>0||renderer.resultDiscriminator!==void 0)).map(([format,renderer])=>{const scoped=renderer;return{format,commands:sortUnique((scoped.commands??[]).map(command=>normalizeCommandName(command))),result_discriminator:scoped.resultDiscriminator!==void 0}}).sort((left,right)=>left.format.localeCompare(right.format));return ownership.length>0?{renderer_ownership:ownership}:{}}function collectBlueprintAssuranceProviders(providers){return!providers||providers.length===0?{}:{assurance_providers:sortUnique(providers.map(provider=>provider.id))}}function collectBlueprintSurfaceSummary(blueprint,importers,exporters){return{item_types:sortUnique((blueprint.itemTypes??[]).map(type=>type.name)),item_fields:sortUnique((blueprint.itemFields??[]).map(field=>field.name)),...(blueprint.relationshipKinds?.length??0)>0?{relationship_kinds:sortUnique(blueprint.relationshipKinds.map(definition=>definition.kind))}:{},migrations:sortUnique((blueprint.migrations??[]).flatMap(migration=>typeof migration.id=="string"?[migration.id]:[])),profiles:sortUnique((blueprint.profiles??[]).map(profile=>profile.name)),importers:sortUnique(importers.map(entry=>normalizeCommandName(entry.name))),exporters:sortUnique(exporters.map(entry=>normalizeCommandName(entry.name))),search_providers:sortUnique((blueprint.searchProviders??[]).map(provider=>provider.name)),vector_store_adapters:sortUnique((blueprint.vectorStoreAdapters??[]).map(adapter=>adapter.name)),...collectBlueprintAssuranceProviders(blueprint.assuranceProviders),parser_overrides:sortUnique(Object.keys(blueprint.parsers??{}).map(command=>normalizeCommandName(command))),service_overrides:sortUnique(Object.keys(blueprint.services??{}).map(service=>String(service).trim().toLowerCase())),renderer_overrides:sortUnique(Object.keys(blueprint.renderers??{}).map(format=>String(format).trim().toLowerCase())),...collectBlueprintRendererOwnership(blueprint.renderers),preflight_overrides:(blueprint.preflights??[]).length,preflight_ownership:(blueprint.preflights??[]).map(preflight=>({commands:[...preflight.commands??[]]}))}}function describeExtensionBlueprint(blueprint){const commands=(blueprint.commands??[]).filter(isPresent),importers=(blueprint.importers??[]).filter(isPresent),exporters=(blueprint.exporters??[]).filter(isPresent),importerPaths=importers.map(importerCommandPath),exporterPaths=exporters.map(exporterCommandPath),commandPaths=collectBlueprintCommandPaths(commands,importers,exporters),flagCommands=collectBlueprintFlagCommands(blueprint,commands,importers,exporters),hooks=blueprint.hooks??{},surfaces=collectBlueprintSurfaceSummary(blueprint,importers,exporters);return{capabilities:deriveExtensionCapabilities(blueprint),commands:sortUnique(commandPaths),command_overrides:sortUnique(Object.keys(blueprint.commandOverrides??{}).map(command=>normalizeCommandName(command))),command_handlers:sortUnique([...commandPaths,...importerPaths,...exporterPaths]),hooks:collectBlueprintHookKinds(hooks),flag_commands:sortUnique(flagCommands),...surfaces}}const BLUEPRINT_LINTABLE_SURFACE_FIELDS=["commands","commandOverrides","flags","parsers","renderers","services","preflights","itemTypes","itemFields","relationshipKinds","migrations","profiles","searchProviders","vectorStoreAdapters","assuranceProviders","importers","exporters"];function collectReservedItemFieldFindings(blueprint){return(blueprint.itemFields??[]).filter(field=>typeof field?.name=="string"&&RESERVED_ITEM_FIELD_NAMES.has(field.name.trim())).map(field=>({code:"reserved_item_field",severity:"error",message:`Item field "${field.name}" collides with reserved item metadata; rename it with an extension-specific prefix before publishing.`,field:field.name}))}function collectBlueprintFlagFindings(blueprint){return[...Object.values(blueprint.flags??{}).flat(),...(blueprint.commands??[]).flatMap(command=>command.flags??[]),...(blueprint.importers??[]).flatMap(entry=>entry.options?.flags??[]),...(blueprint.exporters??[]).flatMap(entry=>entry.options?.flags??[])].flatMap(definition=>{if(typeof definition?.long!="string"&&typeof definition?.short!="string")return[];const finding=findExtensionFlagTokenFailure(definition.long,definition.short);if(finding===null)return[];const{token,failure}=finding;return[{code:failure,severity:"error",message:`Flag "${token}" ${describeExtensionLongFlagFailure(token,failure)}.`,field:token}]})}function normalizeDeclaredCapabilities(capabilities){const known=new Set;for(const capability of capabilities){const normalized=resolveLegacyExtensionCapabilityAlias(capability)??normalizeKnownExtensionCapability(capability);normalized!==null&&known.add(normalized)}return[...known].sort((left,right)=>left.localeCompare(right))}function collectBlueprintCapabilityFindings(used,declared){const findings=[];if(declared===null)return used.length>0&&findings.push({code:"manifest_capabilities_absent",severity:"warning",message:`Blueprint exercises ${used.length===1?"capability":"capabilities"} [${used.join(", ")}] but declares none; set capabilities to deriveExtensionCapabilities(blueprint) so the manifest grant matches.`}),findings;const declaredSet=new Set(declared),usedSet=new Set(used);for(const capability of used)declaredSet.has(capability)||findings.push({code:"capability_undeclared",severity:"error",message:`Blueprint exercises capability "${capability}" but it is absent from the declared capabilities; activation throws extension_capability_missing \u2014 add "${capability}" to the manifest capabilities.`,capability});for(const capability of declared)usedSet.has(capability)||findings.push({code:"capability_unused",severity:"warning",message:`Capability "${capability}" is declared but no blueprint surface exercises it; drop it to keep the manifest least-privilege (pm package doctor reports this as extension_capability_unused).`,capability});return findings}function collectBlueprintCommandFindings(blueprint){const findings=[],commandPathCounts=new Map;for(const command of blueprint.commands??[]){const path=normalizeCommandName(command.name);commandPathCounts.set(path,(commandPathCounts.get(path)??0)+1)}for(const[path,count]of commandPathCounts)count>1&&findings.push({code:"duplicate_command",severity:"warning",message:`Command "${path}" is declared ${count} times in commands; the later registration shadows the earlier one at dispatch.`,command:path});const overridePaths=new Set(Object.keys(blueprint.commandOverrides??{}).map(command=>normalizeCommandName(command)));for(const path of commandPathCounts.keys())overridePaths.has(path)&&findings.push({code:"command_override_conflict",severity:"warning",message:`Command "${path}" is declared both as a new command definition and as a command override; register one or the other.`,command:path});return findings}function collectBlueprintEmptySurfaceFindings(blueprint){const findings=[];for(const field of BLUEPRINT_LINTABLE_SURFACE_FIELDS)field in blueprint&&!hasEntries(blueprint[field])&&findings.push({code:"empty_surface",severity:"warning",message:`Blueprint field "${field}" is present but empty; remove it or populate it.`,field});if("hooks"in blueprint){const hooks=blueprint.hooks??{};[hooks.beforeCommand,hooks.beforeMutation,hooks.afterCommand,hooks.onWrite,hooks.onRead,hooks.onIndex].some(hasEntries)||findings.push({code:"empty_surface",severity:"warning",message:'Blueprint field "hooks" is present but registers no lifecycle hooks; remove it or populate it.',field:"hooks"})}return findings}function lintExtensionBlueprint(blueprint,options={}){const used=deriveExtensionCapabilities(blueprint),declaredSource=options.declaredCapabilities??blueprint.manifest?.capabilities,declared=Array.isArray(declaredSource)?normalizeDeclaredCapabilities(declaredSource):null,findings=[...collectBlueprintCapabilityFindings(used,declared),...collectBlueprintCommandFindings(blueprint),...collectBlueprintFlagFindings(blueprint),...collectReservedItemFieldFindings(blueprint),...collectBlueprintEmptySurfaceFindings(blueprint)];return{ok:findings.every(finding=>finding.severity!=="error"),findings,used,declared}}function synthesizeExtensionManifest(blueprint,identity){const{additionalCapabilities,...manifestIdentity}=identity,extra=Array.isArray(additionalCapabilities)?normalizeDeclaredCapabilities(additionalCapabilities):[],capabilities=[...new Set([...deriveExtensionCapabilities(blueprint),...extra])].sort((left,right)=>left.localeCompare(right));return{...manifestIdentity,capabilities}}function composeExtensionPackage(blueprint,identity){const manifest=synthesizeExtensionManifest(blueprint,identity);return{module:composeExtension({...blueprint,manifest}),manifest}}function toCompatibilityFinding(evaluation,pmVersion){if(evaluation.status==="absent"||evaluation.status==="ok")return null;const code=`${evaluation.kind}_${evaluation.status}`;let message="";switch(code){case"pm_min_version_invalid":message=`pm_min_version "${evaluation.required}" is not a valid version; the extension is treated as incompatible and the loader skips it.`;break;case"pm_min_version_unchecked":message=`pm_min_version "${evaluation.required}" could not be compared against pm ${pmVersion}; compatibility is unverified.`;break;case"pm_min_version_unmet":message=`Requires pm >= ${evaluation.required} but the target is pm ${pmVersion}; the loader skips the extension.`;break;case"pm_max_version_invalid":message=`pm_max_version "${evaluation.required}" is not a valid inclusive upper bound (version ranges are not allowed); the extension is treated as incompatible and the loader skips it.`;break;case"pm_max_version_unchecked":message=`pm_max_version "${evaluation.required}" could not be compared against pm ${pmVersion}; compatibility is unverified.`;break;case"pm_max_version_exceeded":message=`Allows pm <= ${evaluation.required} but the target is pm ${pmVersion}; the loader skips the extension.`;break;case"pm_max_version_exceeded_warn":message=`Target pm ${pmVersion} is newer than pm_max_version ${evaluation.required}, but the "warn" exceeded mode lets it load with a warning.`;break}return{code,severity:evaluation.allowed?"warning":"error",constraint:evaluation.kind,required:evaluation.required,current:pmVersion,message}}function checkExtensionManifestCompatibility(manifest,target){const minEvaluation=evaluatePmMinVersionBound(manifest.pm_min_version,target.pmVersion),maxEvaluation=evaluatePmMaxVersionBound(manifest.pm_max_version,target.pmVersion,target.pmMaxVersionExceededMode??"block"),schemaFindings=lintExtensionManifestSchema(manifest).findings.map(finding=>({code:finding.code,severity:"warning",constraint:"manifest",required:finding.code==="manifest_unknown_key"?finding.path:"pm_min_version",current:target.pmVersion,path:finding.path,...finding.suggested_key?{suggested_key:finding.suggested_key}:{},message:finding.message})),compatibilityFindings=[],minFinding=toCompatibilityFinding(minEvaluation,target.pmVersion);minFinding!==null&&compatibilityFindings.push(minFinding);const maxFinding=toCompatibilityFinding(maxEvaluation,target.pmVersion);return maxFinding!==null&&compatibilityFindings.push(maxFinding),{compatible:minEvaluation.allowed&&maxEvaluation.allowed,findings:[...schemaFindings,...compatibilityFindings],pmVersion:target.pmVersion}}const CAPABILITY_DRIFT_LINT_CODES=new Set(["capability_undeclared","capability_unused","manifest_capabilities_absent"]);function preflightExtension(blueprint,options={}){const blueprintResult=lintExtensionBlueprint(blueprint,{declaredCapabilities:options.declaredCapabilities}),manifest=options.identity?synthesizeExtensionManifest(blueprint,options.identity):null,compatibility=options.target?checkExtensionManifestCompatibility(manifest??blueprint.manifest??{},options.target):null,findings=[...(manifest!==null&&options.declaredCapabilities===void 0?blueprintResult.findings.filter(finding=>!CAPABILITY_DRIFT_LINT_CODES.has(finding.code)):blueprintResult.findings).map(finding=>({source:"blueprint",severity:finding.severity,code:finding.code,message:finding.message})),...(compatibility?.findings??[]).map(finding=>({source:"compatibility",severity:finding.severity,code:finding.code,message:finding.message}))];return{ok:findings.every(finding=>finding.severity!=="error"),capabilities:blueprintResult.used,blueprint:blueprintResult,manifest,compatibility,findings}}export{checkExtensionManifestCompatibility,composeExtension,composeExtensionPackage,defineExtension,defineExtensionBlueprint,deriveExtensionCapabilities,describeExtensionBlueprint,inspectExtensionManifestSchema,lintExtensionBlueprint,lintExtensionManifestSchema,mergeExtensionBlueprints,preflightExtension,synthesizeExtensionManifest};
2
- //# sourceMappingURL=compose.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="b6abd682-bd34-572d-8630-7b24d1b4746b")}catch{}})();export*from"./cli-contracts.js";export*from"./mcp/executable.js";export*from"./graph/query-contracts.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-intent-contracts.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./flag-invocation-contracts.js";import{resolveExtensionFlagValueContract}from"../core/extensions/flag-value-types.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./output-token-accounting.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./read-output-contracts.js";export*from"./history/attestation-contract.js";export*from"../core/history/operation-contract.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export{resolveExtensionFlagValueContract};
2
- //# sourceMappingURL=contracts.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="48d03e9b-14a4-545c-8e5d-5f5f2092a113")}catch{}})();import{AGENT_PROVENANCE_DIMENSIONS,BUILTIN_AGENT_PROVENANCE_ADAPTERS,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,diagnoseAgentIdentity,detectAgentIdentity,detectHarnessIdentity,listAgentProvenanceAdapters,normalizeAgentProvenanceAdapterValue,readAuthorEnvironment,registerHarnessSignalDescriptors,registerAgentProvenanceAdapters,resolveAuthorIdentity,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,writeAuthorEnvironment}from"../core/shared/author.js";import{SEMANTIC_ATTRIBUTION_LIMITS,recordClaimSemanticAttribution,recordFocusSemanticAttribution,recordReleaseSemanticAttribution,resolveSemanticLineageIds,semanticAttributionAffinity}from"./context/semantic-session-attribution.js";import{explainSourceTraceability,parseSourceLineRange}from"./traceability/source-traceability.js";import{analyzeAgentProvenanceDescriptorCoverage,evaluateSemanticAttributionCoverage,groupHistoryByEpisode,resolveHistoryEpisodeGroupIdentity,summarizeAgentProvenance,summarizeAgentModelProvenance}from"./provenance.js";import{analyzeSdkCliParameterCompleteness}from"./cli-contracts.js";export{AGENT_PROVENANCE_DIMENSIONS,BUILTIN_AGENT_PROVENANCE_ADAPTERS,BUILTIN_HARNESS_SIGNAL_DESCRIPTORS,SEMANTIC_ATTRIBUTION_LIMITS,analyzeAgentProvenanceDescriptorCoverage,analyzeSdkCliParameterCompleteness,detectAgentIdentity,detectHarnessIdentity,diagnoseAgentIdentity,evaluateSemanticAttributionCoverage,explainSourceTraceability,groupHistoryByEpisode,listAgentProvenanceAdapters,normalizeAgentProvenanceAdapterValue,parseSourceLineRange,readAuthorEnvironment,recordClaimSemanticAttribution,recordFocusSemanticAttribution,recordReleaseSemanticAttribution,registerAgentProvenanceAdapters,registerHarnessSignalDescriptors,resolveAuthorIdentity,resolveHistoryEpisodeGroupIdentity,resolveSemanticLineageIds,runWithHarnessDetectionSignals,runWithWorkspaceHarnessSignalDescriptors,semanticAttributionAffinity,summarizeAgentModelProvenance,summarizeAgentProvenance,writeAuthorEnvironment};
2
- //# sourceMappingURL=core-governance.js.map
package/dist/sdk/core.js DELETED
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="da93cfe5-b451-50d5-b763-a303bf1f19cc")}catch{}})();import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,canonicalDocument,classifyItemFormatVersion,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,isPmCliExpectedError,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,nowIso,runAction,serializeItemDocument,aggregate,append,claim,claimNext,close,comments,context,copy,create,deleteItem,deps,docs,files,filesDiscover,focus,get,graph,learnings,list,next,notes,release,reopen,restore,search,update,listAllComplete}from"./runtime.js";export*from"./core-governance.js";import{updateLinkedTest}from"./test/update.js";import{isItemAlreadyExistsError,isPmTokenBudgetRecovery}from"./errors.js";export*from"./agent-session-context.js";import{isAlreadyClaimedError}from"./lifecycle/claim.js";import{PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,applyReadOutputDimensions,decodeReadOutputContinuationCursor,encodeReadOutputContinuationCursor,isReadOutputBudgetExceeded,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,validateReadOutputOptions}from"./read-output-contracts.js";import{applyReadOutputSessionReferences,attachReadOutputSessionReceipt,parseReadOutputSession,readOutputSessionRemainingTokens,isReadOutputSessionReference}from"./read-output-session.js";import{assertWellFormedOutputText,toWellFormedText}from"../core/shared/output-unicode.js";export{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PM_READ_OUTPUT_COMPOSITION_OPTION_FLAGS,PM_READ_OUTPUT_DIMENSIONS,PM_READ_OUTPUT_OPTION_FLAGS,PM_READ_OUTPUT_SURFACE_CONTRACTS,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,aggregate,append,applyReadOutputDimensions,applyReadOutputSessionReferences,assertWellFormedOutputText,attachReadOutputSessionReceipt,canonicalDocument,claim,claimNext,classifyItemFormatVersion,close,comments,context,copy,create,createPmCliExpectedError,decodeReadOutputContinuationCursor,deleteItem,deps,docs,effectiveItemFormatVersion,emptyImportedDocument,encodeReadOutputContinuationCursor,files,filesDiscover,focus,get,graph,isAlreadyClaimedError,isItemAlreadyExistsError,isPmCliExpectedError,isPmTokenBudgetRecovery,isReadOutputBudgetExceeded,isReadOutputSessionReference,learnings,list,listAllComplete,next,normalizeItemFormatVersion,normalizeItemId,normalizeStatusInput,notes,nowIso,parseReadOutputSession,readOutputSessionRemainingTokens,release,reopen,resolveReadOutputDimensions,resolveReadOutputEncoding,resolveReadOutputSurface,restore,runAction,search,serializeItemDocument,toWellFormedText,update,updateLinkedTest,validateReadOutputOptions};
2
- //# sourceMappingURL=core.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1202ba19-0bcb-5478-b245-4472e361d4de")}catch{}})();const PM_CORPUS_SHAPE_SCHEMA="https://schema.unbrained.dev/pm/corpus-shape/v1";function positiveInteger(value,field){if(!Number.isSafeInteger(value)||value<=0)throw new TypeError(`Corpus shape ${field} must be a positive safe integer`);return value}function nonNegativeInteger(value,field){if(!Number.isSafeInteger(value)||value<0)throw new TypeError(`Corpus shape ${field} must be a non-negative safe integer`);return value}function deepFreeze(value){if(!(typeof value!="object"||value===null||Object.isFrozen(value))){for(const nested of Object.values(value))deepFreeze(nested);Object.freeze(value)}}function defineCorpusShape(shape){if(shape.schema!==PM_CORPUS_SHAPE_SCHEMA)throw new TypeError(`Unsupported corpus shape schema: ${shape.schema}`);if(shape.name.trim().length===0||shape.description.trim().length===0)throw new TypeError("Corpus shape name and description must be non-empty");if(positiveInteger(shape.hierarchy_depth,"hierarchy_depth"),positiveInteger(shape.hierarchy_fanout,"hierarchy_fanout"),nonNegativeInteger(shape.age_span_days,"age_span_days"),positiveInteger(shape.history_entries_per_item,"history_entries_per_item"),nonNegativeInteger(shape.comments_per_100_items,"comments_per_100_items"),nonNegativeInteger(shape.notes_per_100_items,"notes_per_100_items"),nonNegativeInteger(shape.learnings_per_100_items,"learnings_per_100_items"),positiveInteger(shape.author_cardinality,"author_cardinality"),positiveInteger(shape.component_count,"component_count"),shape.edge_kind_mix.length===0||shape.edge_kind_mix.some(edge=>edge.kind.trim().length===0||edge.weight<=0))throw new TypeError("Corpus shape edge_kind_mix requires non-empty kinds with positive weights");if(shape.terminal_statuses.some(status=>!shape.custom_statuses.includes(status)))throw new TypeError("Corpus shape terminal_statuses must be declared in custom_statuses");const detached=structuredClone(shape);return deepFreeze(detached),detached}const COMMON_EDGE_MIX=[{kind:"implements",weight:5},{kind:"blocked_by",weight:2},{kind:"discovered_from",weight:2},{kind:"verifies",weight:2},{kind:"supersedes",weight:1},{kind:"related",weight:4}],BUILTIN_CORPUS_SHAPES=Object.freeze({scratch:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"scratch",description:"Seconds-old, shallow project with minimal history.",hierarchy_depth:2,hierarchy_fanout:50,age_span_days:0,history_entries_per_item:1,comments_per_100_items:2,notes_per_100_items:1,learnings_per_100_items:1,edge_kind_mix:[{kind:"related",weight:1}],author_cardinality:2,component_count:1,include_cycles:!1,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),representative:defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"representative",description:"Medium-lived project with rich evidence and typed lineage.",hierarchy_depth:5,hierarchy_fanout:8,age_span_days:730,history_entries_per_item:12,comments_per_100_items:30,notes_per_100_items:12,learnings_per_100_items:10,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:32,component_count:1,include_cycles:!1,custom_types:["Experiment"],custom_statuses:["review"],terminal_statuses:[],custom_fields:["domain"]}),"deep-graph":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"deep-graph",description:"Deep typed relationship graph with deterministic cycles.",hierarchy_depth:16,hierarchy_fanout:2,age_span_days:3650,history_entries_per_item:6,comments_per_100_items:15,notes_per_100_items:8,learnings_per_100_items:8,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:16,component_count:1,include_cycles:!0,custom_types:[],custom_statuses:[],terminal_statuses:[],custom_fields:[]}),"multi-decade":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"multi-decade",description:"Thirty-year event history with dense per-item evolution.",hierarchy_depth:6,hierarchy_fanout:6,age_span_days:10958,history_entries_per_item:24,comments_per_100_items:40,notes_per_100_items:20,learnings_per_100_items:16,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:64,component_count:1,include_cycles:!1,custom_types:["Program"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["portfolio"]}),"disconnected-archive":defineCorpusShape({schema:PM_CORPUS_SHAPE_SCHEMA,name:"disconnected-archive",description:"Multiple disconnected historical project components.",hierarchy_depth:4,hierarchy_fanout:10,age_span_days:7305,history_entries_per_item:8,comments_per_100_items:10,notes_per_100_items:5,learnings_per_100_items:6,edge_kind_mix:COMMON_EDGE_MIX,author_cardinality:24,component_count:5,include_cycles:!1,custom_types:["Archive"],custom_statuses:["archived"],terminal_statuses:["archived"],custom_fields:["archive_source"]})});function listBuiltinCorpusShapes(){return Object.keys(BUILTIN_CORPUS_SHAPES).sort().map(name=>BUILTIN_CORPUS_SHAPES[name])}function resolveBuiltinCorpusShape(name){const normalized=name.trim().toLowerCase();if(!Object.hasOwn(BUILTIN_CORPUS_SHAPES,normalized))throw new TypeError(`Unknown corpus shape "${name}". Available: ${Object.keys(BUILTIN_CORPUS_SHAPES).join(", ")}`);return BUILTIN_CORPUS_SHAPES[normalized]}const expandedEdgeKinds=new WeakMap;function selectedEdgeKinds(index,shape){if(index===0)return[];let expanded=expandedEdgeKinds.get(shape);expanded===void 0&&(expanded=shape.edge_kind_mix.flatMap(entry=>Array.from({length:entry.weight},()=>entry.kind)),expandedEdgeKinds.set(shape,expanded));const kinds=[expanded[index%expanded.length]];return shape.include_cycles&&index>2&&index%17===0&&kinds.push("related"),[...new Set(kinds)]}function buildCorpusShapeItemPlan(shape,index,itemCount,seed=42){if(nonNegativeInteger(index,"item index"),positiveInteger(itemCount,"item count"),index>=itemCount)throw new RangeError(`Corpus item index ${index} exceeds ${itemCount}`);const componentCount=Math.min(shape.component_count,itemCount),component=index%componentCount,componentPosition=Math.floor(index/componentCount);let hierarchyCapacity=0,levelWidth=1;for(let depth=0;depth<shape.hierarchy_depth;depth+=1)hierarchyCapacity=Math.min(Number.MAX_SAFE_INTEGER,hierarchyCapacity+levelWidth),levelWidth=Math.min(Number.MAX_SAFE_INTEGER,levelWidth*shape.hierarchy_fanout);const treeOffset=componentPosition%hierarchyCapacity,treeStart=componentPosition-treeOffset,parentIndex=treeOffset===0?void 0:component+(treeStart+Math.floor((treeOffset-1)/shape.hierarchy_fanout))*componentCount,base=Date.UTC(2026,0,1),spanMs=shape.age_span_days*864e5,timestamp=new Date(base+(itemCount===1?0:Math.round(index/(itemCount-1)*spanMs))).toISOString(),annotationBucket=(index*37+seed)%100;return{index,id:`pm-s${index.toString(36).padStart(7,"0")}`,...parentIndex===void 0?{}:{parent:`pm-s${parentIndex.toString(36).padStart(7,"0")}`},component,timestamp,author:`pm-corpus-agent-${(index+seed)%Math.min(shape.author_cardinality,itemCount)}`,history_entry_count:shape.history_entries_per_item,dependency_kinds:selectedEdgeKinds(index,shape),has_comment:annotationBucket<shape.comments_per_100_items,has_note:annotationBucket<shape.notes_per_100_items,has_learning:annotationBucket<shape.learnings_per_100_items,...shape.custom_types.length>0&&index%11===0?{custom_type:shape.custom_types[index%shape.custom_types.length]}:{},...shape.custom_statuses.length>0&&index%13===0?{custom_status:shape.custom_statuses[index%shape.custom_statuses.length]}:{}}}class IncrementalCorpusShapeMeasurement{shape;authors=new Set;components=new Set;depths=new Map;childCounts=new Map;edgeKinds={};expectedEdgeKinds={};annotations={comments:0,notes:0,learnings:0};annotationFields;planMismatches=[];itemCount=0;observedDepth=0;observedFanout=0;historyEntryCount=0;firstTimestamp=null;lastTimestamp=null;constructor(shape){this.shape=shape,this.annotationFields=[["comments","has_comment",shape.comments_per_100_items],["notes","has_note",shape.notes_per_100_items],["learnings","has_learning",shape.learnings_per_100_items]]}recordMismatch(mismatched,message){mismatched&&this.planMismatches.push(message)}recordEdgeKinds(counts,kinds){for(const kind of kinds)counts[kind]=(counts[kind]??0)+1}add(plan){this.itemCount+=1,this.authors.add(plan.author),this.components.add(plan.component),this.recordMismatch(this.depths.has(plan.id),`duplicate_id:${plan.id}`);let depth=1;if(plan.parent!==void 0){const parentDepth=this.depths.get(plan.parent);this.recordMismatch(parentDepth===void 0,`parent_missing:${plan.parent}`),depth=(parentDepth??0)+1;const childCount=(this.childCounts.get(plan.parent)??0)+1;this.childCounts.set(plan.parent,childCount),this.observedFanout=Math.max(this.observedFanout,childCount)}this.depths.set(plan.id,depth),this.observedDepth=Math.max(this.observedDepth,depth),this.historyEntryCount+=plan.history_entry_count,this.recordMismatch(plan.history_entry_count!==this.shape.history_entries_per_item,"history_entries_per_item:drift"),this.firstTimestamp=this.firstTimestamp===null||plan.timestamp<this.firstTimestamp?plan.timestamp:this.firstTimestamp,this.lastTimestamp=this.lastTimestamp===null||plan.timestamp>this.lastTimestamp?plan.timestamp:this.lastTimestamp;for(const[annotation,property]of this.annotationFields)this.annotations[annotation]+=Number(plan[property]);this.recordEdgeKinds(this.edgeKinds,plan.dependency_kinds),this.recordEdgeKinds(this.expectedEdgeKinds,selectedEdgeKinds(plan.index,this.shape))}finish(){const expectedAuthors=Math.min(this.shape.author_cardinality,this.itemCount),expectedComponents=Math.min(this.shape.component_count,this.itemCount),mismatches=[...this.planMismatches,...this.itemCount===0?["item_count:empty"]:[],...this.authors.size===expectedAuthors?[]:[`author_count:${this.authors.size}!=${expectedAuthors}`],...this.components.size===expectedComponents?[]:[`component_count:${this.components.size}!=${expectedComponents}`],...this.observedDepth<=this.shape.hierarchy_depth?[]:[`hierarchy_depth:${this.observedDepth}>${this.shape.hierarchy_depth}`],...this.observedFanout<=this.shape.hierarchy_fanout?[]:[`hierarchy_fanout:${this.observedFanout}>${this.shape.hierarchy_fanout}`]];for(const[annotation,,rate]of this.annotationFields){const completeBuckets=Math.floor(this.itemCount/100),remainder=this.itemCount%100,minimum=completeBuckets*rate+Math.max(0,rate+remainder-100),maximum=completeBuckets*rate+Math.min(rate,remainder),observed=this.annotations[annotation];(observed<minimum||observed>maximum)&&mismatches.push(`${annotation}:${observed}!in[${minimum},${maximum}]`)}const edgeKindNames=new Set([...Object.keys(this.edgeKinds),...Object.keys(this.expectedEdgeKinds)]);for(const kind of[...edgeKindNames].sort()){const observed=this.edgeKinds[kind]??0,expected=this.expectedEdgeKinds[kind]??0;observed!==expected&&mismatches.push(`edge_kind:${kind}:${observed}!=${expected}`)}const uniqueMismatches=[...new Set(mismatches)];return{shape:this.shape.name,item_count:this.itemCount,author_count:this.authors.size,component_count:this.components.size,hierarchy_depth:this.observedDepth,hierarchy_fanout:this.observedFanout,timestamp_range:{first:this.firstTimestamp,last:this.lastTimestamp},history_entry_count:this.historyEntryCount,annotations:{...this.annotations},edge_kinds:{...this.edgeKinds},matches_declaration:uniqueMismatches.length===0,mismatches:uniqueMismatches}}}function createCorpusShapeMeasurement(shape){return new IncrementalCorpusShapeMeasurement(shape)}function measureCorpusShapePlan(shape,plans){const measurement=createCorpusShapeMeasurement(shape);for(const plan of plans)measurement.add(plan);return measurement.finish()}export{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape};
2
- //# sourceMappingURL=corpus-shape.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3f3a5dca-8370-52d7-b279-dc6f9f0aeadf")}catch{}})();function defineExtensionManifest(manifest){return manifest}function defineProjectProfile(profile){return profile}function defineCommand(definition){return definition}function defineFlag(flag){return flag}function defineItemType(type){return type}function defineItemField(field){return field}function defineMigration(migration){return migration}function defineSearchProvider(provider){return provider}function defineVectorStoreAdapter(adapter){return adapter}function defineCommandOverride(override){return override}function defineParserOverride(override){return override}function definePreflightOverride(override){return override}function defineServiceOverride(override){return override}function handleServiceOverride(result){return{handled:!0,result}}function declineServiceOverride(){return{handled:!1}}function defineRendererOverride(renderer){return renderer}function defineImporter(importer){return importer}function defineExporter(exporter){return exporter}function defineBeforeCommandHook(hook){return hook}function defineBeforeMutationHook(hook){return hook}function defineAfterCommandHook(hook){return hook}function defineOnWriteHook(hook){return hook}function defineOnReadHook(hook){return hook}function defineOnIndexHook(hook){return hook}export{declineServiceOverride,defineAfterCommandHook,defineBeforeCommandHook,defineBeforeMutationHook,defineCommand,defineCommandOverride,defineExporter,defineExtensionManifest,defineFlag,defineImporter,defineItemField,defineItemType,defineMigration,defineOnIndexHook,defineOnReadHook,defineOnWriteHook,defineParserOverride,definePreflightOverride,defineProjectProfile,defineRendererOverride,defineSearchProvider,defineServiceOverride,defineVectorStoreAdapter,handleServiceOverride};
2
- //# sourceMappingURL=define.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c234be1c-35b7-5388-8a70-a012e9a34389")}catch{}})();import{sha256Hex,stableStringify}from"../../core/shared/serialization.js";import{runWithAgentSessionContext}from"../agent-session-context.js";import{defineWorkspaceRecipe}from"../workspace-recipe.js";const PM_OBSERVATION_SCHEMA="pm.agent-observation/v1",PM_VERDICT_SCHEMA="pm.agent-verdict/v1",PM_EPISODE_SCHEMA="pm.agent-episode/v1";function assertPositiveInteger(value,label){if(!Number.isSafeInteger(value)||value<=0)throw new Error(`${label} must be a positive safe integer.`)}function assertNonEmpty(value,label){if(value.trim().length===0)throw new Error(`${label} must not be empty.`)}function frozenCopy(value){if(value!==null&&typeof value=="object"&&!Object.isFrozen(value)){Object.freeze(value);for(const nested of Object.values(value))frozenCopy(nested)}return value}function validateObservationReads(reads){if(reads.length===0)throw new Error("observation.reads must declare at least one bounded read.");let readCeiling=0;for(const read of reads)if(assertNonEmpty(read.command,"observation.reads.command"),assertPositiveInteger(read.budget_tokens,"observation.reads.budget_tokens"),readCeiling+=read.budget_tokens,!Number.isSafeInteger(readCeiling))throw new Error("observation read ceilings exceed safe integer range.")}function validateObservationCalibration(calibration){if(calibration.basis!=="emitted_bytes")throw new Error("observation calibration must use emitted_bytes.");for(const sample of calibration.samples)if(!Number.isSafeInteger(sample)||sample<0)throw new Error("observation calibration samples must be non-negative safe integers.");if(calibration.samples.length===0)throw new Error("observation calibration must include at least one sample.");if(assertPositiveInteger(calibration.expected_emitted_bytes,"observation.calibration.expected_emitted_bytes"),!Number.isSafeInteger(calibration.tolerance_bytes)||calibration.tolerance_bytes<0)throw new Error("observation.calibration.tolerance_bytes must be a non-negative safe integer.");const sampleMean=calibration.samples.reduce((total,sample)=>total+sample,0)/calibration.samples.length;if(Math.abs(sampleMean-calibration.expected_emitted_bytes)>calibration.tolerance_bytes)throw new Error("observation expected_emitted_bytes is outside the calibrated sample tolerance.")}function validateObservationTiers(tiers){if(tiers.length===0)throw new Error("observation.tiers must declare a degradation ladder.");const tierIds=new Set;let previousTierBudget=Number.POSITIVE_INFINITY;for(const tier of tiers){if(assertNonEmpty(tier.id,"observation.tiers.id"),assertPositiveInteger(tier.max_tokens,"observation.tiers.max_tokens"),tierIds.has(tier.id))throw new Error(`Duplicate observation tier: ${tier.id}.`);if(tierIds.add(tier.id),tier.max_tokens>previousTierBudget)throw new Error("observation tiers must be ordered from largest to smallest max_tokens.");previousTierBudget=tier.max_tokens;const fields=new Set;for(const field of tier.fields){if(parseFieldPath(field,"observation.tiers.fields"),fields.has(field))throw new Error(`Duplicate observation tier field: ${field}.`);fields.add(field)}}}function defineObservationContract(declaration){if(declaration.schema!==PM_OBSERVATION_SCHEMA)throw new Error(`observation.schema must be ${PM_OBSERVATION_SCHEMA}.`);return assertNonEmpty(declaration.id,"observation.id"),assertPositiveInteger(declaration.version,"observation.version"),validateObservationReads(declaration.reads),validateObservationCalibration(declaration.calibration),declaration.corpus_dependence.kind==="bounded"&&(assertNonEmpty(declaration.corpus_dependence.dimension,"observation.corpus_dependence.dimension"),assertPositiveInteger(declaration.corpus_dependence.maximum,"observation.corpus_dependence.maximum")),validateObservationTiers(declaration.tiers),frozenCopy(structuredClone(declaration))}function describeObservationCost(contract){return{contract_id:contract.id,contract_version:contract.version,guaranteed_ceiling_tokens:contract.reads.reduce((total,read)=>total+read.budget_tokens,0),expected_emitted_bytes:contract.calibration.expected_emitted_bytes,expected_tokens:Math.ceil(contract.calibration.expected_emitted_bytes/4),tolerance_bytes:contract.calibration.tolerance_bytes,calibration_basis:"emitted_bytes",corpus_dependence:contract.corpus_dependence}}async function serveDeclaredObservation(contract,collect,request){assertPositiveInteger(request.budget_tokens,"observation request budget_tokens");const attempted=[];for(const[index,tier]of contract.tiers.entries()){attempted.push(tier.id);const payload=await collect(tier),emittedBytes=Buffer.byteLength(stableStringify(payload),"utf8"),estimatedTokens=Math.ceil(emittedBytes/4);if(estimatedTokens<=Math.min(request.budget_tokens,tier.max_tokens))return{status:"served",payload,receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:tier.id,degraded:index>0,attempted_tiers:attempted,emitted_bytes:emittedBytes,estimated_tokens:estimatedTokens,calibration_basis:"emitted_bytes"}}}return{status:"refused",reason:"no_declared_tier_fits_budget",receipt:{contract_id:contract.id,contract_version:contract.version,served_tier:null,degraded:contract.tiers.length>1,attempted_tiers:attempted,emitted_bytes:null,estimated_tokens:null,calibration_basis:"emitted_bytes"}}}function parseFieldPath(path,label){const segments=path.split(".");if(segments.some(segment=>segment.length===0||segment==="__proto__"||segment==="prototype"||segment==="constructor"))throw new Error(`${label} must be a safe, non-empty dot-separated path.`);return segments}function valueAtPath(root,path){let value=root;for(const segment of parseFieldPath(path,"recorded field path")){if(value===null||typeof value!="object"||!Object.hasOwn(value,segment))return;value=value[segment]}return value}function jsonPointer(path){return`/${parseFieldPath(path,"verdict predicate path").map(segment=>segment.replaceAll("~","~0").replaceAll("/","~1")).join("/")}`}function assertPortableExpectedValue(predicate){if(predicate.kind!=="field_equals")return;let serializedExpected;try{serializedExpected=JSON.stringify(predicate.expected)}catch{throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}if(serializedExpected===void 0)throw new Error(`Expected value for verdict predicate ${predicate.id} must be JSON serializable.`)}function defineVerdictContract(declaration){if(declaration.schema!==PM_VERDICT_SCHEMA)throw new Error(`verdict.schema must be ${PM_VERDICT_SCHEMA}.`);assertNonEmpty(declaration.id,"verdict.id"),assertPositiveInteger(declaration.version,"verdict.version");const predicateIds=new Set;for(const predicate of declaration.predicates){assertNonEmpty(predicate.id,"verdict.predicates.id"),parseFieldPath(predicate.path,"verdict.predicates.path");const runtimeKind=predicate.kind;if(runtimeKind!=="field_equals"&&runtimeKind!=="field_present"&&runtimeKind!=="field_absent")throw new Error(`Unsupported verdict predicate kind for ${predicate.id}.`);if(predicateIds.has(predicate.id))throw new Error(`Duplicate verdict predicate: ${predicate.id}.`);assertPortableExpectedValue(predicate),predicateIds.add(predicate.id)}if(declaration.composition.operator!=="all"&&declaration.composition.operator!=="any")throw new Error("verdict composition operator must be all or any.");if(declaration.composition.predicate_ids.length!==declaration.predicates.length)throw new Error("verdict composition must reference every predicate exactly once.");const compositionIds=new Set(declaration.composition.predicate_ids);if(compositionIds.size!==declaration.composition.predicate_ids.length||[...compositionIds].some(id=>!predicateIds.has(id)))throw new Error("verdict composition contains duplicate or unknown predicate ids.");return frozenCopy(structuredClone(declaration))}function evaluateVerdictContract(contract,recorded){if(contract.predicates.length===0)return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:"not_applicable",score:null,policy:"verdict_only_no_reward",reason:"no_predicates_declared",predicates:[]};const byId=new Map(contract.predicates.map(predicate=>[predicate.id,predicate])),predicates=contract.composition.predicate_ids.map(id=>{const predicate=byId.get(id),observed=valueAtPath(recorded.state,predicate.path),satisfied2=predicate.kind==="field_present"?observed!==void 0:predicate.kind==="field_absent"?observed===void 0:stableStringify(observed)===stableStringify(predicate.expected);return{id,outcome:satisfied2?"satisfied":"violated",evidence_pointer:`${recorded.snapshot_id}#${jsonPointer(predicate.path)}`,evidence_digest:sha256Hex(stableStringify(observed))}}),satisfiedCount=predicates.filter(predicate=>predicate.outcome==="satisfied").length,satisfied=contract.composition.operator==="all"?satisfiedCount===predicates.length:satisfiedCount>0;return{contract_id:contract.id,contract_version:contract.version,snapshot_id:recorded.snapshot_id,outcome:satisfied?"satisfied":"violated",score:satisfiedCount/predicates.length,policy:"verdict_only_no_reward",predicates}}function defineEpisodeSpecification(declaration){if(declaration.schema!==PM_EPISODE_SCHEMA)throw new Error(`episode.schema must be ${PM_EPISODE_SCHEMA}.`);if(assertNonEmpty(declaration.id,"episode.id"),assertPositiveInteger(declaration.version,"episode.version"),!["benchmark","evaluation","training","scale_transfer"].includes(declaration.mode))throw new Error("episode.mode is not supported.");if(declaration.task_item_ids.length===0)throw new Error("episode.task_item_ids must declare at least one pm item.");for(const itemId of declaration.task_item_ids)assertNonEmpty(itemId,"episode.task_item_ids");assertPositiveInteger(declaration.limits.max_actions,"episode.limits.max_actions"),assertPositiveInteger(declaration.limits.max_observations,"episode.limits.max_observations"),assertPositiveInteger(declaration.limits.max_tokens_per_observation,"episode.limits.max_tokens_per_observation");for(const field of declaration.observable_fields)parseFieldPath(field,"episode.observable_fields");for(const field of declaration.withheld_fields)parseFieldPath(field,"episode.withheld_fields");for(const observable of declaration.observable_fields){const overlap=declaration.withheld_fields.find(withheld=>observable===withheld||observable.startsWith(`${withheld}.`)||withheld.startsWith(`${observable}.`));if(overlap!==void 0)throw new Error(`Observable field ${observable} overlaps withheld field ${overlap}.`)}for(const tier of declaration.observation.tiers)for(const field of tier.fields)if(!declaration.observable_fields.includes(field))throw new Error(`Observation tier field ${field} is not declared observable.`);return defineObservationContract(declaration.observation),defineVerdictContract(declaration.verdict),defineWorkspaceRecipe(declaration.recipe),frozenCopy(structuredClone(declaration))}function assignProjectedPath(target,path,value){const segments=parseFieldPath(path,"observation projection field");let cursor=target;for(const[index,segment]of segments.entries()){if(index===segments.length-1){value!==void 0&&(cursor[segment]=structuredClone(value));return}const nested=cursor[segment];(nested===null||typeof nested!="object"||Array.isArray(nested))&&(cursor[segment]={}),cursor=cursor[segment]}}function projectedState(state,fields){const result={};for(const field of fields)assignProjectedPath(result,field,valueAtPath(state,field));return result}async function openPmEpisode(specification,adapter){const trajectory=[];let actions=0,observations=0,closed=!1,closing;const context={episode:{id:specification.id,label:`pm agent environment v${specification.version}`},provenance:{role:specification.mode,topic:"agent-environment"}},reset=await runWithAgentSessionContext(context,()=>adapter.reset(specification.recipe));trajectory.push({sequence:1,kind:"reset",state_id:reset.state_id});const readObservation=async()=>{if(closed)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations)throw new Error("episode exceeded limits.max_observations.");observations+=1;const recorded=await adapter.readRecordedState(),result=await serveDeclaredObservation(specification.observation,async tier=>projectedState(recorded.state,tier.fields),{budget_tokens:specification.limits.max_tokens_per_observation});return trajectory.push({sequence:trajectory.length+1,kind:"observation",state_id:result.receipt.served_tier??recorded.snapshot_id}),result},evaluate=async(reservedForClose=!1)=>{if(closed&&!reservedForClose)throw new Error("episode is already closed.");if(observations>=specification.limits.max_observations)throw new Error("episode exceeded limits.max_observations.");observations+=1;const recorded=await adapter.readRecordedState(),result=evaluateVerdictContract(specification.verdict,recorded);return trajectory.push({sequence:trajectory.length+1,kind:"verdict",state_id:recorded.snapshot_id}),result};return{observe:()=>runWithAgentSessionContext(context,readObservation),step:async action=>{if(closed)throw new Error("episode is already closed.");if(actions>=specification.limits.max_actions)throw new Error("episode exceeded limits.max_actions.");actions+=1;const result=await runWithAgentSessionContext(context,()=>adapter.execute(action));return trajectory.push({sequence:trajectory.length+1,kind:"action",state_id:result.state_id}),result},score:()=>runWithAgentSessionContext(context,evaluate),close:()=>closing!==void 0?closing:closed?Promise.reject(new Error("episode is already closed.")):(closed=!0,closing=runWithAgentSessionContext(context,()=>evaluate(!0)).then(verdict=>(trajectory.push({sequence:trajectory.length+1,kind:"close",state_id:verdict.snapshot_id}),{verdict,trajectory:frozenCopy(structuredClone(trajectory))})).catch(error=>{throw closed=!1,error}).finally(()=>{closing=void 0}),closing)}}export{PM_EPISODE_SCHEMA,PM_OBSERVATION_SCHEMA,PM_VERDICT_SCHEMA,defineEpisodeSpecification,defineObservationContract,defineVerdictContract,describeObservationCost,evaluateVerdictContract,openPmEpisode,serveDeclaredObservation};
2
- //# sourceMappingURL=agent-environment.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="773ad2b6-326e-5483-bdce-a377f935cb31")}catch{}})();function validIdentity(value){return typeof value=="string"&&value.length>0&&value.trim()===value}function inventory(snapshots){if(!Array.isArray(snapshots)||snapshots.length<2)throw new TypeError("Expected at least two artifact ledgers.");const ledgers=new Map;for(const snapshot of snapshots){if(snapshot===null||typeof snapshot!="object"||!validIdentity(snapshot.name)||ledgers.has(snapshot.name)||snapshot.complete!==!0)throw new TypeError("Expected unique complete artifact ledgers.");if(!Array.isArray(snapshot.identities))throw new TypeError("Invalid or duplicate artifact identity.");const identities=new Set(snapshot.identities);if(identities.size!==snapshot.identities.length||[...identities].some(id=>!validIdentity(id)))throw new TypeError("Invalid or duplicate artifact identity.");ledgers.set(snapshot.name,identities)}if([...ledgers.values()].every(identities=>identities.size===0))throw new TypeError("Empty inventories cannot establish artifact reconciliation.");return ledgers}function settlements(exceptions,names){if(!Array.isArray(exceptions))throw new TypeError("Expected unique evidence-backed artifact exceptions.");const accepted=new Map;for(const exception of exceptions){if(exception===null||typeof exception!="object"||!validIdentity(exception.identity)||accepted.has(exception.identity)||!validIdentity(exception.reason)||!validIdentity(exception.evidence))throw new TypeError("Expected unique evidence-backed artifact exceptions.");const missing=exception.missing_from;if(!Array.isArray(missing)||missing.length===0||missing.length>=names.length||new Set(missing).size!==missing.length||[...missing].some(name=>!names.includes(name)))throw new TypeError("Invalid artifact exception ledger signature.");accepted.set(exception.identity,exception)}return accepted}function reconcileArtifactLedgers(snapshots,exceptions=[]){const ledgers=inventory(snapshots),names=[...ledgers.keys()].sort(),accepted=settlements(exceptions,names),identities=[...new Set([...ledgers.values()].flatMap(set=>[...set]))].sort(),findings=[],matched=new Set;for(const identity of identities){const missing=names.filter(name=>!ledgers.get(name).has(identity));if(missing.length===0)continue;const exception=accepted.get(identity),settled=exception!==void 0&&JSON.stringify([...exception.missing_from].sort())===JSON.stringify(missing);settled&&matched.add(identity),findings.push({identity,present_in:names.filter(name=>ledgers.get(name).has(identity)),missing_from:missing,disposition:settled?{reason:exception.reason,evidence:exception.evidence}:null})}const stale=[...accepted.keys()].filter(identity=>!matched.has(identity)).sort();return{schema:"pm-artifact-ledgers/1",ok:findings.every(finding=>finding.disposition!==null)&&stale.length===0,counts:Object.fromEntries(names.map(name=>[name,ledgers.get(name).size])),findings,stale_exceptions:stale}}export{reconcileArtifactLedgers};
2
- //# sourceMappingURL=artifact-ledgers.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="c1cb8d82-20a6-5460-a0ff-f55312911218")}catch{}})();const PM_EXACT_COVERAGE_METRICS=["lines","branches","functions","statements"];function assertCoverageEntry(file,entry){if(typeof entry!="object"||entry===null||Array.isArray(entry))throw new TypeError(`Coverage entry for ${file} must be an object.`)}function coverageCounts(file,metric,value){if(typeof value!="object"||value===null||Array.isArray(value))throw new TypeError(`Coverage entry ${file} has invalid ${metric} counts.`);const counts=value;if(typeof counts.covered!="number"||typeof counts.total!="number"||!Number.isInteger(counts.covered)||!Number.isInteger(counts.total)||counts.covered<0||counts.total<counts.covered)throw new TypeError(`Coverage entry ${file} has invalid ${metric} counts.`);return{covered:counts.covered,total:counts.total}}function findCoverageDeficits(summary){if(typeof summary!="object"||summary===null||Array.isArray(summary))throw new TypeError("Coverage summary must be a JSON object.");if(!("total"in summary))throw new TypeError("Coverage summary is missing the total entry.");const deficits=[];for(const[file,entry]of Object.entries(summary)){assertCoverageEntry(file,entry);for(const metric of PM_EXACT_COVERAGE_METRICS){const counts=coverageCounts(file,metric,entry[metric]),uncovered=counts.total-counts.covered;uncovered>0&&deficits.push({file,metric,uncovered,...counts})}}return deficits}export{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits};
2
- //# sourceMappingURL=coverage-assurance.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="604d7dcb-9fea-5631-8a72-b2a7ff3278f8")}catch{}})();import{isRfc3339DateTime}from"../../core/shared/time.js";function instant(value){if(typeof value!="string"||!isRfc3339DateTime(value))throw new TypeError("Invalid reliability timestamp.");return Date.parse(value)}function validatePolicy(policy){const start=instant(policy.window_start),end=instant(policy.window_end);if(start>=end||!Number.isFinite(policy.max_failure_rate)||policy.max_failure_rate<0||policy.max_failure_rate>=1||!Number.isSafeInteger(policy.min_completed_attempts)||policy.min_completed_attempts<1)throw new TypeError("Invalid reliability window policy.");if(policy.families.length===0||policy.families.some(family=>typeof family!="string"||family.trim().length===0)||new Set(policy.families).size!==policy.families.length)throw new TypeError("Expected unique, nonempty reliability families.");return{start,end}}function groupAttempts(attempts,families,start,end){const groups=new Map(families.map(family=>[family,[]])),ids=new Set;for(const attempt of attempts){if(typeof attempt.id!="string"||attempt.id.trim().length===0||ids.has(attempt.id))throw new TypeError("Invalid or duplicate reliability attempt identity.");ids.add(attempt.id);const group=groups.get(attempt.family);if(!group||!["success","failure","pending"].includes(attempt.outcome)||attempt.cause!==void 0&&(!["product","infrastructure","unknown"].includes(attempt.cause)||attempt.outcome!=="failure"))throw new TypeError("Invalid reliability attempt family, outcome or cause.");const created=instant(attempt.started_at);if(attempt.repaired_at!==void 0&&(instant(attempt.repaired_at)<created||attempt.outcome!=="failure"))throw new TypeError("Invalid reliability repair chronology.");created>=start&&created<end&&group.push(attempt)}return groups}function evaluateReliabilityWindow(attempts,policy){const{start,end}=validatePolicy(policy),families=[...groupAttempts(attempts,policy.families,start,end)].map(([family,rows])=>{const failed=rows.filter(row=>row.outcome==="failure"),completed=rows.filter(row=>row.outcome!=="pending").length,rate=completed===0?null:failed.length/completed,repairs=failed.filter(row=>row.repaired_at!==void 0&&instant(row.repaired_at)<end),causes={product:0,infrastructure:0,unknown:0};for(const row of failed)causes[row.cause??"unknown"]+=1;const violations=[];return completed<policy.min_completed_attempts&&violations.push("insufficient_completed_attempts"),rate!==null&&rate>policy.max_failure_rate&&violations.push("failure_rate"),{family,attempts:rows.length,completed,failed:failed.length,pending:rows.length-completed,failure_rate:rate,affected_days:[...new Set(failed.map(row=>new Date(instant(row.started_at)).toISOString().slice(0,10)))].sort(),repair_minutes:repairs.map(row=>(instant(row.repaired_at)-instant(row.started_at))/6e4).sort((a,b)=>a-b),unresolved:failed.length-repairs.length,causes,violations,ok:violations.length===0}});return{schema:"pm-reliability-window/1",window_start:new Date(start).toISOString(),window_end:new Date(end).toISOString(),ok:families.every(family=>family.ok),families}}export{evaluateReliabilityWindow};
2
- //# sourceMappingURL=reliability.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="14b66b71-90c1-5a6b-96cc-af2694079048")}catch{}})();export*from"./governance/gc.js";export*from"./governance/health.js";export*from"./governance/extension-host-version.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-mutation-error.js";export*from"./governance/assurance-presets.js";export*from"./governance/assurance-runtime.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/defect-recurrence-coverage.js";import{runReindex}from"./governance/reindex.js";export*from"./governance/stale-work.js";export*from"./governance/in-progress-work-health.js";export*from"./governance/storage-integrity.js";export*from"./governance/status-role-diagnostics.js";export*from"./governance/workspace-position.js";export*from"./governance/workflow-policy.js";import{runUpgrade}from"./governance/upgrade.js";export*from"./governance/validate.js";export*from"./governance/closure-timestamps.js";export*from"./governance/linked-file-report.js";export*from"./author-attribution.js";export*from"./mutation-guard.js";export*from"./governance/provenance-health.js";export*from"./governance/reliability.js";export*from"./governance/artifact-ledgers.js";export*from"./similarity.js";export*from"./history/maintenance.js";export*from"./history/attestation.js";export*from"./history/attestation-command.js";export*from"../core/history/digest.js";export{runReindex,runUpgrade};
2
- //# sourceMappingURL=governance.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="ff60bc5b-bd85-5b3c-9a55-21e7e72477ac")}catch{}})();import{createHash}from"node:crypto";import{stableStringify}from"../../core/shared/serialization.js";import{RelationshipGraph,RelationshipKindRegistry}from"../relationships.js";const RELATIONSHIP_GRAPH_SNAPSHOT_VERSION=1;function throwIfAborted(signal){signal?.throwIfAborted()}function requireText(value,field){if(typeof value!="string"||value.trim().length===0)throw new TypeError(`Relationship graph ${field} must be non-empty`);return value.trim()}function createRelationshipGraphSnapshot(graph,registry,options={}){const parsedTimestamp=Date.parse(options.createdAt??new Date().toISOString());if(!Number.isFinite(parsedTimestamp))throw new TypeError("Relationship graph createdAt must be a valid timestamp");const nodes=graph.nodes(),edges=graph.edges(),kinds=registry.list();return Object.freeze({version:RELATIONSHIP_GRAPH_SNAPSHOT_VERSION,fingerprint:createHash("sha256").update(stableStringify({nodes,edges,kinds})).digest("hex"),created_at:new Date(parsedTimestamp).toISOString(),nodes,edges,kinds})}function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function parseRelationshipGraphSnapshot(value){if(!isRecord(value))throw new TypeError("Relationship graph snapshot must be an object");if(value.version!==RELATIONSHIP_GRAPH_SNAPSHOT_VERSION)throw new TypeError(`Unsupported relationship graph snapshot version: ${String(value.version)}`);if(!Array.isArray(value.nodes)||value.nodes.some(id=>typeof id!="string"))throw new TypeError("Relationship graph snapshot nodes must be strings");if(!Array.isArray(value.edges)||!Array.isArray(value.kinds))throw new TypeError("Relationship graph snapshot edges and kinds must be arrays");if(typeof value.created_at!="string"||!Number.isFinite(Date.parse(value.created_at)))throw new TypeError("Relationship graph snapshot created_at must be valid");if(typeof value.fingerprint!="string")throw new TypeError("Relationship graph snapshot fingerprint must be a string");const registry=new RelationshipKindRegistry([]);for(const definition of value.kinds)registry.register(definition);const graph=new RelationshipGraph(value.nodes,value.edges,registry),snapshot=createRelationshipGraphSnapshot(graph,registry,{createdAt:value.created_at});if(snapshot.fingerprint!==value.fingerprint)throw new TypeError("Relationship graph snapshot fingerprint mismatch");return{snapshot,registry,graph}}async function loadRelationshipGraphAdapter(adapter,context){requireText(adapter.name,"adapter name");const workspace=requireText(context.workspace,"workspace");throwIfAborted(context.signal);const value=await adapter.read({...context,workspace});return throwIfAborted(context.signal),value===null?null:parseRelationshipGraphSnapshot(value)}async function syncRelationshipGraphAdapter(adapter,context){const workspace=requireText(context.workspace,"workspace"),validated=parseRelationshipGraphSnapshot(context.snapshot).snapshot,current=await loadRelationshipGraphAdapter(adapter,{workspace,signal:context.signal});if(current?.snapshot.fingerprint===validated.fingerprint)return{adapter:adapter.name,workspace,disposition:"current",fingerprint:validated.fingerprint,previous_fingerprint:current.snapshot.fingerprint,node_count:validated.nodes.length,edge_count:validated.edges.length};if(throwIfAborted(context.signal),await adapter.replace({workspace,signal:context.signal,snapshot:validated,expected_fingerprint:current?.snapshot.fingerprint??null}),(await loadRelationshipGraphAdapter(adapter,{workspace,signal:context.signal}))?.snapshot.fingerprint!==validated.fingerprint)throw new Error(`Relationship graph adapter "${adapter.name}" did not expose the replaced snapshot`);return{adapter:adapter.name,workspace,disposition:"written",fingerprint:validated.fingerprint,...current?{previous_fingerprint:current.snapshot.fingerprint}:{},node_count:validated.nodes.length,edge_count:validated.edges.length}}function federateRelationshipGraphSnapshots(values,options={}){const loaded=values.map(parseRelationshipGraphSnapshot),definitions=new Map;for(const entry of loaded)for(const definition of entry.snapshot.kinds){const prior=definitions.get(definition.kind);if(prior&&stableStringify(prior)!==stableStringify(definition))throw new TypeError(`Conflicting federated relationship kind: ${definition.kind}`);definitions.set(definition.kind,definition)}const registry=new RelationshipKindRegistry([...definitions.values()].sort((left,right)=>left.kind.localeCompare(right.kind))),graph=new RelationshipGraph(new Set(loaded.flatMap(entry=>[...entry.snapshot.nodes])),loaded.flatMap(entry=>[...entry.snapshot.edges]),registry);return createRelationshipGraphSnapshot(graph,registry,options)}class MemoryRelationshipGraphAdapter{name;#snapshots=new Map;constructor(name="memory"){this.name=requireText(name,"adapter name")}async read(context){throwIfAborted(context.signal);const snapshot=this.#snapshots.get(requireText(context.workspace,"workspace"));return snapshot?structuredClone(snapshot):null}async replace(context){throwIfAborted(context.signal);const workspace=requireText(context.workspace,"workspace"),current=this.#snapshots.get(workspace);if(context.expected_fingerprint!==void 0&&(current?.fingerprint??null)!==context.expected_fingerprint)throw new Error(`Relationship graph adapter conflict for ${workspace}`);this.#snapshots.set(workspace,structuredClone(parseRelationshipGraphSnapshot(context.snapshot).snapshot))}async clear(context){throwIfAborted(context.signal);const workspace=requireText(context.workspace,"workspace"),current=this.#snapshots.get(workspace);if(context.expected_fingerprint!==void 0&&(current?.fingerprint??null)!==context.expected_fingerprint)throw new Error(`Relationship graph adapter conflict for ${workspace}`);this.#snapshots.delete(workspace)}}export{MemoryRelationshipGraphAdapter,RELATIONSHIP_GRAPH_SNAPSHOT_VERSION,createRelationshipGraphSnapshot,federateRelationshipGraphSnapshots,loadRelationshipGraphAdapter,parseRelationshipGraphSnapshot,syncRelationshipGraphAdapter};
2
- //# sourceMappingURL=adapter.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="e47f9bb8-f98e-5159-9116-29c3e6fedfc3")}catch{}})();import{MemoryRelationshipGraphAdapter,createRelationshipGraphSnapshot,loadRelationshipGraphAdapter,syncRelationshipGraphAdapter}from"./adapter.js";import{RelationshipGraph,createRelationshipKindRegistry}from"../relationships.js";function positiveInteger(value,field){if(!Number.isInteger(value)||value<1)throw new TypeError(`Relationship graph ${field} must be a positive integer`);return value}function createRelationshipGraphScaleFixture(options){const nodeCount=positiveInteger(options.nodeCount,"nodeCount"),edgeStride=positiveInteger(options.edgeStride??1,"edgeStride"),topology=options.topology??"chain";if(!["chain","star","disconnected"].includes(topology))throw new TypeError(`Unsupported relationship graph topology: ${topology}`);const kind=(options.kind??"related").trim(),idPrefix=(options.idPrefix??"node").trim();if(!kind||!idPrefix)throw new TypeError("Relationship graph kind and idPrefix must be non-empty");const edgeCount=topology==="disconnected"?0:Math.floor((nodeCount-1)/edgeStride);return{node_count:nodeCount,edge_count:edgeCount,edge_basis:"fixture_generated",nodes:{*[Symbol.iterator](){for(let index=0;index<nodeCount;index+=1)yield`${idPrefix}-${index}`}},edges:{*[Symbol.iterator](){if(topology!=="disconnected")for(let index=edgeStride;index<nodeCount;index+=edgeStride)yield{source:`${idPrefix}-${topology==="star"?0:index-edgeStride}`,target:`${idPrefix}-${index}`,kind}}}}}function assertConformance(condition,message){if(!condition)throw new Error(`Relationship graph adapter conformance: ${message}`)}async function assertRelationshipGraphAdapterConformance(adapter,options={}){const workspace=options.workspace?.trim()||"pm-graph-conformance",registry=createRelationshipKindRegistry(),first=createRelationshipGraphSnapshot(new RelationshipGraph(["a","b"],[{source:"a",target:"b",kind:"related"}],registry),registry,{createdAt:"2026-01-01T00:00:00.000Z"}),second=createRelationshipGraphSnapshot(new RelationshipGraph(["a","b","c"],[{source:"a",target:"b",kind:"related"},{source:"b",target:"c",kind:"blocked_by"}],registry),registry,{createdAt:"2026-01-02T00:00:00.000Z"}),cases=[];assertConformance(await loadRelationshipGraphAdapter(adapter,{workspace})===null,"workspace must start empty"),cases.push({name:"empty-read",passed:!0});const written=await syncRelationshipGraphAdapter(adapter,{workspace,snapshot:first});assertConformance(written.disposition==="written","first sync must write"),cases.push({name:"atomic-replace",passed:!0}),(await adapter.read({workspace})).nodes.push("mutated-reader-copy"),assertConformance((await loadRelationshipGraphAdapter(adapter,{workspace}))?.snapshot.nodes.length===2,"reads must not mutate stored state"),cases.push({name:"read-isolation",passed:!0}),assertConformance((await syncRelationshipGraphAdapter(adapter,{workspace,snapshot:first})).disposition==="current","identical sync must be idempotent"),cases.push({name:"idempotent-sync",passed:!0}),await adapter.replace({workspace,snapshot:second,expected_fingerprint:first.fingerprint}),assertConformance((await loadRelationshipGraphAdapter(adapter,{workspace}))?.snapshot.fingerprint===second.fingerprint,"replacement must become visible"),cases.push({name:"replacement-visibility",passed:!0});let conflict=!1;try{await adapter.replace({workspace,snapshot:first,expected_fingerprint:first.fingerprint})}catch{conflict=!0}return assertConformance(conflict,"stale compare-and-swap must fail"),cases.push({name:"stale-cas",passed:!0}),adapter.clear&&(await adapter.clear({workspace,expected_fingerprint:second.fingerprint}),assertConformance(await loadRelationshipGraphAdapter(adapter,{workspace})===null,"clear must remove the workspace"),cases.push({name:"clear",passed:!0})),{adapter:adapter.name,workspace,cases:Object.freeze(cases),clear_supported:adapter.clear!==void 0}}function assertMemoryRelationshipGraphAdapterConformance(workspace){return assertRelationshipGraphAdapterConformance(new MemoryRelationshipGraphAdapter,workspace?{workspace}:{})}export{assertMemoryRelationshipGraphAdapterConformance,assertRelationshipGraphAdapterConformance,createRelationshipGraphScaleFixture};
2
- //# sourceMappingURL=conformance.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="58736688-35d0-545d-892e-e0ede7fedc1a")}catch{}})();export*from"./query-contracts.js";import{computeRelationshipDominators,detectRelationshipCommunities,findRedundantRelationshipEdges,forEachMatchedRelationshipEdge}from"./analytics.js";import{computeRelationshipCentrality,findRelationshipCutStructure}from"./centrality.js";import{createRelationshipGraphSnapshot,federateRelationshipGraphSnapshots,loadRelationshipGraphAdapter,MemoryRelationshipGraphAdapter,parseRelationshipGraphSnapshot,RELATIONSHIP_GRAPH_SNAPSHOT_VERSION,syncRelationshipGraphAdapter}from"./adapter.js";import{assertMemoryRelationshipGraphAdapterConformance,assertRelationshipGraphAdapterConformance,createRelationshipGraphScaleFixture}from"./conformance.js";import{analyzeRelationshipSchedule}from"./scheduling.js";import{deriveRelationshipDeadlines}from"./deadline-scheduling.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,collectDuplicateDependencyRows,collectMissingDependencyTargetIds,collectOrderingStorageContradictions,normalizeDependencyGraphTarget,resolveWorkspaceRelationshipKindRegistry}from"./assembly.js";import{auditWorkspaceRelationshipGraph,collectDuplicateRelationshipEdgeGroups,collectOrderingCycles,diffRelationshipAuditSnapshots,formatDuplicateEdgeGroup,formatOrderingStorageContradiction}from"./governance.js";import{analyzeHierarchyIntegrity,assertHierarchyMutationAllowed,collectHierarchyRelations,formatHierarchyRelation,indexHierarchyRelations}from"./hierarchy-integrity.js";import{clearDurableGraphCache,durableGraphCachePath,durableGraphCacheStatus,GRAPH_DURABLE_CACHE_MIN_ITEMS,GRAPH_DURABLE_CACHE_VERSION,graphAuditBaselinePath,loadGraphAuditBaseline,openDurableGraphCache,persistDurableGraphResult,saveGraphAuditBaseline,shouldPersistDurableGraphCache}from"./durable-cache.js";import{enumerateRelationshipPaths,hierarchyAncestors,hierarchyDescendants,orderingPredecessors,orderingSuccessors}from"./traversal.js";import{computeWorkspaceGraphFingerprint,resetWorkspaceGraphCache,workspaceGraphCache,WorkspaceGraphCache}from"./cache.js";import{planRelationshipRemediation}from"./remediation.js";import{collectNewOrderingCycleWarnings}from"./mutation-advisory.js";import{assertNonHierarchyCardinalityMutationAllowed}from"./cardinality-integrity.js";import{GRAPH_SUBCOMMAND_VALUES,parseGraphSubcommand,runGraph}from"./run.js";export{GRAPH_DURABLE_CACHE_MIN_ITEMS,GRAPH_DURABLE_CACHE_VERSION,GRAPH_SUBCOMMAND_VALUES,MemoryRelationshipGraphAdapter,RELATIONSHIP_GRAPH_SNAPSHOT_VERSION,WorkspaceGraphCache,analyzeHierarchyIntegrity,analyzeRelationshipSchedule,assembleWorkspaceRelationshipGraph,assertHierarchyMutationAllowed,assertMemoryRelationshipGraphAdapterConformance,assertNonHierarchyCardinalityMutationAllowed,assertRelationshipGraphAdapterConformance,auditWorkspaceRelationshipGraph,clearDurableGraphCache,collectDanglingDependencyReferences,collectDuplicateDependencyRows,collectDuplicateRelationshipEdgeGroups,collectHierarchyRelations,collectMissingDependencyTargetIds,collectNewOrderingCycleWarnings,collectOrderingCycles,collectOrderingStorageContradictions,computeRelationshipCentrality,computeRelationshipDominators,computeWorkspaceGraphFingerprint,createRelationshipGraphScaleFixture,createRelationshipGraphSnapshot,deriveRelationshipDeadlines,detectRelationshipCommunities,diffRelationshipAuditSnapshots,durableGraphCachePath,durableGraphCacheStatus,enumerateRelationshipPaths,federateRelationshipGraphSnapshots,findRedundantRelationshipEdges,findRelationshipCutStructure,forEachMatchedRelationshipEdge,formatDuplicateEdgeGroup,formatHierarchyRelation,formatOrderingStorageContradiction,graphAuditBaselinePath,hierarchyAncestors,hierarchyDescendants,indexHierarchyRelations,loadGraphAuditBaseline,loadRelationshipGraphAdapter,normalizeDependencyGraphTarget,openDurableGraphCache,orderingPredecessors,orderingSuccessors,parseGraphSubcommand,parseRelationshipGraphSnapshot,persistDurableGraphResult,planRelationshipRemediation,resetWorkspaceGraphCache,resolveWorkspaceRelationshipKindRegistry,runGraph,saveGraphAuditBaseline,shouldPersistDurableGraphCache,syncRelationshipGraphAdapter,workspaceGraphCache};
2
- //# sourceMappingURL=index.js.map
package/dist/sdk/graph.js DELETED
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="54beb96f-a26d-513d-b849-8d319661eb12")}catch{}})();export*from"./graph/index.js";export*from"./actionability.js";export*from"./relationships.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";
2
- //# sourceMappingURL=graph.js.map
package/dist/sdk/index.js DELETED
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d914ebc9-d578-50a5-8508-9818543bf1f3")}catch{}})();import{isItemAlreadyExistsError,isPmTokenBudgetRecovery,PM_CLI_ERROR_DETAILS_LIMITS,isPmCliErrorDetails,projectPmCliErrorDetails,projectPmCliErrorContextDetails,snapshotPmCliErrorContext}from"./errors.js";import{PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,renderPmCommandVisibilityMarkdown,resolvePmCommandCapabilityFamily,resolvePmCommandVisibilityTier}from"./agent-capability-contracts.js";export*from"./mcp/protocol.js";export*from"./mcp/executable.js";export*from"./mcp/interactions.js";export*from"./mcp/tasks.js";export*from"./mcp/subscriptions.js";export*from"./mcp/transport.js";export*from"./mcp/authorization.js";export*from"./mcp/apps.js";export*from"./mcp/skills.js";export*from"./cli-contracts/grammar-contracts.js";export*from"./agent-session-context.js";export*from"./environment/agent-environment.js";import{isErrnoError,limitAnnotationEntries,parseAnnotationTextInput,readAnnotationEntries,normalizeAnnotationTransportOptions,resolveAnnotationInput,resolveAnnotationIndex,runAnnotationCommand,wrapOwnershipConflict}from"./annotations.js";import{acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,inspectHistoryAuthorStream,parseUnknownAuthorHistoryEventCoordinates,planUnknownAuthorHistoryAcknowledgment,resolveUnknownAuthorAcknowledgmentSelector,scanHistoryAuthorAttribution}from"./author-attribution.js";import{BUILTIN_CORPUS_SHAPES,PM_CORPUS_SHAPE_SCHEMA,buildCorpusShapeItemPlan,createCorpusShapeMeasurement,defineCorpusShape,listBuiltinCorpusShapes,measureCorpusShapePlan,resolveBuiltinCorpusShape}from"./corpus-shape.js";export*from"./core-governance.js";import{createPmCliProgram}from"./cli-program.js";import{runSearchRefreshWorkerEntrypoint}from"./search-refresh-worker.js";import{PM_REPRODUCIBLE_PROCESS_ENV,createReproducibleProcessRunner,resolveReproducibleProcessEnvironment,runWithReproducibleProcessEnvironment}from"./reproducibility/process.js";import{PM_WORKSPACE_RECIPE_SCHEMA,defineWorkspaceRecipe,executeWorkspaceRecipe,runWithWorkspaceRecipe}from"./workspace-recipe.js";import{SNAPSHOT_SCHEMA,WORKSPACE_SNAPSHOT_ACTIONS,createWorkspaceSnapshot,deleteWorkspaceSnapshot,inspectWorkspaceSnapshot,listWorkspaceSnapshots,planWorkspaceSnapshotRestore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery}from"./workspace-snapshot.js";import{flushTelemetryQueue}from"./telemetry-flush.js";import{PM_HISTORY_COMMAND_ALIASES,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_RELOCATED_COMMAND_ALIASES,PM_NAMESPACED_COMMAND_ALIASES,findPmNamespacedCommand,resolvePmCommandOperation,resolvePmHistoryOperation}from"./cli-contracts.js";import{EXECUTABLE_COMMAND_ALIASES,PM_COMMAND_ALIAS_CONTRACTS,renderPmCommandAliasMigrationHint,resolvePmCommandAlias,applyBootstrapPagerPolicy,coalesceRepeatedListFlags,listAliasPluralKeys,mergeLinkedTestTwoTokenEntries,normalizeBootstrapInvocation,normalizeLegacyExtensionActionSyntax,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,stripGlobalBootstrapTokens}from"./cli-bootstrap.js";import{quoteCommandArg,quoteWindowsCommandArg,redactUrlCredentialsInText,redactUrlCredentialsInToken,renderPmCommand,resolvePmCommandScopeArgs,URL_CREDENTIAL_PLACEHOLDER}from"./command-line.js";export*from"./agent/command-recovery.js";export*from"./agent/linked-resource-recovery.js";export*from"./agent/command-suggestions.js";export*from"./agent/item-addressing.js";export*from"./agent/create-option-policy.js";import{runGc}from"./governance/gc.js";import{PM_EXACT_COVERAGE_METRICS,findCoverageDeficits}from"./governance/coverage-assurance.js";import{_testOnlyHealthCommand,runHealth}from"./governance/health.js";import{_testOnlyValidateCommand,projectValidateCounts,runValidate}from"./governance/validate.js";import{runExtension}from"./extension.js";import{inspectStaticExtensionInventory}from"./extension/static-inventory.js";import{buildExtensionInstallPlan,planExtensionDirectoryCopy}from"./extension/install-plan.js";import{resolveExtensionInstallSourceIdentity}from"./extension/source-resolution.js";import{applyStoredExtensionMigrationState,readExtensionMigrationState,resolveExtensionMigrationStatePath,runExtensionMigrateAction,runExtensionMigrations}from"./extension/migrations.js";import{findInstalledNpmPackageCandidate}from"./extension/install-sources.js";import{buildExtensionDescribeResult,renderExtensionDescribeMarkdown}from"./extension/describe.js";import{runEvent,runMeet,runRemind}from"./scheduling-shortcuts.js";import{createExtensionCommandSdk}from"./extension-command-context.js";import{isRuntimeRecord}from"./runtime-input.js";import{resolveStartTaskInProgressStatus}from"./start-task-status.js";import{auditMergeAttributeFence,buildMergeAttributePatterns,findGitWorkspaceRoot,installMergeFence,refreshMergeAttributeFenceIfInstalled,resolveMergeInstallContext,resolveProjectMergeTypeFolders,runMergeInstall}from"./merge/install.js";import{deriveSchemaEvolutionMigrationId,formatSchemaEvolutionMigrationHuman,planSchemaEvolutionMigration,runSchemaEvolutionMigration}from"./schema-migration.js";import{runWithActiveExtensions}from"./runtime.js";import{applyInvocationAuthorOverride}from"./invocation-author.js";import{describeItemRevisionChanges,isItemRevisionConflict,ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,normalizeExpectedItemHash,parseExpectHashSpecs,readItemRevision,withExpectedItemRevisions}from"./lifecycle/item-revision.js";import{admitStartWithOpenBlockers,isStartTransition,START_BLOCKED_REFUSAL_CODE,START_BLOCKER_ENFORCEMENT_DEFAULT}from"./lifecycle/start-blockers.js";import{resolveDeclaredBlockers}from"./query/declared-blockers.js";import{evaluateMutationGuard,getMutationActionContract,isMutationAction,listMutationActions,PM_MUTATION_ACTION_CONTRACTS,scanMutationSecrets,decideSecretGuardFinding,SECRET_GUARD_RULE_CATEGORIES,secretGuardRuleCategory}from"./mutation-guard.js";import{findSimilarItems,findDuplicateClusters,evaluateSimilarityGovernance,similarityAdvisoryWarnings,jaccardSimilarity,normalizeSimilarityText,prepareSimilarityText,scoreItemSimilarity,scorePreparedItemSimilarity,tokenizeSimilarityText}from"./similarity.js";import{STALE_WORK_THRESHOLD_SETTING,inspectInProgressWork,inspectStaleInProgressItems,resolveLastActivityAt,scanInProgressWork,scanStaleInProgressItems}from"./governance/stale-work.js";import{buildInProgressSweepCommands}from"./governance/in-progress-work-health.js";import{describeItemOwnershipConflict,evaluateClaimActivity,resolveItemOwnershipActivity,resolveItemOwnershipConflict}from"./ownership-source.js";import{discoverNearbyPmRoot}from"./tracker-root-discovery.js";import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"./environment/tracker-preflight.js";import{_testOnly}from"./templates.js";import{runConfig,_testOnlyConfigCommand}from"./config.js";export*from"./agent/identity-config.js";import{INIT_AGENT_GUIDANCE_MODE_VALUES,runInitAgentGuidance,_testOnly as _testOnly2}from"./init-agent-guidance.js";import{runInit,summarizeInitResult,_testOnly as _testOnly3}from"./init.js";import{PROFILE_SUBCOMMANDS,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,runProfileApply,runProfileLint,runProfileList,runProfileShow}from"./profile.js";export*from"./extension-contracts.js";import{RESERVED_ITEM_FIELD_NAMES}from"../core/extensions/item-fields.js";import{PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_RESOURCE_KINDS,collectPackageExtensionDirectories,readPmPackageManifest}from"../core/packages/manifest.js";import{ACTIVITY_FLAG_CONTRACTS,ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,DELETE_FLAG_CONTRACTS,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EVENTS_FLAG_CONTRACTS,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,LEARNINGS_FLAG_CONTRACTS,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_CORE_COMMAND_NAMES,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_ITEM_ACTION_SUBCOMMANDS,PM_DEPRECATED_TOOL_ACTIONS,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_ACTIONS,analyzePmToolActionParity,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PROFILE_FLAG_CONTRACTS,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESTORE_FLAG_CONTRACTS,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,TELEMETRY_FLAG_CONTRACTS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,verifyToolOptionCliParity,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,buildPmActionToolInputSchema,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,compactFlagAliasContracts,createPmCommandOutputBudget,definePmCommandOutputBudget,estimatePmOutputTokens,inferPmOutputBudgetClass,projectPmDiagnosticOutput,projectPmDiagnosticText,PM_GENERIC_REFUSAL_GUIDANCE,PM_RECOVERY_ECHO_FIELDS,isGenericRefusalRequired,isGenericRefusalWhy,projectLeanRecoveryPayload,withoutGenericRefusalExamples,analyzeSdkCliParameterCompleteness,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmToolAction,hasSubcommandFlagContractsForCommand,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readStringArrayFromCommanderOptions,resolvePmPositionalActionFlagContracts,resolveSubcommandFlagContractsForCommand,resolvePmCommandOutputBudget,resolvePmDiagnosticOutputBudget,resolvePmToolCustomFieldCollision,toCompletionFlagString,withFlagAliasMetadata}from"./cli-contracts.js";export*from"./compose.js";export*from"./governance/assurance.js";export*from"./governance/assurance-action.js";export*from"./governance/assurance-runtime.js";export*from"./governance/assurance-presets.js";export*from"./governance/boundary-fixtures.js";export*from"./governance/defect-recurrence.js";export*from"./governance/merge-receipt-history.js";export*from"./compile-cache.js";export*from"./environment/project-runtime-compatibility.js";export*from"./environment/source-context.js";export*from"./environment/host-environment-errors.js";export*from"./cli-contracts/command-exit-contracts.js";export*from"./context-relevance.js";export*from"./context/recency.js";export*from"./context-intent-contracts.js";export*from"./context-intent-runtime.js";export*from"./context-signal-store.js";export*from"./workspace-memory.js";export*from"./lifecycle-completion.js";export*from"./lifecycle-policy.js";export*from"./output-projection.js";export*from"./read-output-contracts.js";export*from"./read-output-rows.js";export*from"./read-output-session.js";export*from"./output-token-accounting.js";export*from"./output/fit-envelope.js";export*from"./context-packing.js";export*from"./context-usage.js";import{classifyHistoryEvent,HISTORY_EVENT_CLASSIFICATION_VERSION,MAINTENANCE_HISTORY_OPERATIONS,SUBSTANTIVE_HISTORY_OPERATIONS}from"../core/history/event-classification.js";export*from"./dependency-provenance.js";export*from"./duplicates.js";export*from"./lifecycle/reopen.js";export*from"./history-compact.js";export*from"./history-read.js";export*from"../core/history/operation-contract.js";export*from"./history/maintenance.js";import{readHistorySnapshot}from"../core/history/read.js";export*from"./history-provenance.js";export*from"./mutation-events.js";export*from"./history-redact.js";import{_testOnly as _testOnly4}from"./history-redact.js";export*from"./history-repair.js";export*from"./item-children.js";export*from"./item-schedule.js";export*from"./merge/index.js";import{runDeps}from"./dependencies.js";export*from"./graph/index.js";import{runDocs}from"./docs.js";import{runFiles,runFilesDiscover,runFilesLookup}from"./files.js";import{applyPathMigrations,applyStandaloneNote,artifactKey,assertLinkedArtifactMutationIsUnambiguous,dedupeLinkedArtifacts,ensureScope,expandAddGlobEntries,normalizeLinkedPath,parseAddEntries,parseAddGlobEntries,parseMigrateEntries,parseRemoveEntries,renameArtifactsResultKey,runLinkedArtifacts,sortLinkedArtifacts,validateLinkedPaths,projectLinkedCollectionMutation,writtenLinkedEntries}from"./linked-artifacts.js";import{LINKED_ARTIFACT_NOTE_CONFLICT_MODES,reviseLinkedNote}from"./linked-artifacts.js";export*from"./pagination.js";export*from"./query/item-filter-options.js";export*from"./query/parsers.js";export*from"./output.js";export*from"./output-contracts.js";export*from"./agent/task-transcript-contracts.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";export*from"./workspace-transaction.js";export*from"./workspace-transaction-gc.js";export*from"./item-transaction.js";export*from"./item-metadata-index.js";export*from"./structured-mutations.js";export*from"./lifecycle/structured-mutation-plan.js";export*from"./runtime-primitives.js";export*from"./error-runtime.js";export*from"./error-code-catalog.js";export*from"./generated-error-code-catalog.js";export*from"./agent/refusal-reachability.js";export*from"./agent/refusal-closure-census.js";export*from"./agent/refusal-closure.js";export*from"./agent/closed-domain-contracts.js";export*from"./agent/refusal-corpus-contracts.js";import{MERGE_SUBCOMMAND_VALUES}from"./cli-contracts.js";export*from"./agent/tracker-preflight-contracts.js";export*from"./agent/subcommand-recovery.js";export*from"./flag-invocation-contracts.js";export*from"./cli-contracts/flag-lexicon-contracts.js";export*from"./relationships.js";export*from"./actionability.js";import{runCreate}from"./lifecycle/create.js";import{runPlan}from"./lifecycle/plan.js";import{runAppend}from"./lifecycle/append.js";import{STALE_CLAIM_TAKEOVER_REFUSED_CODE,isAlreadyClaimedError,runClaim,runClaimNext,runRelease}from"./lifecycle/claim.js";import{runStartTask,runPauseTask,runCloseTask}from"./lifecycle/task-composition.js";import{runCloseMany}from"./lifecycle/close-many.js";import{runUpdateMany}from"./lifecycle/update-many.js";import{runComments}from"./comments.js";import{runNotes}from"./notes.js";import{runLearnings}from"./learnings.js";import{runUpgrade}from"./governance/upgrade.js";import{PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES}from"./lifecycle/plan.js";export*from"./define.js";import{BASELINE_ITEM_FORMAT_VERSION,BUILTIN_ITEM_TYPE_VALUES,CONFIDENCE_TEXT_VALUES,CURRENT_ITEM_FORMAT_VERSION,DEPENDENCY_KIND_VALUES,EXIT_CODE,ISSUE_SEVERITY_VALUES,ITEM_TYPE_VALUES,PM_CLI_EXPECTED_ERROR_NAME,PmCliError,PmClient,RISK_VALUES,STATUS_VALUES,acquireLock,acquireLockLease,appendHistoryEntry,canonicalDocument,classifyItemFormatVersion,clearWorkspaceContractsCache,commitImportedItem,createHistoryEntry,createPmCliExpectedError,effectiveItemFormatVersion,emptyImportedDocument,ensureTrackerInitialized,generateItemId,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getSettingsPath,getWorkspaceContracts,isPmCliExpectedError,isTimestampLiteral,listAllItemMetadata,loadCreateTemplateOptions,locateItem,normalizeItemMetadata,normalizeItemFormatVersion,normalizeItemId,normalizeRawItemId,normalizeStatusInput,nowIso,parseTags,pathExists,readBooleanOption,readCsvListOption,readFileIfExists,readLocatedItem,readRequiredString,readSettings,readStringOption,removeFileIfExists,renderCalendarMarkdown,renderCalendarToon,renderGuideMarkdown,resolveCalendarOutputFormat,resolveGuideOutputFormat,resolveItemTypeRegistry,resolveImplicitPmRoot,resolvePmRoot,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runCalendar,runCompletion,runGuide,runList,runReindex,runSearch,runTemplatesList,runTemplatesSave,runTemplatesShow,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,scanItemFormatVersions,selectImportAuthor,serializeItemDocument,splitFrontMatter,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportDeferredFields,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,writeFileAtomic,aggregate,append,claim,claimNext,close,reopen,closeTask,comments,config,context,copy,create,deleteItem,deps,docs,duplicates,extension,extensionActivate,extensionDeactivate,extensionList,files,filesDiscover,filesLookup,focus,gc,get,graph,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,init,learnings,list,listAllComplete,next,notes,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageReload,packageUninstall,pauseTask,profile,profileApply,profileLint,profileList,profileShow,release,restore,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaShow,schemaShowField,schemaShowStatus,schemaRenameField,schemaRenameType,search,startTask,stats,update,upgrade,validate}from"./runtime.js";import{extensionMigrate,packageMigrate}from"./package-migrations.js";import{CONTEXT_OUTPUT_VALUES,NEXT_OUTPUT_VALUES,PM_GITIGNORE_END,PM_GITIGNORE_START,analyzeSdkActionCoverage,ensurePmGitignore,getPmGitignoreBlock,closeItem,runAggregate,runClose,runCopy,runContext,runDelete,runFocus,runGet,runNext,runRestore,runUpdate}from"./runtime.js";import{runStats}from"./stats.js";import{readImprovementLedger,recordImprovementObservation}from"./improvement-ledger.js";import{evaluateProvenanceCoverage,projectFleetAttributionAnalytics,projectProvenanceCoverageAnalytics,readHistoryAnalyticsWindow,runFleetAttributionAnalytics,runProvenanceCoverageAnalytics}from"./history-analytics.js";import{DEFAULT_EVAL_QUERIES_RELATIVE_PATH,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,parseEvalQuerySet,runEval}from"./eval.js";import{runTelemetry,TELEMETRY_SUBCOMMANDS}from"./telemetry.js";import{classifyLinkedTestCommandSafety,classifyLinkedTestFailure,countFailureCategories,extractReferencedPmItemIdsFromCommand,resolveLinkedTestFailureExitCode,runLinkedTests,runTest,summarizeContextPreflight}from"./test/execution.js";import{assertTestMeasurementRun}from"./test/prerequisites.js";import{TEST_RUN_MEASUREMENT_LIMIT,diffTestRunMeasurements,parseTestRunMeasurements,queryTestRunMeasurementsBelow}from"./test/measurements.js";import{runTestAll}from"./test/batch.js";import{LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode}from"./test/parsers.js";import{acknowledgeLinkedTests,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,linkedTestTrustFingerprint,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch}from"./test/trust.js";import{updateLinkedTest}from"./test/update.js";import{runStartBackgroundRun,runTestRunsWorker}from"./test/runs.js";import{BUILTIN_PROFILES,listProfiles,normalizeProfileName,PROFILE_NAMES,resolveProfile}from"../core/profile/profile-presets.js";import{planProfileApplication}from"../core/profile/profile-plan.js";import{describeProfileComposition,describeProjectProfile}from"../core/profile/profile-describe.js";import{lintProjectProfile,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS}from"../core/profile/profile-lint.js";export*from"./authoring.js";export*from"./governance.js";export*from"./mcp/discovery.js";export*from"./query.js";export*from"./testing.js";import{normalizeDirectExtensionCommandOptions,resolveExtensionFlagOptionKey}from"./extension/command-options.js";export{ACTIVITY_COMMANDER_STRING_OPTION_CONTRACTS,ACTIVITY_FLAG_CONTRACTS,AGGREGATE_FLAG_CONTRACTS,APPEND_FLAG_CONTRACTS,ASSURANCE_FLAG_CONTRACTS,BASELINE_ITEM_FORMAT_VERSION,BUILTIN_CORPUS_SHAPES,BUILTIN_ITEM_TYPE_VALUES,BUILTIN_PROFILES,CALENDAR_COMMANDER_STRING_OPTION_CONTRACTS,CALENDAR_FLAG_CONTRACTS,CLAIM_FLAG_CONTRACTS,CLOSE_ACTION_OPTION_KEYS,CLOSE_FLAG_CONTRACTS,CLOSE_MANY_FLAG_CONTRACTS,CLOSE_TASK_FLAG_CONTRACTS,COMMENTS_FLAG_CONTRACTS,COMPLETION_FLAG_CONTRACTS,CONFIDENCE_TEXT_VALUES,CONFIG_FLAG_CONTRACTS,CONTEXT_COMMANDER_STRING_OPTION_CONTRACTS,CONTEXT_FLAG_CONTRACTS,CONTEXT_OUTPUT_VALUES,CONTRACTS_FLAG_CONTRACTS,COPY_FLAG_CONTRACTS,CREATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,CREATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,CREATE_COMMANDER_STRING_OPTION_CONTRACTS,CREATE_FLAG_CONTRACTS,CURRENT_ITEM_FORMAT_VERSION,DEFAULT_EVAL_QUERIES_RELATIVE_PATH,DELETE_FLAG_CONTRACTS,DEPENDENCY_KIND_VALUES,DEPS_FLAG_CONTRACTS,DOCS_FLAG_CONTRACTS,DUPLICATES_FLAG_CONTRACTS,EVAL_FLAG_CONTRACTS,EVAL_QUERY_SET_CONTRACT,EVAL_QUERY_SET_EXAMPLE,EVAL_QUERY_SET_SCHEMA_ID,EVENTS_FLAG_CONTRACTS,EVENT_FLAG_CONTRACTS,EXECUTABLE_COMMAND_ALIASES,EXIT_CODE,EXTENSION_ACTIVATE_FLAG_CONTRACTS,EXTENSION_ADOPT_ALL_FLAG_CONTRACTS,EXTENSION_ADOPT_FLAG_CONTRACTS,EXTENSION_CATALOG_FLAG_CONTRACTS,EXTENSION_DEACTIVATE_FLAG_CONTRACTS,EXTENSION_DESCRIBE_FLAG_CONTRACTS,EXTENSION_DOCTOR_FLAG_CONTRACTS,EXTENSION_EXPLORE_FLAG_CONTRACTS,EXTENSION_FLAG_CONTRACTS,EXTENSION_INIT_FLAG_CONTRACTS,EXTENSION_INSTALL_FLAG_CONTRACTS,EXTENSION_MANAGE_FLAG_CONTRACTS,EXTENSION_MIGRATE_FLAG_CONTRACTS,EXTENSION_RELOAD_FLAG_CONTRACTS,EXTENSION_SCOPE_FLAG_CONTRACTS,EXTENSION_UNINSTALL_FLAG_CONTRACTS,FILES_FLAG_CONTRACTS,FOCUS_FLAG_CONTRACTS,GC_FLAG_CONTRACTS,GET_FLAG_CONTRACTS,GLOBAL_FLAG_CONTRACTS,GRAPH_FLAG_CONTRACTS,GUIDE_FLAG_CONTRACTS,HEALTH_FLAG_CONTRACTS,HISTORY_AUTHOR_ACKNOWLEDGE_FLAG_CONTRACTS,HISTORY_COMPACT_FLAG_CONTRACTS,HISTORY_EVENT_CLASSIFICATION_VERSION,HISTORY_FLAG_CONTRACTS,HISTORY_REDACT_FLAG_CONTRACTS,HISTORY_REPAIR_FLAG_CONTRACTS,INIT_AGENT_GUIDANCE_MODE_VALUES,INIT_FLAG_CONTRACTS,INSTALL_FLAG_CONTRACTS,ISSUE_SEVERITY_VALUES,ITEM_COMPLETE_FLAG_CONTRACTS,ITEM_MUTATE_FLAG_CONTRACTS,ITEM_REOPEN_FLAG_CONTRACTS,ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,ITEM_TYPE_VALUES,LEARNINGS_FLAG_CONTRACTS,LINKED_ARTIFACT_NOTE_CONFLICT_MODES,LINKED_TEST_ENV_NAME_PATTERN,LINKED_TEST_PM_CONTEXT_MODE_VALUES,LINKED_TEST_PROTECTED_ENV_KEYS,LINKED_TEST_WORKSPACE_CONTEXT_MODE_VALUES,LIST_COMMANDER_STRING_OPTION_CONTRACTS,LIST_FILTER_FLAG_CONTRACTS,MAINTENANCE_HISTORY_OPERATIONS,MEET_FLAG_CONTRACTS,MERGE_FLAG_CONTRACTS,MERGE_SUBCOMMAND_VALUES,NEXT_COMMANDER_STRING_OPTION_CONTRACTS,NEXT_FLAG_CONTRACTS,NEXT_OUTPUT_VALUES,NOTES_FLAG_CONTRACTS,PACKAGE_FLAG_CONTRACTS,PACKAGE_INIT_FLAG_CONTRACTS,PAUSE_TASK_FLAG_CONTRACTS,PLAN_CREATE_METADATA_PARAMETER_KEYS,PLAN_FLAG_CONTRACTS,PLAN_SHOW_DEPTH_VALUES,PLAN_SUBCOMMANDS,PLAN_TEMPLATE_NAMES,PM_BULK_LIFECYCLE_COMMAND_ALIASES,PM_CLI_ERROR_DETAILS_LIMITS,PM_CLI_EXPECTED_ERROR_NAME,PM_CLI_ONLY_TOOL_ACTION_WAIVERS,PM_COMMAND_ALIAS_CONTRACTS,PM_COMMAND_CAPABILITY_CONTRACTS,PM_COMMAND_OUTPUT_BUDGET_CONTRACTS,PM_COMMAND_VISIBILITY_CONTRACTS,PM_CONTEXT_OPS_COMMAND_ALIASES,PM_CORE_COMMAND_NAMES,PM_CORPUS_SHAPE_SCHEMA,PM_DEPRECATED_TOOL_ACTIONS,PM_DIAGNOSTIC_DEGRADATION_STEPS,PM_DIAGNOSTIC_OUTPUT_BUDGET_CONTRACTS,PM_DIAGNOSTIC_OUTPUT_CLASSES,PM_DISCOVERABLE_TOOL_ACTIONS,PM_EXACT_COVERAGE_METRICS,PM_EXTENSION_CAPABILITY_CONTRACTS,PM_EXTENSION_PACKAGE_ACTION_SUBCOMMANDS,PM_EXTENSION_POLICY_MODE_CONTRACTS,PM_EXTENSION_POLICY_SURFACE_CONTRACTS,PM_EXTENSION_SANDBOX_PROFILE_CONTRACTS,PM_EXTENSION_SERVICE_NAME_CONTRACTS,PM_EXTENSION_TRUST_MODE_CONTRACTS,PM_GENERIC_REFUSAL_GUIDANCE,PM_GITIGNORE_END,PM_GITIGNORE_START,PM_HISTORY_COMMAND_ALIASES,PM_ITEM_ACTION_SUBCOMMANDS,PM_MCP_PROMPT_CONTRACTS,PM_MCP_RESOURCE_CONTRACTS,PM_MCP_TOOL_COMMAND_CONTRACTS,PM_MUTATION_ACTION_CONTRACTS,PM_NAMESPACED_COMMAND_ALIASES,PM_OUTPUT_BUDGET_CLASSES,PM_OUTPUT_DEGRADATION_STEPS,PM_PACKAGE_CONVENTIONAL_RESOURCE_ROOTS,PM_PACKAGE_ONLY_ACTION_SUBCOMMANDS,PM_PACKAGE_RESOURCE_KINDS,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA,PM_PROVIDER_TOOL_PARAMETERS_SCHEMA_VERSION,PM_RECOVERY_ECHO_FIELDS,PM_RELOCATED_COMMAND_ALIASES,PM_REPRODUCIBLE_PROCESS_ENV,PM_TOOL_ACTIONS,PM_TOOL_ACTION_PARAMETER_CONTRACTS,PM_TOOL_PARAMETERS_SCHEMA,PM_TOOL_PARAMETERS_SCHEMA_MAJOR,PM_TOOL_PARAMETERS_SCHEMA_VERSION,PM_TOOL_RESERVED_CUSTOM_FIELD_PROPERTIES,PM_WORKSPACE_RECIPE_SCHEMA,PROFILE_FLAG_CONTRACTS,PROFILE_LINT_CODES,PROFILE_LINT_DIMENSIONS,PROFILE_NAMES,PROFILE_SUBCOMMANDS,PmCliError,PmClient,REINDEX_FLAG_CONTRACTS,RELEASE_FLAG_CONTRACTS,REMIND_FLAG_CONTRACTS,RESERVED_ITEM_FIELD_NAMES,RESTORE_FLAG_CONTRACTS,RISK_VALUES,SCHEMA_FLAG_CONTRACTS,SEARCH_COMMANDER_STRING_OPTION_CONTRACTS,SEARCH_FLAG_CONTRACTS,SECRET_GUARD_RULE_CATEGORIES,SNAPSHOT_SCHEMA,STALE_CLAIM_TAKEOVER_REFUSED_CODE,STALE_WORK_THRESHOLD_SETTING,START_BLOCKED_REFUSAL_CODE,START_BLOCKER_ENFORCEMENT_DEFAULT,START_TASK_FLAG_CONTRACTS,STATS_FLAG_CONTRACTS,STATUS_VALUES,SUBCOMMAND_GLOBAL_FLAG_CONTRACTS,SUBSTANTIVE_HISTORY_OPERATIONS,TELEMETRY_FLAG_CONTRACTS,TELEMETRY_SUBCOMMANDS,TEST_ALL_FLAG_CONTRACTS,TEST_FLAG_CONTRACTS,TEST_RUNS_FLAG_CONTRACTS,TEST_RUN_MEASUREMENT_LIMIT,TOOL_ACTIVITY_OPTION_CONTRACTS,TOOL_AGGREGATE_OPTION_CONTRACTS,TOOL_BULK_MUTATION_FILTER_OPTION_CONTRACT_SOURCE,TOOL_CALENDAR_OPTION_CONTRACTS,TOOL_CLOSE_MANY_FILTER_OPTION_CONTRACTS,TOOL_CONTEXT_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACTS,TOOL_CREATE_OPTION_CONTRACT_SOURCE,TOOL_DEPS_OPTION_CONTRACTS,TOOL_GRAPH_OPTION_CONTRACTS,TOOL_LIST_FILTER_OPTION_CONTRACTS,TOOL_SEARCH_FILTER_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACTS,TOOL_SHARED_CREATE_UPDATE_OPTION_CONTRACT_SOURCE,TOOL_UPDATE_MANY_FILTER_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACTS,TOOL_UPDATE_OPTION_CONTRACT_SOURCE,UPDATE_COMMANDER_OPTION_REGISTRATION_CONTRACTS,UPDATE_COMMANDER_REPEATABLE_OPTION_CONTRACTS,UPDATE_COMMANDER_STRING_OPTION_CONTRACTS,UPDATE_FLAG_CONTRACTS,UPDATE_MANY_FLAG_CONTRACTS,UPGRADE_FLAG_CONTRACTS,URL_CREDENTIAL_PLACEHOLDER,VALIDATE_FLAG_CONTRACTS,WORKSPACE_FLAG_CONTRACTS,WORKSPACE_SNAPSHOT_ACTIONS,_testOnly4 as _testOnly,_testOnlyConfigCommand,_testOnlyHealthCommand,_testOnly3 as _testOnlyInit,_testOnly2 as _testOnlyInitAgentGuidance,_testOnly as _testOnlyTemplates,_testOnlyValidateCommand,acknowledgeLinkedTests,acknowledgeUnknownAuthorHistoryEvents,acknowledgeUnknownAuthorHistoryEventsFromTransport,acquireLock,acquireLockLease,admitStartWithOpenBlockers,aggregate,analyzePmToolActionParity,analyzeSdkActionCoverage,analyzeSdkCliParameterCompleteness,append,appendHistoryEntry,applyBootstrapPagerPolicy,applyInvocationAuthorOverride,applyPathMigrations,applyStandaloneNote,applyStoredExtensionMigrationState,artifactKey,assertInitializedTracker,assertLinkedArtifactMutationIsUnambiguous,assertReadableTrackerRoot,assertTestMeasurementRun,attachLinkedTestMutationProvenance,attachLinkedTestProvenance,auditMergeAttributeFence,buildCorpusShapeItemPlan,buildExtensionDescribeResult,buildExtensionInstallPlan,buildInProgressSweepCommands,buildMergeAttributePatterns,buildPmActionToolInputSchema,buildTrackerInitializationRecovery,canonicalDocument,claim,claimNext,classifyHistoryEvent,classifyItemFormatVersion,classifyLinkedTestCommandSafety,classifyLinkedTestFailure,clearWorkspaceContractsCache,close,closeItem,closeTask,coalesceRepeatedListFlags,collectPackageExtensionDirectories,comments,commitImportedItem,compactFlagAliasContracts,config,context,copy,countFailureCategories,create,createCorpusShapeMeasurement,createExtensionCommandSdk,createHistoryEntry,createPmCliExpectedError,createPmCliProgram,createPmCommandOutputBudget,createReproducibleProcessRunner,createWorkspaceSnapshot,decideSecretGuardFinding,dedupeLinkedArtifacts,defineCorpusShape,definePmCommandOutputBudget,defineWorkspaceRecipe,deleteItem,deleteWorkspaceSnapshot,deps,deriveSchemaEvolutionMigrationId,describeItemOwnershipConflict,describeItemRevisionChanges,describeProfileComposition,describeProjectProfile,diffTestRunMeasurements,discoverNearbyPmRoot,docs,duplicates,effectiveItemFormatVersion,emptyImportedDocument,ensurePmGitignore,ensureScope,ensureTrackerInitialized,estimatePmOutputTokens,evaluateClaimActivity,evaluateMutationGuard,evaluateProvenanceCoverage,evaluateSimilarityGovernance,executeWorkspaceRecipe,expandAddGlobEntries,extension,extensionActivate,extensionDeactivate,extensionList,extensionMigrate,extractReferencedPmItemIdsFromCommand,files,filesDiscover,filesLookup,findCoverageDeficits,findDuplicateClusters,findGitWorkspaceRoot,findInstalledNpmPackageCandidate,findPmNamespacedCommand,findSimilarItems,flushTelemetryQueue,focus,formatProfileApplyHuman,formatProfileLintHuman,formatProfileListHuman,formatProfileShowHuman,formatSchemaEvolutionMigrationHuman,gc,generateItemId,get,getActiveExtensionRegistrations,getContracts,getHistoryPath,getItemPath,getMutationActionContract,getPmGitignoreBlock,getSettingsPath,getWorkspaceContracts,graph,hasSubcommandFlagContractsForCommand,health,historyCompact,historyCompactBulk,historyRedact,historyRepair,historyRepairAll,inferPmOutputBudgetClass,init,inspectHistoryAuthorStream,inspectInProgressWork,inspectStaleInProgressItems,inspectStaticExtensionInventory,inspectWorkspaceSnapshot,installMergeFence,isAlreadyClaimedError,isErrnoError,isGenericRefusalRequired,isGenericRefusalWhy,isItemAlreadyExistsError,isItemRevisionConflict,isMutationAction,isPmCliErrorDetails,isPmCliExpectedError,isPmExtensionCapabilityContract,isPmExtensionPolicyModeContract,isPmExtensionPolicySurfaceContract,isPmExtensionServiceNameContract,isPmTokenBudgetRecovery,isPmToolAction,isRuntimeRecord,isStartTransition,isTimestampLiteral,jaccardSimilarity,learnings,limitAnnotationEntries,linkedTestTrustFingerprint,lintProjectProfile,list,listAliasPluralKeys,listAllComplete,listAllItemMetadata,listBuiltinCorpusShapes,listMutationActions,listPmCommandsForFamily,listPmCommandsForTier,listPmMcpToolsForProfile,listProfiles,listWorkspaceSnapshots,loadCreateTemplateOptions,locateItem,measureCorpusShapePlan,mergeLinkedTestTwoTokenEntries,next,normalizeAnnotationTransportOptions,normalizeBootstrapInvocation,normalizeDirectExtensionCommandOptions,normalizeExpectedItemHash,normalizeItemFormatVersion,normalizeItemId,normalizeItemMetadata,normalizeLegacyExtensionActionSyntax,normalizeLinkedPath,normalizeProfileName,normalizeRawItemId,normalizeSimilarityText,normalizeStatusInput,notes,nowIso,packageActivate,packageCatalog,packageDeactivate,packageDescribe,packageDoctor,packageInstall,packageLifecycle,packageList,packageManage,packageMigrate,packageReload,packageUninstall,parseAddEntries,parseAddGlobEntries,parseAnnotationTextInput,parseBootstrapCommandName,parseBootstrapGlobalOptions,parseBootstrapHelpRequest,parseBootstrapTypeValue,parseEvalQuerySet,parseExpectHashSpecs,parseLinkedTestAssertionEqualsMap,parseLinkedTestAssertionGteMap,parseLinkedTestBoolean,parseLinkedTestContextMode,parseLinkedTestEnvClear,parseLinkedTestEnvSet,parseLinkedTestJsonEntries,parseLinkedTestMinLines,parseLinkedTestRegexList,parseLinkedTestStringList,parseLinkedTestWorkspaceContextMode,parseMigrateEntries,parseRemoveEntries,parseTags,parseTestRunMeasurements,parseUnknownAuthorHistoryEventCoordinates,pathExists,pauseTask,planExtensionDirectoryCopy,planProfileApplication,planSchemaEvolutionMigration,planUnknownAuthorHistoryAcknowledgment,planWorkspaceSnapshotRestore,prepareSimilarityText,profile,profileApply,profileLint,profileList,profileShow,projectFleetAttributionAnalytics,projectLeanRecoveryPayload,projectLinkedCollectionMutation,projectPmCliErrorContextDetails,projectPmCliErrorDetails,projectPmDiagnosticOutput,projectPmDiagnosticText,projectProvenanceCoverageAnalytics,projectValidateCounts,queryTestRunMeasurementsBelow,quoteCommandArg,quoteWindowsCommandArg,readAnnotationEntries,readBooleanOption,readCsvListOption,readExtensionMigrationState,readFileIfExists,readFirstStringFromCommanderOptions,readFirstValueFromCommanderOptions,readHistoryAnalyticsWindow,readHistorySnapshot,readImprovementLedger,readItemRevision,readLocatedItem,readPmPackageManifest,readRequiredString,readSettings,readStringArrayFromCommanderOptions,readStringOption,recordImprovementObservation,redactUrlCredentialsInText,redactUrlCredentialsInToken,refreshMergeAttributeFenceIfInstalled,release,removeFileIfExists,renameArtifactsResultKey,renderCalendarMarkdown,renderCalendarToon,renderExtensionDescribeMarkdown,renderGuideMarkdown,renderPmCommand,renderPmCommandAliasMigrationHint,renderPmCommandVisibilityMarkdown,reopen,resolveAnnotationIndex,resolveAnnotationInput,resolveBuiltinCorpusShape,resolveCalendarOutputFormat,resolveDeclaredBlockers,resolveExtensionFlagOptionKey,resolveExtensionInstallSourceIdentity,resolveExtensionMigrationStatePath,resolveGuideOutputFormat,resolveImplicitPmRoot,resolveItemOwnershipActivity,resolveItemOwnershipConflict,resolveItemTypeRegistry,resolveLastActivityAt,resolveLinkedTestFailureExitCode,resolveLinkedTestSourceRef,resolveLinkedTestSourceWorkspaceRoot,resolveLinkedTestTrust,resolveLinkedTestTrustBatch,resolveMergeInstallContext,resolvePmCommandAlias,resolvePmCommandCapabilityFamily,resolvePmCommandOperation,resolvePmCommandOutputBudget,resolvePmCommandScopeArgs,resolvePmCommandVisibilityTier,resolvePmDiagnosticOutputBudget,resolvePmHistoryOperation,resolvePmPositionalActionFlagContracts,resolvePmRoot,resolvePmToolCustomFieldCollision,resolveProfile,resolveProjectMergeTypeFolders,resolveReproducibleProcessEnvironment,resolveRuntimeFieldRegistry,resolveRuntimeStatusRegistry,resolveStartTaskInProgressStatus,resolveSubcommandFlagContractsForCommand,resolveUnknownAuthorAcknowledgmentSelector,restore,restoreWorkspaceSnapshot,restoreWorkspaceSnapshotWithRecovery,reviseLinkedNote,runAction,runActiveOnReadHooks,runActiveOnWriteHooks,runAggregate,runAnnotationCommand,runAppend,runCalendar,runClaim,runClaimNext,runClose,runCloseMany,runCloseTask,runComments,runCompletion,runConfig,runContext,runCopy,runCreate,runDelete,runDeps,runDocs,runEval,runEvent,runExtension,runExtensionMigrateAction,runExtensionMigrations,runFiles,runFilesDiscover,runFilesLookup,runFleetAttributionAnalytics,runFocus,runGc,runGet,runGuide,runHealth,runInit,runInitAgentGuidance,runLearnings,runLinkedArtifacts,runLinkedTests,runList,runMeet,runMergeInstall,runNext,runNotes,runPauseTask,runPlan,runProfileApply,runProfileLint,runProfileList,runProfileShow,runProvenanceCoverageAnalytics,runReindex,runRelease,runRemind,runRestore,runSchemaEvolutionMigration,runSearch,runSearchRefreshWorkerEntrypoint,runStartBackgroundRun,runStartTask,runStats,runTelemetry,runTemplatesList,runTemplatesSave,runTemplatesShow,runTest,runTestAll,runTestRunsList,runTestRunsLogs,runTestRunsResume,runTestRunsStatus,runTestRunsStop,runTestRunsWorker,runUpdate,runUpdateMany,runUpgrade,runValidate,runWithActiveExtensions,runWithReproducibleProcessEnvironment,runWithWorkspaceRecipe,scanHistoryAuthorAttribution,scanInProgressWork,scanItemFormatVersions,scanMutationSecrets,scanStaleInProgressItems,schema,schemaAddField,schemaAddStatus,schemaAddType,schemaApplyPreset,schemaInferTypes,schemaList,schemaListFields,schemaRemapStatus,schemaRemoveField,schemaRemoveStatus,schemaRemoveType,schemaRenameField,schemaRenameType,schemaShow,schemaShowField,schemaShowStatus,scoreItemSimilarity,scorePreparedItemSimilarity,search,secretGuardRuleCategory,selectImportAuthor,serializeItemDocument,similarityAdvisoryWarnings,snapshotPmCliErrorContext,sortLinkedArtifacts,splitFrontMatter,startTask,stats,stripGlobalBootstrapTokens,summarizeContextPreflight,summarizeInitResult,toCompletionFlagString,toEstimatedMinutesValue,toImportBoolean,toImportConfidence,toImportDeferredFields,toImportInteger,toImportLinkedDocs,toImportLinkedFiles,toImportLinkedTests,toImportLogEntries,toImportNormalizedEnum,toImportNumberMap,toImportPriority,toImportStatus,toImportStringList,toImportStringMap,toImportTags,toNonEmptyImportString,tokenizeSimilarityText,update,updateLinkedTest,upgrade,validate,validateLinkedPaths,verifyToolOptionCliParity,withExpectedItemRevisions,withFlagAliasMetadata,withoutGenericRefusalExamples,wrapOwnershipConflict,writeFileAtomic,writtenLinkedEntries};
2
- //# sourceMappingURL=index.js.map
package/dist/sdk/query.js DELETED
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="92de6b54-8d32-5394-964c-854d01cea810")}catch{}})();export*from"./query/list.js";export*from"./query/complete-list.js";export*from"./query/search.js";import{readRecentActivity,runActivity}from"./query/activity.js";export*from"./query/aggregate.js";export*from"./query/calendar.js";import{CONTEXT_OUTPUT_VALUES,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,projectContextFocusRows,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary}from"./query/context.js";export*from"./query/get.js";export*from"./query/history.js";export*from"./query/next.js";export*from"./actionability.js";export*from"./query/search-pagination.js";export*from"./query/search-rendering.js";export*from"./query/item-filter-options.js";export*from"./query/multi-value-filters.js";export*from"./query/parsers.js";export*from"./pagination.js";export*from"./item-children.js";export*from"./item-metadata-index.js";export*from"./context-packing.js";export*from"./output/fit-envelope.js";export*from"./context-relevance.js";export*from"./context-signal-store.js";export*from"./context-usage.js";export*from"./workspace-memory.js";export*from"./duplicates.js";import{evaluateMetricFloors,parseEvalMetricFloors,EVAL_METRIC_NAMES}from"../core/search/eval-thresholds.js";import{analyzeDuplicateItems}from"./similarity.js";import{measureItemMetadataReadWork}from"../core/store/item-metadata-read-work.js";import{executeEmbeddingBatchesWithRetry}from"../core/search/embedding-batches.js";export{CONTEXT_OUTPUT_VALUES,EVAL_METRIC_NAMES,analyzeDuplicateItems,applyContextTagProjection,buildChildrenByParent,collectSubtreeIds,compareCriticalItems,evaluateMetricFloors,executeEmbeddingBatchesWithRetry,measureItemMetadataReadWork,mergeSortedWarnings,packRankedContextItems,parseContextDepth,parseContextFocusFields,parseContextSections,parseEvalMetricFloors,projectContextFocusRows,readRecentActivity,renderContextMarkdown,resolveContextOutputFormat,resolveContextTokenBudget,runActivity,runContext,toContextFocusItem,toContextPackingSummary,toContextRankingSummary};
2
- //# sourceMappingURL=query.js.map
@@ -1,2 +0,0 @@
1
- (function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7163a078-d8be-5bca-813f-c941fcb8e406")}catch{}})();import{createHash}from"node:crypto";import{assembleWorkspaceRelationshipGraph}from"./graph/assembly.js";function requiredMigrationText(value,field){if(typeof value!="string"||value.trim().length===0)throw new TypeError(`Relationship backfill ${field} must be non-empty`);return value.trim()}function planRelationshipEventBackfill(items,options){const migrationId=requiredMigrationText(options.migrationId,"migrationId"),author=requiredMigrationText(options.author,"author"),parsedTimestamp=Date.parse(options.timestamp);if(!Number.isFinite(parsedTimestamp))throw new TypeError("Relationship backfill timestamp must be valid");const timestamp=new Date(parsedTimestamp).toISOString(),assembly=assembleWorkspaceRelationshipGraph(items,void 0,options.registry),nodes=assembly.graph.nodes(),completeEvents=assembly.graph.edges().map(edge=>{const digest=createHash("sha256").update(JSON.stringify([migrationId,edge.kind,edge.source,edge.target,edge.createdAt??null,edge.author??null,edge.payload??null])).digest("hex").slice(0,24);return Object.freeze({eventId:`backfill:${migrationId}:${digest}`,relationshipId:`migration:${migrationId}:${digest}`,action:"add",edge,author,timestamp,reason:`Backfill ${migrationId} from legacy item metadata`})}),fingerprint=createHash("sha256").update(JSON.stringify({migrationId,nodes,events:completeEvents})).digest("hex"),existingEventIds=new Set([...options.existingEventIds??[]].filter(id=>typeof id=="string").map(id=>id.trim()).filter(Boolean)),events=completeEvents.filter(event=>!existingEventIds.has(event.eventId));return Object.freeze({migration_id:migrationId,fingerprint,nodes,events:Object.freeze(events),edge_count:completeEvents.length,skipped_existing_count:completeEvents.length-events.length,duplicate_dependency_rows:assembly.duplicateRows.length,dangling_reference_count:assembly.dangling.active.length+assembly.dangling.legacy_terminal.length})}export{planRelationshipEventBackfill};
2
- //# sourceMappingURL=relationship-migration.js.map