@unbrained/pm-cli 2026.11.22 → 2026.11.23

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 (892) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/dist/cli/after-command-context-usage.js +1 -1
  3. package/dist/cli/argv-utils.js +1 -1
  4. package/dist/cli/bootstrap-args.js +1 -1
  5. package/dist/cli/bundle-integrity.js +2 -2
  6. package/dist/cli/command-namespaces.js +1 -1
  7. package/dist/cli/commander-usage.js +11 -11
  8. package/dist/cli/commands/annotations/comments.js +1 -1
  9. package/dist/cli/commands/annotations/docs.js +1 -1
  10. package/dist/cli/commands/annotations/files.js +1 -1
  11. package/dist/cli/commands/annotations/learnings.js +1 -1
  12. package/dist/cli/commands/annotations/notes.js +1 -1
  13. package/dist/cli/commands/extension/describe.js +1 -1
  14. package/dist/cli/commands/extension/extension.js +1 -1
  15. package/dist/cli/commands/extension/scaffold.js +1 -1
  16. package/dist/cli/commands/extension/shared.js +1 -1
  17. package/dist/cli/commands/governance/gc.js +1 -1
  18. package/dist/cli/commands/governance/health.js +1 -1
  19. package/dist/cli/commands/governance/telemetry.js +1 -1
  20. package/dist/cli/commands/governance/validate.js +1 -1
  21. package/dist/cli/commands/history/activity.js +1 -1
  22. package/dist/cli/commands/history/history-compact.js +1 -1
  23. package/dist/cli/commands/history/history-redact.js +1 -1
  24. package/dist/cli/commands/history/history-repair.js +1 -1
  25. package/dist/cli/commands/history/history.js +1 -1
  26. package/dist/cli/commands/history/restore.js +1 -1
  27. package/dist/cli/commands/lifecycle/append.js +1 -1
  28. package/dist/cli/commands/lifecycle/claim.js +1 -1
  29. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  30. package/dist/cli/commands/lifecycle/close.js +1 -1
  31. package/dist/cli/commands/lifecycle/copy.js +1 -1
  32. package/dist/cli/commands/lifecycle/create.js +1 -1
  33. package/dist/cli/commands/lifecycle/delete.js +1 -1
  34. package/dist/cli/commands/lifecycle/focus.js +1 -1
  35. package/dist/cli/commands/lifecycle/plan.js +1 -1
  36. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  37. package/dist/cli/commands/lifecycle/update.js +1 -1
  38. package/dist/cli/commands/query/aggregate.js +1 -1
  39. package/dist/cli/commands/query/context.js +1 -1
  40. package/dist/cli/commands/query/deps.js +1 -1
  41. package/dist/cli/commands/query/duplicates.js +1 -1
  42. package/dist/cli/commands/query/eval.js +1 -1
  43. package/dist/cli/commands/query/get.js +1 -1
  44. package/dist/cli/commands/query/graph.js +1 -1
  45. package/dist/cli/commands/query/list.js +1 -1
  46. package/dist/cli/commands/query/next.js +1 -1
  47. package/dist/cli/commands/query/search.js +1 -1
  48. package/dist/cli/commands/query/stats.js +1 -1
  49. package/dist/cli/commands/test/test-all.js +1 -1
  50. package/dist/cli/commands/test/test-runs.js +1 -1
  51. package/dist/cli/commands/test/test.js +1 -1
  52. package/dist/cli/commands/workspace/config.js +1 -1
  53. package/dist/cli/commands/workspace/contracts.js +1 -1
  54. package/dist/cli/commands/workspace/init.js +1 -1
  55. package/dist/cli/commands/workspace/merge.js +1 -1
  56. package/dist/cli/commands/workspace/profile.js +1 -1
  57. package/dist/cli/commands/workspace/schema.js +1 -1
  58. package/dist/cli/commands/workspace/upgrade.js +1 -1
  59. package/dist/cli/context-intent-invocation.js +1 -1
  60. package/dist/cli/description-stdin.js +1 -1
  61. package/dist/cli/error-guidance.js +5 -5
  62. package/dist/cli/expected-revisions.js +1 -1
  63. package/dist/cli/extension-command-help.js +6 -6
  64. package/dist/cli/extension-recovery.js +1 -1
  65. package/dist/cli/help-content.js +5 -5
  66. package/dist/cli/help-json-payload.js +7 -7
  67. package/dist/cli/invocation-profile.js +2 -2
  68. package/dist/cli/main.js +5 -5
  69. package/dist/cli/migration-gates.js +1 -1
  70. package/dist/cli/option-values.js +1 -1
  71. package/dist/cli/preflight-warnings.js +3 -3
  72. package/dist/cli/public.js +1 -1
  73. package/dist/cli/register-annotations.js +1 -1
  74. package/dist/cli/register-assurance.js +1 -1
  75. package/dist/cli/register-files-lookup.js +1 -1
  76. package/dist/cli/register-history-activity.js +1 -1
  77. package/dist/cli/register-history-author.js +1 -1
  78. package/dist/cli/register-history-maintenance.js +2 -2
  79. package/dist/cli/register-list-query.js +10 -10
  80. package/dist/cli/register-mutation-options.js +0 -1
  81. package/dist/cli/register-mutation.js +6 -6
  82. package/dist/cli/register-operations.js +1 -1
  83. package/dist/cli/register-setup.js +1 -1
  84. package/dist/cli/register-structured-mutation.js +1 -1
  85. package/dist/cli/registration-helpers.js +1 -1
  86. package/dist/cli/runtime/activation.js +1 -1
  87. package/dist/cli/runtime/annotation-option-retry.js +1 -1
  88. package/dist/cli/runtime/close-fields-retry.js +1 -1
  89. package/dist/cli/runtime/field-route-retry.js +1 -1
  90. package/dist/cli/runtime/invocation-options.js +1 -1
  91. package/dist/cli/runtime/invocation-rewrites.js +1 -1
  92. package/dist/cli/runtime/projection-retry.js +1 -1
  93. package/dist/cli/runtime/read-output-mutation-retry.js +1 -1
  94. package/dist/cli/runtime/refusal-credential-redaction.js +1 -1
  95. package/dist/cli/runtime/selection.js +1 -1
  96. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  97. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  98. package/dist/cli/schema/registration.js +15 -15
  99. package/dist/cli/schema-registration-helpers.js +1 -1
  100. package/dist/cli/search-refresh.js +1 -1
  101. package/dist/cli/stats-analytics-json.js +1 -1
  102. package/dist/cli/telemetry-flush.js +1 -1
  103. package/dist/cli-bundle/bundle-manifest.json +1 -1
  104. package/dist/cli-bundle/chunks/chunk-2UQU7HRR.js +9 -0
  105. package/dist/cli-bundle/chunks/chunk-5DUP4AZA.js +2 -0
  106. package/dist/cli-bundle/chunks/chunk-5WZZ5XEN.js +3 -0
  107. package/dist/cli-bundle/chunks/chunk-6H36ZHMI.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-6MYJLOSG.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-AA52P34H.js +3 -0
  110. package/dist/cli-bundle/chunks/{chunk-B76TFRO2.js → chunk-AEOHUSUI.js} +101 -101
  111. package/dist/cli-bundle/chunks/chunk-BSRIVYTM.js +8 -0
  112. package/dist/cli-bundle/chunks/chunk-CFWLQFJM.js +71 -0
  113. package/dist/cli-bundle/chunks/chunk-D6PDUKUG.js +9 -0
  114. package/dist/cli-bundle/chunks/chunk-ENKXRSFZ.js +31 -0
  115. package/dist/cli-bundle/chunks/chunk-F2Z6XLZB.js +3 -0
  116. package/dist/cli-bundle/chunks/chunk-FJOEL75F.js +2 -0
  117. package/dist/cli-bundle/chunks/chunk-GDXCAC52.js +2 -0
  118. package/dist/cli-bundle/chunks/chunk-H7JEXRIN.js +6 -0
  119. package/dist/cli-bundle/chunks/chunk-J2PDAVBC.js +2 -0
  120. package/dist/cli-bundle/chunks/chunk-KE7HMBEW.js +2 -0
  121. package/dist/cli-bundle/chunks/chunk-KZHIBEJL.js +33 -0
  122. package/dist/cli-bundle/chunks/chunk-NGJ5ERBF.js +115 -0
  123. package/dist/cli-bundle/chunks/chunk-NQ54T7T2.js +2 -0
  124. package/dist/cli-bundle/chunks/chunk-O7JHS64G.js +3 -0
  125. package/dist/cli-bundle/chunks/chunk-OKEZF7HU.js +2 -0
  126. package/dist/cli-bundle/chunks/chunk-OKIKF4FD.js +2 -0
  127. package/dist/cli-bundle/chunks/chunk-OPJF254V.js +9 -0
  128. package/dist/cli-bundle/chunks/chunk-PZA7QECY.js +1 -0
  129. package/dist/cli-bundle/chunks/chunk-RWA5YZ5X.js +2 -0
  130. package/dist/cli-bundle/chunks/chunk-S32NGRQM.js +2 -0
  131. package/dist/cli-bundle/chunks/chunk-SLFRSZK6.js +1 -0
  132. package/dist/cli-bundle/chunks/chunk-TZY5MVJF.js +125 -0
  133. package/dist/cli-bundle/chunks/chunk-YYT3MIRF.js +3 -0
  134. package/dist/cli-bundle/chunks/chunk-ZPS4B6SI.js +8 -0
  135. package/dist/cli-bundle/chunks/context-budget-recovery-M5RFUEFG.js +2 -0
  136. package/dist/cli-bundle/chunks/indexed-receipt-blobs-BPYKN5Q7.js +4 -0
  137. package/dist/cli-bundle/chunks/{item-revision-4QBMZXKX.js → item-revision-FMD4KWBB.js} +2 -2
  138. package/dist/cli-bundle/chunks/item-transaction-SEHTH7N2.js +2 -0
  139. package/dist/cli-bundle/chunks/mutation-actor-SFGYIRPW.js +2 -0
  140. package/dist/cli-bundle/chunks/mutation-admission-57LBSKQI.js +2 -0
  141. package/dist/cli-bundle/chunks/{register-list-query-RR5KACJ3.js → register-list-query-L4IBU64P.js} +11 -11
  142. package/dist/cli-bundle/chunks/register-mutation-6NUOPHZ3.js +21 -0
  143. package/dist/cli-bundle/chunks/register-operations-JGYVORNN.js +2 -0
  144. package/dist/cli-bundle/chunks/register-setup-C44SIXEH.js +2 -0
  145. package/dist/cli-bundle/chunks/settlement-hook-6MR32OOC.js +7 -0
  146. package/dist/cli-bundle/chunks/stage-PQ7AB63N.js +2 -0
  147. package/dist/cli-bundle/focused-chunks/chunk-6LKTEKHS.js +6 -0
  148. package/dist/cli-bundle/focused-chunks/chunk-6LPXMFLM.js +2 -0
  149. package/dist/cli-bundle/focused-chunks/chunk-A6VEMCRR.js +3 -0
  150. package/dist/cli-bundle/focused-chunks/chunk-AIDL2ZNT.js +3 -0
  151. package/dist/cli-bundle/focused-chunks/chunk-BKPUUW5O.js +1 -0
  152. package/dist/cli-bundle/focused-chunks/chunk-BWOVFE5B.js +2 -0
  153. package/dist/cli-bundle/focused-chunks/chunk-HMDQDRV2.js +8 -0
  154. package/dist/cli-bundle/focused-chunks/chunk-I66IKYKP.js +2 -0
  155. package/dist/cli-bundle/focused-chunks/chunk-IIP6LZ5E.js +2 -0
  156. package/dist/cli-bundle/focused-chunks/chunk-IR2J3NOT.js +2 -0
  157. package/dist/cli-bundle/focused-chunks/chunk-IROZDIDX.js +3 -0
  158. package/dist/cli-bundle/focused-chunks/chunk-ITKDHSBR.js +2 -0
  159. package/dist/cli-bundle/focused-chunks/chunk-K53OIT5J.js +2 -0
  160. package/dist/cli-bundle/focused-chunks/chunk-LQYYPXUK.js +26 -0
  161. package/dist/cli-bundle/focused-chunks/chunk-NQTEE66P.js +13 -0
  162. package/dist/cli-bundle/focused-chunks/chunk-O7Z73ALG.js +2 -0
  163. package/dist/cli-bundle/focused-chunks/chunk-OTMMOKPM.js +91 -0
  164. package/dist/cli-bundle/focused-chunks/chunk-OXOCZJC6.js +2 -0
  165. package/dist/cli-bundle/focused-chunks/chunk-QLAHEDT6.js +2 -0
  166. package/dist/cli-bundle/focused-chunks/chunk-QQIIMMFU.js +2 -0
  167. package/dist/cli-bundle/focused-chunks/chunk-RIE3SJSE.js +9 -0
  168. package/dist/cli-bundle/focused-chunks/chunk-TD544C74.js +8 -0
  169. package/dist/cli-bundle/focused-chunks/chunk-UFTUNBMY.js +27 -0
  170. package/dist/cli-bundle/focused-chunks/chunk-X6CXWWNB.js +2 -0
  171. package/dist/cli-bundle/focused-chunks/chunk-XRS3VNC6.js +44 -0
  172. package/dist/cli-bundle/focused-chunks/chunk-XYPEZGTR.js +2 -0
  173. package/dist/cli-bundle/focused-chunks/chunk-Y2ESLKCF.js +8 -0
  174. package/dist/cli-bundle/focused-chunks/chunk-YSJKQLFR.js +2 -0
  175. package/dist/cli-bundle/focused-chunks/chunk-Z2X7HH3C.js +102 -0
  176. package/dist/cli-bundle/focused-chunks/chunk-ZHWPCVQL.js +78 -0
  177. package/dist/cli-bundle/focused-chunks/context-budget-recovery-CSJV3TY3.js +2 -0
  178. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-EGEJMG3G.js +4 -0
  179. package/dist/cli-bundle/focused-chunks/{item-revision-2O6MLPEX.js → item-revision-YDACCDVY.js} +2 -2
  180. package/dist/cli-bundle/focused-chunks/item-transaction-UKEQCTKB.js +2 -0
  181. package/dist/cli-bundle/focused-chunks/mutation-actor-AS465LRX.js +2 -0
  182. package/dist/cli-bundle/focused-chunks/mutation-admission-E5UHJZFE.js +2 -0
  183. package/dist/cli-bundle/focused-chunks/settlement-hook-FMLGKG7J.js +7 -0
  184. package/dist/cli-bundle/focused-chunks/stage-36J7YLGI.js +2 -0
  185. package/dist/cli-bundle/main.js +27 -27
  186. package/dist/cli-bundle/sdk-authoring.js +1 -1
  187. package/dist/cli-bundle/sdk-contracts.js +5 -5
  188. package/dist/cli-bundle/sdk-core.js +1 -1
  189. package/dist/cli-bundle/sdk-governance.js +1 -1
  190. package/dist/cli-bundle/sdk-graph.js +1 -1
  191. package/dist/cli-bundle/sdk-merge.js +66 -66
  192. package/dist/cli-bundle/sdk-query.js +1 -1
  193. package/dist/cli-bundle/sdk-runtime.js +1 -1
  194. package/dist/cli-bundle/sdk-testing.js +1 -1
  195. package/dist/cli-bundle/sdk.js +12 -12
  196. package/dist/cli.js +1 -1
  197. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  198. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  199. package/dist/core/checkpoint/mutation-context.js +1 -1
  200. package/dist/core/config/nested-settings.js +1 -1
  201. package/dist/core/config/positional-value.js +1 -1
  202. package/dist/core/diagnostics/remediation.js +1 -1
  203. package/dist/core/extensions/activation-summary-markdown.js +2 -2
  204. package/dist/core/extensions/activation-summary.js +1 -1
  205. package/dist/core/extensions/activation-transaction.js +1 -1
  206. package/dist/core/extensions/capability-usage.js +1 -1
  207. package/dist/core/extensions/command-hook-context.js +1 -1
  208. package/dist/core/extensions/command-metadata-contract.js +1 -1
  209. package/dist/core/extensions/command-visibility-tier.js +1 -1
  210. package/dist/core/extensions/contribution-inventory.js +1 -1
  211. package/dist/core/extensions/exporter-output-contract.js +1 -1
  212. package/dist/core/extensions/extension-candidate.js +1 -1
  213. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  214. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  215. package/dist/core/extensions/extension-policy.js +1 -1
  216. package/dist/core/extensions/extension-registries.js +1 -1
  217. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  218. package/dist/core/extensions/extension-types.js +1 -1
  219. package/dist/core/extensions/flag-definition-validation.js +1 -1
  220. package/dist/core/extensions/flag-value-types.js +1 -1
  221. package/dist/core/extensions/index.js +1 -1
  222. package/dist/core/extensions/item-field-types.js +1 -1
  223. package/dist/core/extensions/item-fields.js +1 -1
  224. package/dist/core/extensions/loader.js +1 -1
  225. package/dist/core/extensions/manifest-parser.js +1 -1
  226. package/dist/core/extensions/manifest-schema.js +1 -1
  227. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  228. package/dist/core/extensions/mutation-actor-snapshot.js +1 -1
  229. package/dist/core/extensions/mutation-actor.js +1 -1
  230. package/dist/core/extensions/preflight-ownership.js +1 -1
  231. package/dist/core/extensions/read-output-contract.js +1 -1
  232. package/dist/core/extensions/registration-contracts.js +1 -1
  233. package/dist/core/extensions/registration-validation.js +1 -1
  234. package/dist/core/extensions/registration-values.js +1 -1
  235. package/dist/core/extensions/reserved-host-flags.js +1 -1
  236. package/dist/core/extensions/runtime-registrations.js +1 -1
  237. package/dist/core/extensions/service-ownership.js +1 -1
  238. package/dist/core/extensions/version-compat.js +1 -1
  239. package/dist/core/extensions/version-diagnostics.js +1 -1
  240. package/dist/core/fs/atomic-create.js +1 -1
  241. package/dist/core/fs/file-glob.js +1 -1
  242. package/dist/core/fs/fs-utils.js +2 -2
  243. package/dist/core/fs/host-environment-errors.js +1 -1
  244. package/dist/core/fs/index.js +1 -1
  245. package/dist/core/fs/path-utils.js +1 -1
  246. package/dist/core/governance/content-fields.js +1 -1
  247. package/dist/core/governance/issue-codes.js +1 -1
  248. package/dist/core/governance/metadata-coverage.js +1 -1
  249. package/dist/core/history/bridge.js +1 -1
  250. package/dist/core/history/digest.js +1 -1
  251. package/dist/core/history/drift-cache.js +3 -3
  252. package/dist/core/history/drift-scan.js +1 -1
  253. package/dist/core/history/event-classification.js +1 -1
  254. package/dist/core/history/event-index.js +11 -11
  255. package/dist/core/history/history-compact-bulk.js +1 -1
  256. package/dist/core/history/history-diff.js +1 -1
  257. package/dist/core/history/history-rewrite.js +1 -1
  258. package/dist/core/history/history-storage-stats.js +1 -1
  259. package/dist/core/history/history-stream-policy.js +1 -1
  260. package/dist/core/history/history.js +2 -2
  261. package/dist/core/history/identity.js +1 -1
  262. package/dist/core/history/index.js +1 -1
  263. package/dist/core/history/operation-contract.js +1 -1
  264. package/dist/core/history/projection.js +1 -1
  265. package/dist/core/history/read.js +1 -1
  266. package/dist/core/history/replay.js +2 -2
  267. package/dist/core/history/stream-summary.js +2 -2
  268. package/dist/core/history/tombstone.js +1 -1
  269. package/dist/core/history/version-address.js +1 -1
  270. package/dist/core/history/workspace-history.js +2 -2
  271. package/dist/core/io/body-file.js +1 -1
  272. package/dist/core/io/bulk-ids-input.js +2 -2
  273. package/dist/core/item/actionability.js +1 -1
  274. package/dist/core/item/deferred-fields.js +1 -1
  275. package/dist/core/item/dependency-reference.js +1 -1
  276. package/dist/core/item/id.js +1 -1
  277. package/dist/core/item/index.js +1 -1
  278. package/dist/core/item/item-format-version.js +1 -1
  279. package/dist/core/item/item-format.js +7 -7
  280. package/dist/core/item/item-record.js +1 -1
  281. package/dist/core/item/item-type-definition.js +1 -1
  282. package/dist/core/item/literal-mutation-input.js +1 -1
  283. package/dist/core/item/parent-reference-policy.js +1 -1
  284. package/dist/core/item/parse.js +8 -8
  285. package/dist/core/item/plan-lifecycle.js +1 -1
  286. package/dist/core/item/priority.js +1 -1
  287. package/dist/core/item/sprint-release-format.js +1 -1
  288. package/dist/core/item/status-filter.js +1 -1
  289. package/dist/core/item/status.js +1 -1
  290. package/dist/core/item/toon-decode.js +1 -1
  291. package/dist/core/item/type-registry.js +1 -1
  292. package/dist/core/item/type-synonyms.js +1 -1
  293. package/dist/core/lock/index.js +1 -1
  294. package/dist/core/lock/lock-confinement.js +1 -1
  295. package/dist/core/lock/lock-gc.js +1 -1
  296. package/dist/core/lock/lock-owner.js +1 -1
  297. package/dist/core/lock/lock.js +4 -4
  298. package/dist/core/output/linked-test-projection.js +5 -5
  299. package/dist/core/output/mutation-projection.js +1 -1
  300. package/dist/core/output/output-control.js +1 -1
  301. package/dist/core/output/output.js +19 -19
  302. package/dist/core/output/query-summary.js +1 -1
  303. package/dist/core/output/tabular.js +3 -3
  304. package/dist/core/packages/manifest.js +1 -1
  305. package/dist/core/packages/root.js +1 -1
  306. package/dist/core/policy/workflow-policy-schema.js +1 -1
  307. package/dist/core/policy/workflow-policy-store.js +1 -1
  308. package/dist/core/policy/workflow-policy.js +1 -1
  309. package/dist/core/profile/profile-describe.js +1 -1
  310. package/dist/core/profile/profile-lint.d.ts +1 -1
  311. package/dist/core/profile/profile-lint.js +1 -1
  312. package/dist/core/profile/profile-plan.js +1 -1
  313. package/dist/core/profile/profile-presets.js +4 -4
  314. package/dist/core/reproducibility/context.js +1 -1
  315. package/dist/core/schema/fields-file.js +2 -2
  316. package/dist/core/schema/item-types-file.js +2 -2
  317. package/dist/core/schema/runtime-field-filters.js +1 -1
  318. package/dist/core/schema/runtime-field-values.js +1 -1
  319. package/dist/core/schema/runtime-schema.js +2 -2
  320. package/dist/core/schema/status-defs-file.js +2 -2
  321. package/dist/core/schema/status-token.js +1 -1
  322. package/dist/core/schema/type-inference.js +1 -1
  323. package/dist/core/schema/type-presets.js +1 -1
  324. package/dist/core/schema/type-workflows.js +1 -1
  325. package/dist/core/search/background-refresh.js +2 -2
  326. package/dist/core/search/bm25.js +1 -1
  327. package/dist/core/search/cache.js +2 -2
  328. package/dist/core/search/corpus.js +1 -1
  329. package/dist/core/search/embedding-batches.js +1 -1
  330. package/dist/core/search/eval-thresholds.js +1 -1
  331. package/dist/core/search/eval.js +1 -1
  332. package/dist/core/search/http-client.js +1 -1
  333. package/dist/core/search/providers.js +1 -1
  334. package/dist/core/search/relevance.js +1 -1
  335. package/dist/core/search/semantic-defaults.js +1 -1
  336. package/dist/core/search/staleness.js +1 -1
  337. package/dist/core/search/vector-stores.js +2 -2
  338. package/dist/core/search/vectorization-metadata.js +1 -1
  339. package/dist/core/sentry/helpers.js +1 -1
  340. package/dist/core/sentry/instrument.js +1 -1
  341. package/dist/core/sentry/sensitive-assignments.js +1 -1
  342. package/dist/core/session/session-state.js +1 -1
  343. package/dist/core/shared/agent-session-context.js +1 -1
  344. package/dist/core/shared/author.js +5 -5
  345. package/dist/core/shared/command-line.js +1 -1
  346. package/dist/core/shared/command-types.js +0 -1
  347. package/dist/core/shared/conflict-markers.js +1 -1
  348. package/dist/core/shared/constants.js +1 -1
  349. package/dist/core/shared/error-details.js +1 -1
  350. package/dist/core/shared/errors.js +1 -1
  351. package/dist/core/shared/html-entity-decode.js +1 -1
  352. package/dist/core/shared/index.js +1 -1
  353. package/dist/core/shared/item-metadata-contract.js +1 -1
  354. package/dist/core/shared/lazy-module.js +1 -1
  355. package/dist/core/shared/levenshtein.js +1 -1
  356. package/dist/core/shared/memo.js +1 -1
  357. package/dist/core/shared/numeric-parsers.js +1 -1
  358. package/dist/core/shared/option-alias-visibility.js +1 -1
  359. package/dist/core/shared/output-unicode.js +1 -1
  360. package/dist/core/shared/primitives.js +1 -1
  361. package/dist/core/shared/process-tree.js +2 -2
  362. package/dist/core/shared/secret-rules.js +5 -5
  363. package/dist/core/shared/serial-queue.js +1 -1
  364. package/dist/core/shared/serialization.js +1 -1
  365. package/dist/core/shared/split-comma-list.js +1 -1
  366. package/dist/core/shared/text-normalization.js +1 -1
  367. package/dist/core/shared/time.js +2 -2
  368. package/dist/core/shared/url-credentials.js +1 -1
  369. package/dist/core/store/index.js +1 -1
  370. package/dist/core/store/item-format-migration.js +1 -1
  371. package/dist/core/store/item-metadata-cache.js +1 -1
  372. package/dist/core/store/item-metadata-query-index.js +11 -11
  373. package/dist/core/store/item-metadata-read-work.js +1 -1
  374. package/dist/core/store/item-mutation-precondition.js +1 -1
  375. package/dist/core/store/item-store.js +1 -1
  376. package/dist/core/store/paths.js +1 -1
  377. package/dist/core/store/settings-concurrency.js +1 -1
  378. package/dist/core/store/settings-read-cache.js +1 -1
  379. package/dist/core/store/settings-sections.js +2 -2
  380. package/dist/core/store/settings-validator.js +1 -1
  381. package/dist/core/store/settings.d.ts +3 -1
  382. package/dist/core/store/settings.js +6 -6
  383. package/dist/core/store/sqlite-runtime.js +1 -1
  384. package/dist/core/store/tracker-preflight.js +1 -1
  385. package/dist/core/store/transaction-coordinator-scope.js +1 -1
  386. package/dist/core/telemetry/consent.js +3 -3
  387. package/dist/core/telemetry/observability.js +1 -1
  388. package/dist/core/telemetry/policy.js +1 -1
  389. package/dist/core/telemetry/read-sampling.js +2 -2
  390. package/dist/core/telemetry/runtime.js +9 -9
  391. package/dist/core/test/background-runs.js +4 -4
  392. package/dist/core/test/item-test-run-tracking.js +1 -1
  393. package/dist/core/test/run-selectors.js +1 -1
  394. package/dist/core/validate/estimate-defaults.js +1 -1
  395. package/dist/core/validate/fix-planning.js +1 -1
  396. package/dist/core/validate/linked-artifact-reference.js +1 -1
  397. package/dist/core/validate/missing-by-type.js +1 -1
  398. package/dist/core/validate/missing-link-owners.js +1 -1
  399. package/dist/core/validate/stale-file-classification.js +1 -1
  400. package/dist/mcp/http-server.js +5 -5
  401. package/dist/mcp/legacy-adapter.js +1 -1
  402. package/dist/mcp/runtime-capabilities.js +1 -1
  403. package/dist/mcp/server.js +4 -4
  404. package/dist/mcp/tool-definitions.js +1 -1
  405. package/dist/sdk/actionability.js +1 -1
  406. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  407. package/dist/sdk/agent/command-recovery.js +1 -1
  408. package/dist/sdk/agent/command-suggestions.js +1 -1
  409. package/dist/sdk/agent/create-option-policy.js +1 -1
  410. package/dist/sdk/agent/identity-config.js +1 -1
  411. package/dist/sdk/agent/item-addressing.js +1 -1
  412. package/dist/sdk/agent/linked-resource-recovery.js +1 -1
  413. package/dist/sdk/agent/refusal-closure-census.js +2 -2
  414. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  415. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  416. package/dist/sdk/agent-capability-contracts.js +3 -3
  417. package/dist/sdk/agent-session-context.js +1 -1
  418. package/dist/sdk/annotations.js +1 -1
  419. package/dist/sdk/author-attribution.js +1 -1
  420. package/dist/sdk/cli-bootstrap.js +1 -1
  421. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -5
  422. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  423. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  424. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  425. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  426. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  427. package/dist/sdk/cli-contracts/completeness.js +1 -1
  428. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  429. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  430. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -2
  431. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  432. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  433. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  434. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  435. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  436. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  437. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  438. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  439. package/dist/sdk/cli-contracts/typed-action-inputs.js +0 -1
  440. package/dist/sdk/cli-contracts.js +1 -1
  441. package/dist/sdk/cli-program.js +1 -1
  442. package/dist/sdk/command-line.js +1 -1
  443. package/dist/sdk/comments.js +1 -1
  444. package/dist/sdk/compile-cache.js +1 -1
  445. package/dist/sdk/completion/bash.js +2 -2
  446. package/dist/sdk/completion/fish.js +72 -72
  447. package/dist/sdk/completion/shared.js +1 -1
  448. package/dist/sdk/completion/zsh.js +75 -75
  449. package/dist/sdk/completion.js +1 -1
  450. package/dist/sdk/config.js +1 -1
  451. package/dist/sdk/context/recency.js +1 -1
  452. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  453. package/dist/sdk/context/usage-egress.js +1 -1
  454. package/dist/sdk/context/usage-ledger.js +6 -6
  455. package/dist/sdk/context-intent-contracts.js +1 -1
  456. package/dist/sdk/context-intent-runtime.js +1 -1
  457. package/dist/sdk/context-packing.js +1 -1
  458. package/dist/sdk/context-relevance.js +1 -1
  459. package/dist/sdk/context-signal-store.js +2 -2
  460. package/dist/sdk/context-usage.js +1 -1
  461. package/dist/sdk/dependencies/context-budget-recovery.js +1 -1
  462. package/dist/sdk/dependencies.js +1 -1
  463. package/dist/sdk/dependency-flag-validation.js +1 -1
  464. package/dist/sdk/dependency-provenance.js +1 -1
  465. package/dist/sdk/docs.js +1 -1
  466. package/dist/sdk/duplicates.js +1 -1
  467. package/dist/sdk/environment/host-environment-errors.js +1 -1
  468. package/dist/sdk/environment/project-runtime-compatibility.js +2 -2
  469. package/dist/sdk/environment/source-context.js +1 -1
  470. package/dist/sdk/environment/tracker-preflight.js +1 -1
  471. package/dist/sdk/error-code-catalog.js +1 -1
  472. package/dist/sdk/error-runtime.js +1 -1
  473. package/dist/sdk/errors.js +1 -1
  474. package/dist/sdk/eval.js +1 -1
  475. package/dist/sdk/extension/author-manifest.js +1 -1
  476. package/dist/sdk/extension/bundled-catalog.js +1 -1
  477. package/dist/sdk/extension/command-options.js +1 -1
  478. package/dist/sdk/extension/concurrency.js +1 -1
  479. package/dist/sdk/extension/copy-scope.js +1 -1
  480. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  481. package/dist/sdk/extension/describe.js +3 -3
  482. package/dist/sdk/extension/doctor.js +1 -1
  483. package/dist/sdk/extension/install-plan.js +1 -1
  484. package/dist/sdk/extension/install-receipts.js +1 -1
  485. package/dist/sdk/extension/install-runtime.js +3 -3
  486. package/dist/sdk/extension/install-snapshot.js +1 -1
  487. package/dist/sdk/extension/install-sources.js +5 -5
  488. package/dist/sdk/extension/managed-state.js +2 -2
  489. package/dist/sdk/extension/managed-update-status.js +1 -1
  490. package/dist/sdk/extension/migrations.js +2 -2
  491. package/dist/sdk/extension/native-command-options.js +1 -1
  492. package/dist/sdk/extension/output-ownership.js +1 -1
  493. package/dist/sdk/extension/runtime-summary.js +1 -1
  494. package/dist/sdk/extension/scaffold.js +11 -11
  495. package/dist/sdk/extension/shared.js +1 -1
  496. package/dist/sdk/extension/source-resolution.js +1 -1
  497. package/dist/sdk/extension/static-inventory.js +1 -1
  498. package/dist/sdk/extension/update-check.js +1 -1
  499. package/dist/sdk/extension-command-context.js +2 -2
  500. package/dist/sdk/extension-contracts.js +1 -1
  501. package/dist/sdk/extension.js +1 -1
  502. package/dist/sdk/files.js +1 -1
  503. package/dist/sdk/flag-invocation-contracts.js +1 -1
  504. package/dist/sdk/generated/error-code-catalog-rows.js +1 -1
  505. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  506. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  507. package/dist/sdk/generated-error-code-catalog.js +1 -1
  508. package/dist/sdk/governance/assurance-action-contracts.js +0 -1
  509. package/dist/sdk/governance/assurance-action.js +1 -1
  510. package/dist/sdk/governance/assurance-limits.js +1 -1
  511. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  512. package/dist/sdk/governance/assurance-presets.js +1 -1
  513. package/dist/sdk/governance/assurance-runtime.js +1 -1
  514. package/dist/sdk/governance/assurance.js +4 -4
  515. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  516. package/dist/sdk/governance/closure-timestamps.js +1 -1
  517. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  518. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  519. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  520. package/dist/sdk/governance/defect-recurrence.js +2 -2
  521. package/dist/sdk/governance/extension-host-version.js +1 -1
  522. package/dist/sdk/governance/gc.js +1 -1
  523. package/dist/sdk/governance/health/history-drift-remedies.js +1 -1
  524. package/dist/sdk/governance/health/projection.js +1 -1
  525. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  526. package/dist/sdk/governance/health.js +2 -2
  527. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  528. package/dist/sdk/governance/in-progress-work-health.js +1 -1
  529. package/dist/sdk/governance/lifecycle-dependency-cycles.js +1 -1
  530. package/dist/sdk/governance/linked-file-report.js +1 -1
  531. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  532. package/dist/sdk/governance/provenance-health.js +4 -4
  533. package/dist/sdk/governance/reindex.js +5 -5
  534. package/dist/sdk/governance/stale-work.js +1 -1
  535. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  536. package/dist/sdk/governance/storage-integrity.js +1 -1
  537. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  538. package/dist/sdk/governance/upgrade.js +2 -2
  539. package/dist/sdk/governance/validate-deferred-fields.js +1 -1
  540. package/dist/sdk/governance/validate-history-drift.js +1 -1
  541. package/dist/sdk/governance/validate-item-reader.js +1 -1
  542. package/dist/sdk/governance/validate-normalization.js +1 -1
  543. package/dist/sdk/governance/validate.js +1 -1
  544. package/dist/sdk/governance/workflow-completeness.js +1 -1
  545. package/dist/sdk/governance/workflow-policy.js +3 -3
  546. package/dist/sdk/governance/workspace-position.js +2 -2
  547. package/dist/sdk/graph/analytics.js +1 -1
  548. package/dist/sdk/graph/assembly.js +1 -1
  549. package/dist/sdk/graph/cache.js +1 -1
  550. package/dist/sdk/graph/cardinality-integrity.js +1 -1
  551. package/dist/sdk/graph/centrality.js +1 -1
  552. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  553. package/dist/sdk/graph/durable-cache.js +1 -1
  554. package/dist/sdk/graph/governance-contracts.js +1 -1
  555. package/dist/sdk/graph/governance.js +1 -1
  556. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  557. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  558. package/dist/sdk/graph/mutation-advisory.js +1 -1
  559. package/dist/sdk/graph/query-contracts.js +1 -1
  560. package/dist/sdk/graph/remediation.js +1 -1
  561. package/dist/sdk/graph/run.js +1 -1
  562. package/dist/sdk/graph/scheduling.js +1 -1
  563. package/dist/sdk/graph/traversal.js +1 -1
  564. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  565. package/dist/sdk/guide-topics.js +1 -1
  566. package/dist/sdk/guide.js +7 -7
  567. package/dist/sdk/history/append-only-repair.js +4 -4
  568. package/dist/sdk/history/attestation-command.js +2 -2
  569. package/dist/sdk/history/attestation-contract.js +1 -1
  570. package/dist/sdk/history/attestation-scan.js +1 -1
  571. package/dist/sdk/history/attestation.js +1 -1
  572. package/dist/sdk/history/maintenance.js +1 -1
  573. package/dist/sdk/history/reanchor-refusal.js +1 -1
  574. package/dist/sdk/history/reseed.js +1 -1
  575. package/dist/sdk/history/salvage.js +5 -5
  576. package/dist/sdk/history/subject.js +1 -1
  577. package/dist/sdk/history-analytics.js +1 -1
  578. package/dist/sdk/history-compact.js +1 -1
  579. package/dist/sdk/history-mcp.js +1 -1
  580. package/dist/sdk/history-provenance.js +1 -1
  581. package/dist/sdk/history-read.js +1 -1
  582. package/dist/sdk/history-redact.js +1 -1
  583. package/dist/sdk/history-repair.js +1 -1
  584. package/dist/sdk/improvement-ledger-validation.js +1 -1
  585. package/dist/sdk/improvement-ledger.js +2 -2
  586. package/dist/sdk/init-agent-guidance.js +10 -10
  587. package/dist/sdk/init.js +14 -14
  588. package/dist/sdk/invocation-author.js +1 -1
  589. package/dist/sdk/item-children.js +1 -1
  590. package/dist/sdk/item-metadata-index.js +1 -1
  591. package/dist/sdk/item-schedule.js +1 -1
  592. package/dist/sdk/item-transaction.js +1 -1
  593. package/dist/sdk/learnings.js +1 -1
  594. package/dist/sdk/lifecycle/append.js +3 -3
  595. package/dist/sdk/lifecycle/checkpoint-rollback.js +1 -1
  596. package/dist/sdk/lifecycle/claim.js +1 -1
  597. package/dist/sdk/lifecycle/cli-input.js +1 -1
  598. package/dist/sdk/lifecycle/close-many.js +1 -1
  599. package/dist/sdk/lifecycle/close.js +1 -1
  600. package/dist/sdk/lifecycle/copy.js +1 -1
  601. package/dist/sdk/lifecycle/core-field-recovery.js +1 -1
  602. package/dist/sdk/lifecycle/core-item-fields.js +1 -1
  603. package/dist/sdk/lifecycle/create-deferrals.js +1 -1
  604. package/dist/sdk/lifecycle/create.js +1 -1
  605. package/dist/sdk/lifecycle/delete.js +1 -1
  606. package/dist/sdk/lifecycle/dependency-removal.js +1 -1
  607. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  608. package/dist/sdk/lifecycle/focus.js +1 -1
  609. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  610. package/dist/sdk/lifecycle/item-revision.js +1 -1
  611. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  612. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  613. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  614. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  615. package/dist/sdk/lifecycle/mutation-command-options.js +0 -1
  616. package/dist/sdk/lifecycle/mutation-facet-contracts.js +1 -1
  617. package/dist/sdk/lifecycle/mutation-option-validation.js +1 -1
  618. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  619. package/dist/sdk/lifecycle/plan.js +1 -1
  620. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  621. package/dist/sdk/lifecycle/release-handoff.js +1 -1
  622. package/dist/sdk/lifecycle/reopen.js +1 -1
  623. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -2
  624. package/dist/sdk/lifecycle/repeated-terminal-state.js +1 -1
  625. package/dist/sdk/lifecycle/restore.js +1 -1
  626. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  627. package/dist/sdk/lifecycle/start-blockers.js +1 -1
  628. package/dist/sdk/lifecycle/structured-mutation-plan.js +1 -1
  629. package/dist/sdk/lifecycle/task-composition.js +1 -1
  630. package/dist/sdk/lifecycle/update-many.js +1 -1
  631. package/dist/sdk/lifecycle/update.js +2 -2
  632. package/dist/sdk/lifecycle/workflow-transition.js +1 -1
  633. package/dist/sdk/lifecycle-completion.js +1 -1
  634. package/dist/sdk/lifecycle-policy.js +1 -1
  635. package/dist/sdk/linked-artifacts.js +2 -2
  636. package/dist/sdk/mcp/apps.js +5 -5
  637. package/dist/sdk/mcp/authorization.js +1 -1
  638. package/dist/sdk/mcp/discovery.js +1 -1
  639. package/dist/sdk/mcp/executable.js +4 -4
  640. package/dist/sdk/mcp/interactions.js +1 -1
  641. package/dist/sdk/mcp/protocol.js +1 -1
  642. package/dist/sdk/mcp/skills.js +3 -3
  643. package/dist/sdk/mcp/subscriptions.js +1 -1
  644. package/dist/sdk/mcp/tasks.js +2 -2
  645. package/dist/sdk/mcp/transport.js +1 -1
  646. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  647. package/dist/sdk/merge/driver.js +7 -7
  648. package/dist/sdk/merge/history-scalar-rebase.js +1 -1
  649. package/dist/sdk/merge/ignored-artifacts.js +1 -1
  650. package/dist/sdk/merge/index.js +1 -1
  651. package/dist/sdk/merge/indexed-receipt-blobs.js +2 -2
  652. package/dist/sdk/merge/install.js +6 -6
  653. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  654. package/dist/sdk/merge/receipt-operation.js +1 -1
  655. package/dist/sdk/merge/receipt-schema.js +1 -1
  656. package/dist/sdk/merge/receipts.js +4 -4
  657. package/dist/sdk/merge/reconcile.js +1 -1
  658. package/dist/sdk/merge/settlement-hook.js +4 -4
  659. package/dist/sdk/merge/stage.js +1 -1
  660. package/dist/sdk/merge/three-way.js +9 -9
  661. package/dist/sdk/merge/worktree-config.js +2 -2
  662. package/dist/sdk/merge.js +1 -1
  663. package/dist/sdk/mutation-events.js +1 -1
  664. package/dist/sdk/mutation-guard.js +1 -1
  665. package/dist/sdk/notes.js +1 -1
  666. package/dist/sdk/output/fit-envelope.js +1 -1
  667. package/dist/sdk/output/list-envelope.js +1 -1
  668. package/dist/sdk/output/table-rows.js +1 -1
  669. package/dist/sdk/output-contracts.js +1 -1
  670. package/dist/sdk/output-projection.js +1 -1
  671. package/dist/sdk/output-token-accounting.js +1 -1
  672. package/dist/sdk/output.js +2 -2
  673. package/dist/sdk/ownership-source.js +1 -1
  674. package/dist/sdk/package-import-adapters.js +1 -1
  675. package/dist/sdk/package-migrations.js +1 -1
  676. package/dist/sdk/package-runtime-options.js +1 -1
  677. package/dist/sdk/pagination.js +1 -1
  678. package/dist/sdk/profile.js +5 -5
  679. package/dist/sdk/provenance.js +1 -1
  680. package/dist/sdk/public-surface.json +1 -1
  681. package/dist/sdk/query/activity.js +1 -1
  682. package/dist/sdk/query/aggregate.js +1 -1
  683. package/dist/sdk/query/calendar.js +4 -4
  684. package/dist/sdk/query/complete-list.js +1 -1
  685. package/dist/sdk/query/context.js +2 -2
  686. package/dist/sdk/query/declared-blockers.js +1 -1
  687. package/dist/sdk/query/duplicate-candidates.js +1 -1
  688. package/dist/sdk/query/get-facet-roots.js +1 -1
  689. package/dist/sdk/query/get.js +1 -1
  690. package/dist/sdk/query/history.js +1 -1
  691. package/dist/sdk/query/item-filter-options.js +0 -1
  692. package/dist/sdk/query/light-metadata.js +1 -1
  693. package/dist/sdk/query/list-filter-shared.js +1 -1
  694. package/dist/sdk/query/list.js +1 -1
  695. package/dist/sdk/query/multi-value-filters.js +1 -1
  696. package/dist/sdk/query/next-ranking-policy.js +1 -1
  697. package/dist/sdk/query/next-ready-budget.js +1 -1
  698. package/dist/sdk/query/next.js +2 -2
  699. package/dist/sdk/query/parsers.js +1 -1
  700. package/dist/sdk/query/projection-contracts.js +1 -1
  701. package/dist/sdk/query/search/corpus.js +2 -2
  702. package/dist/sdk/query/search/filters.js +1 -1
  703. package/dist/sdk/query/search/input.js +1 -1
  704. package/dist/sdk/query/search/lexical.js +1 -1
  705. package/dist/sdk/query/search/response.js +1 -1
  706. package/dist/sdk/query/search/semantic.js +3 -3
  707. package/dist/sdk/query/search/types.js +0 -1
  708. package/dist/sdk/query/search-contracts.js +1 -1
  709. package/dist/sdk/query/search-pagination.js +1 -1
  710. package/dist/sdk/query/search-rendering.js +1 -1
  711. package/dist/sdk/query/search.js +1 -1
  712. package/dist/sdk/query/window-pagination.js +1 -1
  713. package/dist/sdk/query/workspace-contracts.js +1 -1
  714. package/dist/sdk/read-output/continuation.js +1 -1
  715. package/dist/sdk/read-output/extension.js +1 -1
  716. package/dist/sdk/read-output/options.js +1 -1
  717. package/dist/sdk/read-output/positional-rows.js +1 -1
  718. package/dist/sdk/read-output/provenance.js +1 -1
  719. package/dist/sdk/read-output/session-result.js +0 -1
  720. package/dist/sdk/read-output/surfaces.js +1 -1
  721. package/dist/sdk/read-output/tail-retention.js +1 -1
  722. package/dist/sdk/read-output-budget.js +1 -1
  723. package/dist/sdk/read-output-contracts.js +1 -1
  724. package/dist/sdk/read-output-rows.js +1 -1
  725. package/dist/sdk/read-output-session.js +1 -1
  726. package/dist/sdk/relationship-analytics.js +1 -1
  727. package/dist/sdk/relationship-context.js +1 -1
  728. package/dist/sdk/relationship-history.js +6 -6
  729. package/dist/sdk/relationship-kinds/contract.js +1 -1
  730. package/dist/sdk/relationships.js +1 -1
  731. package/dist/sdk/reproducibility/process.js +1 -1
  732. package/dist/sdk/runtime/actions.js +1 -1
  733. package/dist/sdk/runtime/context.js +1 -1
  734. package/dist/sdk/runtime/mutation-admission.js +1 -1
  735. package/dist/sdk/runtime/mutation-value-validation.js +1 -1
  736. package/dist/sdk/runtime/schema-preview.js +1 -1
  737. package/dist/sdk/runtime/schema.js +1 -1
  738. package/dist/sdk/runtime-action-aliases.js +1 -1
  739. package/dist/sdk/runtime-extended-actions.js +1 -1
  740. package/dist/sdk/runtime-input.d.ts +2 -0
  741. package/dist/sdk/runtime-input.js +1 -1
  742. package/dist/sdk/runtime-primitives.js +1 -1
  743. package/dist/sdk/runtime-public-contracts.js +0 -1
  744. package/dist/sdk/runtime-stats-options.js +1 -1
  745. package/dist/sdk/runtime.d.ts +5 -3
  746. package/dist/sdk/runtime.js +1 -1
  747. package/dist/sdk/scheduling-shortcuts.js +1 -1
  748. package/dist/sdk/schema/field-option-collisions.js +2 -0
  749. package/dist/sdk/schema-migration.js +4 -4
  750. package/dist/sdk/schema.js +7 -7
  751. package/dist/sdk/search-refresh-worker.js +1 -1
  752. package/dist/sdk/similarity-scoring.js +1 -1
  753. package/dist/sdk/similarity.js +1 -1
  754. package/dist/sdk/start-task-status.js +1 -1
  755. package/dist/sdk/stats.js +1 -1
  756. package/dist/sdk/structured-mutations.js +1 -1
  757. package/dist/sdk/telemetry-flush.js +1 -1
  758. package/dist/sdk/telemetry.js +4 -4
  759. package/dist/sdk/templates.js +3 -3
  760. package/dist/sdk/test/batch.js +2 -2
  761. package/dist/sdk/test/command-args.js +1 -1
  762. package/dist/sdk/test/command-resolution.js +2 -2
  763. package/dist/sdk/test/entry.js +2 -2
  764. package/dist/sdk/test/execution-receipts.js +2 -2
  765. package/dist/sdk/test/execution.js +5 -5
  766. package/dist/sdk/test/json-path.js +1 -1
  767. package/dist/sdk/test/linked-command-detection.js +1 -1
  768. package/dist/sdk/test/measurements.js +1 -1
  769. package/dist/sdk/test/parsers.js +1 -1
  770. package/dist/sdk/test/prerequisites.js +1 -1
  771. package/dist/sdk/test/receipt-index-snapshot.js +1 -1
  772. package/dist/sdk/test/run-phases.js +1 -1
  773. package/dist/sdk/test/runs.js +1 -1
  774. package/dist/sdk/test/trust.js +2 -2
  775. package/dist/sdk/test/update.js +1 -1
  776. package/dist/sdk/test/workspace-snapshot.js +1 -1
  777. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  778. package/dist/sdk/traceability/source-traceability.js +2 -2
  779. package/dist/sdk/tracker-root-discovery.js +1 -1
  780. package/dist/sdk/transactions/item-finalization.js +1 -1
  781. package/dist/sdk/workspace-contracts-cache.js +1 -1
  782. package/dist/sdk/workspace-contracts.js +1 -1
  783. package/dist/sdk/workspace-memory.js +2 -2
  784. package/dist/sdk/workspace-snapshot.js +5 -5
  785. package/dist/sdk/workspace-transaction-gc.js +1 -1
  786. package/dist/sdk/workspace-transaction.js +2 -2
  787. package/dist/sdk/workspace.js +6 -6
  788. package/dist/types/index.js +1 -1
  789. package/dist/types.js +1 -1
  790. package/docs/COMMANDS.md +1 -1
  791. package/docs/EXTENSIONS.md +1 -1
  792. package/docs/SDK.md +74 -4
  793. package/marketplace.json +1 -1
  794. package/package.json +2 -1
  795. package/packages/pm-beads/package.json +1 -1
  796. package/packages/pm-calendar/package.json +1 -1
  797. package/packages/pm-command-kit/package.json +1 -1
  798. package/packages/pm-digital-twin/package.json +1 -1
  799. package/packages/pm-governance-audit/package.json +1 -1
  800. package/packages/pm-guide-shell/package.json +1 -1
  801. package/packages/pm-kanban/package.json +1 -1
  802. package/packages/pm-lifecycle-hooks/package.json +1 -1
  803. package/packages/pm-linked-test-adapters/package.json +1 -1
  804. package/packages/pm-search-advanced/package.json +1 -1
  805. package/packages/pm-templates/package.json +1 -1
  806. package/packages/pm-todos/package.json +1 -1
  807. package/packages/pm-vcs/package.json +1 -1
  808. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  809. package/plugins/pm-claude/package.json +1 -1
  810. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  811. package/plugins/pm-codex/package.json +1 -1
  812. package/plugins/pm-codex/plugin.json +1 -1
  813. package/runtime-dependencies.json +1 -1
  814. package/scripts/finalize-build.mjs +63 -24
  815. package/scripts/prepare-build-cache.mjs +28 -1
  816. package/dist/cli-bundle/chunks/chunk-3W47ZZ5T.js +0 -9
  817. package/dist/cli-bundle/chunks/chunk-4TB5D6HL.js +0 -125
  818. package/dist/cli-bundle/chunks/chunk-5ZMVLWE3.js +0 -2
  819. package/dist/cli-bundle/chunks/chunk-6BBDEIKC.js +0 -33
  820. package/dist/cli-bundle/chunks/chunk-AR4NP5HI.js +0 -3
  821. package/dist/cli-bundle/chunks/chunk-B4PPFOPY.js +0 -3
  822. package/dist/cli-bundle/chunks/chunk-CAR2L5NW.js +0 -8
  823. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  824. package/dist/cli-bundle/chunks/chunk-EIGUKEV6.js +0 -2
  825. package/dist/cli-bundle/chunks/chunk-GTPCAJMZ.js +0 -8
  826. package/dist/cli-bundle/chunks/chunk-GYP24M7W.js +0 -2
  827. package/dist/cli-bundle/chunks/chunk-HC2OPETM.js +0 -2
  828. package/dist/cli-bundle/chunks/chunk-HKUV74K3.js +0 -2
  829. package/dist/cli-bundle/chunks/chunk-HXHYDO2R.js +0 -115
  830. package/dist/cli-bundle/chunks/chunk-IB7UB5TE.js +0 -2
  831. package/dist/cli-bundle/chunks/chunk-J2LABXBL.js +0 -2
  832. package/dist/cli-bundle/chunks/chunk-J52BEBSS.js +0 -2
  833. package/dist/cli-bundle/chunks/chunk-KQIZ34SF.js +0 -3
  834. package/dist/cli-bundle/chunks/chunk-LQBWLNZJ.js +0 -3
  835. package/dist/cli-bundle/chunks/chunk-OJTMGDON.js +0 -31
  836. package/dist/cli-bundle/chunks/chunk-SPPHDVZE.js +0 -2
  837. package/dist/cli-bundle/chunks/chunk-TC6XLIYO.js +0 -2
  838. package/dist/cli-bundle/chunks/chunk-U7EL3AYA.js +0 -3
  839. package/dist/cli-bundle/chunks/chunk-VQFWW4EF.js +0 -6
  840. package/dist/cli-bundle/chunks/chunk-X6MIWTTT.js +0 -2
  841. package/dist/cli-bundle/chunks/chunk-XC5Q2ZV7.js +0 -2
  842. package/dist/cli-bundle/chunks/chunk-XFHPKXAE.js +0 -71
  843. package/dist/cli-bundle/chunks/chunk-YHVLVSEZ.js +0 -9
  844. package/dist/cli-bundle/chunks/chunk-YMUSRWV4.js +0 -9
  845. package/dist/cli-bundle/chunks/chunk-YR2KEBHP.js +0 -2
  846. package/dist/cli-bundle/chunks/context-budget-recovery-L2WP5S26.js +0 -2
  847. package/dist/cli-bundle/chunks/indexed-receipt-blobs-ITTXIN4K.js +0 -4
  848. package/dist/cli-bundle/chunks/item-transaction-QY3PUHEI.js +0 -2
  849. package/dist/cli-bundle/chunks/mutation-actor-FWLYWJ37.js +0 -2
  850. package/dist/cli-bundle/chunks/mutation-admission-7ZDCK3G2.js +0 -2
  851. package/dist/cli-bundle/chunks/register-mutation-57AJQWFV.js +0 -21
  852. package/dist/cli-bundle/chunks/register-operations-RKWST7CU.js +0 -2
  853. package/dist/cli-bundle/chunks/register-setup-CMI23PC5.js +0 -2
  854. package/dist/cli-bundle/chunks/settlement-hook-BXN5LEQD.js +0 -7
  855. package/dist/cli-bundle/chunks/stage-4KDVXC5Z.js +0 -2
  856. package/dist/cli-bundle/focused-chunks/chunk-2ZD7275J.js +0 -2
  857. package/dist/cli-bundle/focused-chunks/chunk-324AHXJO.js +0 -2
  858. package/dist/cli-bundle/focused-chunks/chunk-3IRCYJI5.js +0 -3
  859. package/dist/cli-bundle/focused-chunks/chunk-3V53UBHN.js +0 -9
  860. package/dist/cli-bundle/focused-chunks/chunk-3XSWH6QC.js +0 -91
  861. package/dist/cli-bundle/focused-chunks/chunk-4JZITIJB.js +0 -2
  862. package/dist/cli-bundle/focused-chunks/chunk-4KTFKSS3.js +0 -2
  863. package/dist/cli-bundle/focused-chunks/chunk-5C5TK3ET.js +0 -78
  864. package/dist/cli-bundle/focused-chunks/chunk-AKJYOZZP.js +0 -2
  865. package/dist/cli-bundle/focused-chunks/chunk-BRZV7BFV.js +0 -8
  866. package/dist/cli-bundle/focused-chunks/chunk-C3O6JJPO.js +0 -2
  867. package/dist/cli-bundle/focused-chunks/chunk-CR7CGEB2.js +0 -3
  868. package/dist/cli-bundle/focused-chunks/chunk-EGN2HFRU.js +0 -2
  869. package/dist/cli-bundle/focused-chunks/chunk-GHQVM6K6.js +0 -2
  870. package/dist/cli-bundle/focused-chunks/chunk-HDEKFSOK.js +0 -2
  871. package/dist/cli-bundle/focused-chunks/chunk-I5LGPUWH.js +0 -2
  872. package/dist/cli-bundle/focused-chunks/chunk-IWOXAUDU.js +0 -2
  873. package/dist/cli-bundle/focused-chunks/chunk-ML3JHCC6.js +0 -6
  874. package/dist/cli-bundle/focused-chunks/chunk-OPGOOP25.js +0 -2
  875. package/dist/cli-bundle/focused-chunks/chunk-RE7ZWT7D.js +0 -27
  876. package/dist/cli-bundle/focused-chunks/chunk-RKQNVYGF.js +0 -3
  877. package/dist/cli-bundle/focused-chunks/chunk-RQ252B6V.js +0 -8
  878. package/dist/cli-bundle/focused-chunks/chunk-SVOOGGAK.js +0 -2
  879. package/dist/cli-bundle/focused-chunks/chunk-URGHTTT3.js +0 -8
  880. package/dist/cli-bundle/focused-chunks/chunk-USPYKWQG.js +0 -13
  881. package/dist/cli-bundle/focused-chunks/chunk-UWS3FC4D.js +0 -102
  882. package/dist/cli-bundle/focused-chunks/chunk-UXQGFGAT.js +0 -44
  883. package/dist/cli-bundle/focused-chunks/chunk-WZWXGDYY.js +0 -26
  884. package/dist/cli-bundle/focused-chunks/chunk-YKSLZPLT.js +0 -2
  885. package/dist/cli-bundle/focused-chunks/chunk-ZWJTY4ID.js +0 -2
  886. package/dist/cli-bundle/focused-chunks/context-budget-recovery-5MKOCGY5.js +0 -2
  887. package/dist/cli-bundle/focused-chunks/indexed-receipt-blobs-AF4U3F3D.js +0 -4
  888. package/dist/cli-bundle/focused-chunks/item-transaction-GLACUTPL.js +0 -2
  889. package/dist/cli-bundle/focused-chunks/mutation-actor-TCYDPUGG.js +0 -2
  890. package/dist/cli-bundle/focused-chunks/mutation-admission-LY73EJWM.js +0 -2
  891. package/dist/cli-bundle/focused-chunks/settlement-hook-ARYCZQY4.js +0 -7
  892. package/dist/cli-bundle/focused-chunks/stage-DQ7RQQ52.js +0 -2
@@ -1,2 +1,2 @@
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]="74b476d9-5f30-5135-9539-5fe3e864c60f")}catch{}})();import{runActiveServiceOverride}from"../core/extensions/index.js";import{normalizeStatusForRegistry,normalizeStatusInput}from"../core/item/status.js";import{compareTimestampStrings}from"../core/shared/time.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{isReadOutputBudgetExceeded}from"./read-output-contracts.js";import{canonicalizeContextRecencyCoordinate,CONTEXT_RECENCY_EPOCH}from"./context/recency.js";const CONTEXT_RELEVANCE_SIGNAL_NAMES=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],NO_CONTEXT_AUTHOR=Symbol("no-context-author"),NO_ITEM_ASSIGNEE=Symbol("no-item-assignee");function normalizeContextActor(value,missingValue){if(typeof value!="string")return missingValue;const normalized=value.trim().toLowerCase();return normalized.length>0?normalized:missingValue}function releaseCohortCoordinate(value){if(typeof value!="string")return;const match=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(value.trim());if(!match)return;const year=Number(match[1]),month=Number(match[2]),day=Number(match[3]),date=new Date(Date.UTC(year,month-1,day));return date.getUTCFullYear()===year&&date.getUTCMonth()===month-1&&date.getUTCDate()===day?date.toISOString():void 0}function fallbackRecencyEvidence(item){const releaseCoordinate=releaseCohortCoordinate(item.release);return releaseCoordinate!==void 0?{source:"release_cohort",coordinate:releaseCoordinate}:{source:"created_at",coordinate:canonicalizeContextRecencyCoordinate(item.created_at)??CONTEXT_RECENCY_EPOCH}}function canonicalizeRecencyEvidence(evidence){if(!["substantive_history","release_cohort","created_at"].includes(evidence.source)||(evidence.source==="substantive_history"?evidence.history_op!==void 0&&typeof evidence.history_op!="string"||evidence.event_class!==void 0&&evidence.event_class!=="substantive":evidence.history_op!==void 0||evidence.event_class!==void 0))throw new TypeError("Context signal recency provenance must match its source");const coordinate=canonicalizeContextRecencyCoordinate(evidence.coordinate);if(coordinate===null)throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision");return{...evidence,coordinate}}function normalizedPressure(value,maximum){const parsed=typeof value=="number"?value:typeof value=="string"?Number.parseFloat(value):Number.NaN;return Number.isFinite(parsed)?1-Math.min(Math.max(parsed,0),maximum)/maximum:0}function deadlinePressure(deadline,nowMs){const deadlineMs=typeof deadline=="string"?Date.parse(deadline):deadline instanceof Date?deadline.getTime():typeof deadline=="number"?deadline:Number.NaN;if(!Number.isFinite(deadlineMs)||!Number.isFinite(nowMs))return 0;const days=(deadlineMs-nowMs)/864e5;return days<=0?1:1/(1+days/30)}function riskPressure(risk){const normalized=typeof risk=="string"?risk.trim().toLowerCase():void 0;return normalized==="critical"||normalized==="high"?1:normalized==="medium"?.5:normalized==="low"?.1:0}function derivedSignalOrFallback(values,id,fallback){return values?.[id]??fallback}function buildItemContextRelevanceCandidates(items,options){const recencyEvidence=new Map(items.map(item=>{const suppliedEvidence=options.recencyEvidence?.[item.id];return[item.id,suppliedEvidence===void 0?fallbackRecencyEvidence(item):canonicalizeRecencyEvidence(suppliedEvidence)]})),recencyOrder=[...items].sort((left,right)=>{const leftTime=recencyEvidence.get(left.id).coordinate,rightTime=recencyEvidence.get(right.id).coordinate;return compareTimestampStrings(rightTime,leftTime)||left.id.localeCompare(right.id)}),recencyRank=new Map(recencyOrder.map((item,index)=>[item.id,index])),denominator=Math.max(items.length-1,1),normalizedAuthor=normalizeContextActor(options.author,NO_CONTEXT_AUTHOR),inProgressStatus=normalizeStatusInput("in_progress",options.statusRegistry),nowMs=Date.parse(options.now);return items.map(item=>{const assigned=normalizeContextActor(item.assignee,NO_ITEM_ASSIGNEE)===normalizedAuthor,knowledgeEntries=(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0);return{id:item.id,item,signal_provenance:{recency:recencyEvidence.get(item.id)},signals:{recency:items.length===1?1:1-recencyRank.get(item.id)/denominator,activity_density:options.activityDensity?.[item.id],graph_proximity:derivedSignalOrFallback(options.graphProximity,item.id,item.parent?.3:0),claim_focus:derivedSignalOrFallback(options.claimFocus,item.id,normalizeStatusForRegistry(item.status,options.statusRegistry)===inProgressStatus?1:assigned?.75:0),priority_pressure:normalizedPressure(item.priority,4),risk_pressure:riskPressure(item.risk),deadline_pressure:deadlinePressure(item.deadline,nowMs),knowledge_density:derivedSignalOrFallback(options.knowledgeDensity,item.id,Math.min(knowledgeEntries/5,1)),author_affinity:derivedSignalOrFallback(options.authorAffinity,item.id,assigned?1:0),usage_affinity:options.usageAffinity?.[item.id],semantic_similarity:options.semanticSimilarity?.[item.id]}}})}const CONTEXT_RELEVANCE_SERVICE="context_relevance",DEFAULT_CONTEXT_RELEVANCE_WEIGHTS={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5},JSON_TOKEN_ENCODER=new TextEncoder;function assertCandidates(candidates){const ids=new Set;for(const candidate of candidates){if(typeof candidate.id!="string"||candidate.id.trim().length===0||ids.has(candidate.id))throw new TypeError("Context relevance candidates require unique non-empty ids");ids.add(candidate.id);for(const[signal,value]of Object.entries(candidate.signals??{})){if(signal==="structural"||!CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal))throw new TypeError(`Unknown context relevance signal: ${signal}`);if(value!==void 0&&(!Number.isFinite(value)||value<0||value>1))throw new TypeError(`Context relevance signal ${signal} must be a finite number from 0 to 1`)}}}function resolveWeights(overrides){const weights={...DEFAULT_CONTEXT_RELEVANCE_WEIGHTS};for(const[signal,weight]of Object.entries(overrides??{}))weight!==void 0&&CONTEXT_RELEVANCE_SIGNAL_NAMES.includes(signal)&&(weights[signal]=weight);for(const[signal,weight]of Object.entries(weights))if(!Number.isFinite(weight)||weight<0)throw new TypeError(`Context relevance weight ${signal} must be a finite non-negative number`);return weights}function defaultScoreContextCandidates(candidates,options={}){assertCandidates(candidates);const weights=resolveWeights(options.weights),denominator=Math.max(candidates.length-1,1),available=new Set(["structural"]);for(const candidate of candidates)for(const[signal,value]of Object.entries(candidate.signals??{}))value!==void 0&&available.add(signal);const availableSignals=CONTEXT_RELEVANCE_SIGNAL_NAMES.filter(signal=>available.has(signal)),scored=candidates.map((candidate,index)=>{const signalValues={structural:candidates.length===1?1:1-index/denominator,...candidate.signals},contributions={};let weightedScore=0,totalWeight=0;for(const signal of availableSignals){const value=signalValues[signal];if(value===void 0)continue;const contribution=value*weights[signal];contributions[signal]=contribution,weightedScore+=contribution,totalWeight+=weights[signal]}return{...candidate,baseline_rank:index+1,rank:0,score:totalWeight===0?0:weightedScore/totalWeight,contributions}});return scored.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank),scored.forEach((entry,index)=>{entry.rank=index+1}),{model:"default-weighted-v1",available_signals:availableSignals,ranked:scored}}async function scoreContextCandidates(candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options);if(!options.scorer)return defaultReport;const customScores=await options.scorer({candidates,default_report:defaultReport}),scoreById=new Map;for(const entry of customScores){if(scoreById.has(entry.id)||!Number.isFinite(entry.score))throw new TypeError("Context relevance scorer must return one finite score for every candidate");scoreById.set(entry.id,entry.score)}if(scoreById.size!==candidates.length||candidates.some(candidate=>!scoreById.has(candidate.id)))throw new TypeError("Context relevance scorer must return one finite score for every candidate");const ranked=defaultReport.ranked.map(entry=>{const score=scoreById.get(entry.id);return{...entry,score,contributions:{custom:score}}});return ranked.sort((left,right)=>right.score-left.score||left.baseline_rank-right.baseline_rank),ranked.forEach((entry,index)=>{entry.rank=index+1}),{model:"custom",available_signals:defaultReport.available_signals,ranked}}async function scoreContextCandidatesWithActiveExtensions(surface,candidates,options={}){const defaultReport=defaultScoreContextCandidates(candidates,options),override=await runActiveServiceOverride(CONTEXT_RELEVANCE_SERVICE,{surface,candidates,default_report:defaultReport});if(!override.handled)return override.warnings.length>0?{...defaultReport,warnings:override.warnings}:defaultReport;if(!Array.isArray(override.result)||!override.result.every(entry=>typeof entry=="object"&&entry!==null&&typeof entry.id=="string"&&typeof entry.score=="number"&&Number.isFinite(entry.score)))return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]};try{const report=await scoreContextCandidates(candidates,{...options,scorer:()=>override.result});return override.warnings.length>0?{...report,warnings:override.warnings}:report}catch{return{...defaultReport,warnings:[...override.warnings,"extension_context_relevance_invalid_result"]}}}const CONTEXT_EVALUATION_METRIC_NAMES=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function ratioOfPresent(expected,actual){return expected.length===0?1:expected.filter(id=>actual.has(id)).length/expected.length}function evaluateContextRanking(input){if(!Number.isFinite(input.actual_tokens)||input.actual_tokens<0||!Number.isFinite(input.token_budget)||input.token_budget<=0)throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0");const judgments=input.judgments??{},gains=input.ranked_ids.map(id=>Math.max(0,judgments[id]??0)),idealGains=Object.values(judgments).map(grade=>Math.max(0,grade)).sort((left,right)=>right-left).slice(0,gains.length||1),discountedGain=values=>values.reduce((total,grade,index)=>total+(2**grade-1)/Math.log2(index+2),0),ideal=discountedGain(idealGains),firstRelevant=gains.findIndex(grade=>grade>0),actualIds=new Set(input.ranked_ids),withinBudget=input.actual_tokens<=input.token_budget;return{ndcg:ideal===0?1:discountedGain(gains)/ideal,reciprocal_rank:firstRelevant<0?0:1/(firstRelevant+1),required_recall:ratioOfPresent(input.required_ids??[],actualIds),continuity_coverage:ratioOfPresent(input.continuity_ids??[],actualIds),token_budget_adherence:withinBudget?1:input.token_budget/input.actual_tokens,within_token_budget:withinBudget}}function estimateJsonTokens(value){return Math.ceil(JSON_TOKEN_ENCODER.encode(JSON.stringify(value)).byteLength/4)}function roundEvaluationMetric(value){return Math.round(value*1e4)/1e4}function rankingPayloadForScenario(result,surface){const rankedIds=surface==="context"?[...result.high_level??[],...result.low_level??[],...result.blocked_fallback??[]].map(item=>item.id):[...result.recommended?[result.recommended]:[],...result.ready??[]].map(item=>item.id),servedIds=new Set(rankedIds),attribution=(result.ranking?.items??[]).filter(item=>servedIds.has(item.id)).map(item=>({id:item.id,contributions:item.contributions}));return{rankedIds,attribution}}async function runContextEvaluationScenario(scenario,reader){if(scenario.id.trim().length===0||scenario.rationale.trim().length===0)throw new TypeError("Context evaluation scenarios require non-empty id and rationale values");const result=scenario.surface==="context"?await reader.context({...scenario.options,explainRanking:!0,outputBudget:scenario.options?.outputBudget??"unbounded"}):await reader.next({...scenario.options,explainRanking:!0,outputBudget:scenario.options?.outputBudget??"unbounded"});if(isReadOutputBudgetExceeded(result)||result.read_output?.result_omitted===!0||result.context_intent?.result_omitted===!0)throw new PmCliError(`Cannot evaluate ${scenario.surface} scenario "${scenario.id}": the read omitted its useful result.`,EXIT_CODE.USAGE,{code:"context_evaluation_read_incomplete",nextSteps:["Increase the read output budget or start a new shared output session, then rerun the scenario."]});const{rankedIds,attribution}=rankingPayloadForScenario(result,scenario.surface),packet={...result,ranking:void 0},actualTokens=estimateJsonTokens(packet);return{id:scenario.id,surface:scenario.surface,rationale:scenario.rationale,ranked_ids:rankedIds,actual_tokens:actualTokens,metrics:evaluateContextRanking({ranked_ids:rankedIds,judgments:scenario.judgments,required_ids:scenario.required_ids,continuity_ids:scenario.continuity_ids,actual_tokens:actualTokens,token_budget:scenario.token_budget}),attribution}}function summarizeContextEvaluationReports(reports,thresholds){if(reports.length===0)throw new TypeError("Context evaluation requires at least one scenario report");const metrics=CONTEXT_EVALUATION_METRIC_NAMES;for(const metric of metrics)if(!Number.isFinite(thresholds[metric]))throw new TypeError(`Context evaluation threshold ${metric} must be a finite number`);const aggregate=Object.fromEntries(metrics.map(metric=>[metric,roundEvaluationMetric(reports.reduce((total,report)=>total+report.metrics[metric],0)/reports.length)])),failures=metrics.filter(metric=>aggregate[metric]<thresholds[metric]).map(metric=>`${metric}:${aggregate[metric]}<${thresholds[metric]}`);return{scenario_count:reports.length,aggregate,scenarios:[...reports],passed:failures.length===0,failures}}async function runContextEvaluationCorpus(scenarios,reader,thresholds){const reports=[];for(const scenario of scenarios)reports.push(await runContextEvaluationScenario(scenario,reader));return summarizeContextEvaluationReports(reports,thresholds)}export{CONTEXT_EVALUATION_METRIC_NAMES,CONTEXT_RELEVANCE_SERVICE,CONTEXT_RELEVANCE_SIGNAL_NAMES,buildItemContextRelevanceCandidates,defaultScoreContextCandidates,evaluateContextRanking,runContextEvaluationCorpus,runContextEvaluationScenario,scoreContextCandidates,scoreContextCandidatesWithActiveExtensions,summarizeContextEvaluationReports};
1
+ import{runActiveServiceOverride as k}from"../core/extensions/index.js";import{normalizeStatusForRegistry as x,normalizeStatusInput as C}from"../core/item/status.js";import{compareTimestampStrings as v}from"../core/shared/time.js";import{EXIT_CODE as T}from"../core/shared/constants.js";import{PmCliError as N}from"../core/shared/errors.js";import{isReadOutputBudgetExceeded as S}from"./read-output-contracts.js";import{canonicalizeContextRecencyCoordinate as p,CONTEXT_RECENCY_EPOCH as O}from"./context/recency.js";const m=["structural","recency","activity_density","graph_proximity","claim_focus","priority_pressure","risk_pressure","deadline_pressure","knowledge_density","author_affinity","usage_affinity","semantic_similarity"],R=Symbol("no-context-author"),A=Symbol("no-item-assignee");function b(e,t){if(typeof e!="string")return t;const n=e.trim().toLowerCase();return n.length>0?n:t}function M(e){if(typeof e!="string")return;const t=/^v?(\d{4})\.(\d{1,2})\.(\d{1,2})(?:$|[-+])/u.exec(e.trim());if(!t)return;const n=Number(t[1]),s=Number(t[2]),i=Number(t[3]),r=new Date(Date.UTC(n,s-1,i));return r.getUTCFullYear()===n&&r.getUTCMonth()===s-1&&r.getUTCDate()===i?r.toISOString():void 0}function I(e){const t=M(e.release);return t!==void 0?{source:"release_cohort",coordinate:t}:{source:"created_at",coordinate:p(e.created_at)??O}}function F(e){if(!["substantive_history","release_cohort","created_at"].includes(e.source)||(e.source==="substantive_history"?e.history_op!==void 0&&typeof e.history_op!="string"||e.event_class!==void 0&&e.event_class!=="substantive":e.history_op!==void 0||e.event_class!==void 0))throw new TypeError("Context signal recency provenance must match its source");const t=p(e.coordinate);if(t===null)throw new TypeError("Context signal recency coordinate must be a valid absolute timestamp with millisecond precision");return{...e,coordinate:t}}function j(e,t){const n=typeof e=="number"?e:typeof e=="string"?Number.parseFloat(e):Number.NaN;return Number.isFinite(n)?1-Math.min(Math.max(n,0),t)/t:0}function z(e,t){const n=typeof e=="string"?Date.parse(e):e instanceof Date?e.getTime():typeof e=="number"?e:Number.NaN;if(!Number.isFinite(n)||!Number.isFinite(t))return 0;const s=(n-t)/864e5;return s<=0?1:1/(1+s/30)}function D(e){const t=typeof e=="string"?e.trim().toLowerCase():void 0;return t==="critical"||t==="high"?1:t==="medium"?.5:t==="low"?.1:0}function _(e,t,n){return e?.[t]??n}function oe(e,t){const n=new Map(e.map(o=>{const u=t.recencyEvidence?.[o.id];return[o.id,u===void 0?I(o):F(u)]})),s=[...e].sort((o,u)=>{const l=n.get(o.id).coordinate,f=n.get(u.id).coordinate;return v(f,l)||o.id.localeCompare(u.id)}),i=new Map(s.map((o,u)=>[o.id,u])),r=Math.max(e.length-1,1),c=b(t.author,R),a=C("in_progress",t.statusRegistry),d=Date.parse(t.now);return e.map(o=>{const u=b(o.assignee,A)===c,l=(o.comments?.length??0)+(o.notes?.length??0)+(o.learnings?.length??0);return{id:o.id,item:o,signal_provenance:{recency:n.get(o.id)},signals:{recency:e.length===1?1:1-i.get(o.id)/r,activity_density:t.activityDensity?.[o.id],graph_proximity:_(t.graphProximity,o.id,o.parent?.3:0),claim_focus:_(t.claimFocus,o.id,x(o.status,t.statusRegistry)===a?1:u?.75:0),priority_pressure:j(o.priority,4),risk_pressure:D(o.risk),deadline_pressure:z(o.deadline,d),knowledge_density:_(t.knowledgeDensity,o.id,Math.min(l/5,1)),author_affinity:_(t.authorAffinity,o.id,u?1:0),usage_affinity:t.usageAffinity?.[o.id],semantic_similarity:t.semanticSimilarity?.[o.id]}}})}const q="context_relevance",$={structural:.4,recency:.35,activity_density:.25,graph_proximity:.15,claim_focus:.6,priority_pressure:.35,risk_pressure:.2,deadline_pressure:.45,knowledge_density:.25,author_affinity:.2,usage_affinity:.3,semantic_similarity:.5},L=new TextEncoder;function P(e){const t=new Set;for(const n of e){if(typeof n.id!="string"||n.id.trim().length===0||t.has(n.id))throw new TypeError("Context relevance candidates require unique non-empty ids");t.add(n.id);for(const[s,i]of Object.entries(n.signals??{})){if(s==="structural"||!m.includes(s))throw new TypeError(`Unknown context relevance signal: ${s}`);if(i!==void 0&&(!Number.isFinite(i)||i<0||i>1))throw new TypeError(`Context relevance signal ${s} must be a finite number from 0 to 1`)}}}function U(e){const t={...$};for(const[n,s]of Object.entries(e??{}))s!==void 0&&m.includes(n)&&(t[n]=s);for(const[n,s]of Object.entries(t))if(!Number.isFinite(s)||s<0)throw new TypeError(`Context relevance weight ${n} must be a finite non-negative number`);return t}function w(e,t={}){P(e);const n=U(t.weights),s=Math.max(e.length-1,1),i=new Set(["structural"]);for(const a of e)for(const[d,o]of Object.entries(a.signals??{}))o!==void 0&&i.add(d);const r=m.filter(a=>i.has(a)),c=e.map((a,d)=>{const o={structural:e.length===1?1:1-d/s,...a.signals},u={};let l=0,f=0;for(const g of r){const h=o[g];if(h===void 0)continue;const y=h*n[g];u[g]=y,l+=y,f+=n[g]}return{...a,baseline_rank:d+1,rank:0,score:f===0?0:l/f,contributions:u}});return c.sort((a,d)=>d.score-a.score||a.baseline_rank-d.baseline_rank),c.forEach((a,d)=>{a.rank=d+1}),{model:"default-weighted-v1",available_signals:r,ranked:c}}async function B(e,t={}){const n=w(e,t);if(!t.scorer)return n;const s=await t.scorer({candidates:e,default_report:n}),i=new Map;for(const c of s){if(i.has(c.id)||!Number.isFinite(c.score))throw new TypeError("Context relevance scorer must return one finite score for every candidate");i.set(c.id,c.score)}if(i.size!==e.length||e.some(c=>!i.has(c.id)))throw new TypeError("Context relevance scorer must return one finite score for every candidate");const r=n.ranked.map(c=>{const a=i.get(c.id);return{...c,score:a,contributions:{custom:a}}});return r.sort((c,a)=>a.score-c.score||c.baseline_rank-a.baseline_rank),r.forEach((c,a)=>{c.rank=a+1}),{model:"custom",available_signals:n.available_signals,ranked:r}}async function ie(e,t,n={}){const s=w(t,n),i=await k(q,{surface:e,candidates:t,default_report:s});if(!i.handled)return i.warnings.length>0?{...s,warnings:i.warnings}:s;if(!Array.isArray(i.result)||!i.result.every(r=>typeof r=="object"&&r!==null&&typeof r.id=="string"&&typeof r.score=="number"&&Number.isFinite(r.score)))return{...s,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]};try{const r=await B(t,{...n,scorer:()=>i.result});return i.warnings.length>0?{...r,warnings:i.warnings}:r}catch{return{...s,warnings:[...i.warnings,"extension_context_relevance_invalid_result"]}}}const X=["ndcg","reciprocal_rank","required_recall","continuity_coverage","token_budget_adherence"];function E(e,t){return e.length===0?1:e.filter(n=>t.has(n)).length/e.length}function G(e){if(!Number.isFinite(e.actual_tokens)||e.actual_tokens<0||!Number.isFinite(e.token_budget)||e.token_budget<=0)throw new TypeError("Context ranking token counts require actual_tokens >= 0 and token_budget > 0");const t=e.judgments??{},n=e.ranked_ids.map(o=>Math.max(0,t[o]??0)),s=Object.values(t).map(o=>Math.max(0,o)).sort((o,u)=>u-o).slice(0,n.length||1),i=o=>o.reduce((u,l,f)=>u+(2**l-1)/Math.log2(f+2),0),r=i(s),c=n.findIndex(o=>o>0),a=new Set(e.ranked_ids),d=e.actual_tokens<=e.token_budget;return{ndcg:r===0?1:i(n)/r,reciprocal_rank:c<0?0:1/(c+1),required_recall:E(e.required_ids??[],a),continuity_coverage:E(e.continuity_ids??[],a),token_budget_adherence:d?1:e.token_budget/e.actual_tokens,within_token_budget:d}}function V(e){return Math.ceil(L.encode(JSON.stringify(e)).byteLength/4)}function W(e){return Math.round(e*1e4)/1e4}function H(e,t){const n=t==="context"?[...e.high_level??[],...e.low_level??[],...e.blocked_fallback??[]].map(r=>r.id):[...e.recommended?[e.recommended]:[],...e.ready??[]].map(r=>r.id),s=new Set(n),i=(e.ranking?.items??[]).filter(r=>s.has(r.id)).map(r=>({id:r.id,contributions:r.contributions}));return{rankedIds:n,attribution:i}}async function J(e,t){if(e.id.trim().length===0||e.rationale.trim().length===0)throw new TypeError("Context evaluation scenarios require non-empty id and rationale values");const n=e.surface==="context"?await t.context({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"}):await t.next({...e.options,explainRanking:!0,outputBudget:e.options?.outputBudget??"unbounded"});if(S(n)||n.read_output?.result_omitted===!0||n.context_intent?.result_omitted===!0)throw new N(`Cannot evaluate ${e.surface} scenario "${e.id}": the read omitted its useful result.`,T.USAGE,{code:"context_evaluation_read_incomplete",nextSteps:["Increase the read output budget or start a new shared output session, then rerun the scenario."]});const{rankedIds:i,attribution:r}=H(n,e.surface),c={...n,ranking:void 0},a=V(c);return{id:e.id,surface:e.surface,rationale:e.rationale,ranked_ids:i,actual_tokens:a,metrics:G({ranked_ids:i,judgments:e.judgments,required_ids:e.required_ids,continuity_ids:e.continuity_ids,actual_tokens:a,token_budget:e.token_budget}),attribution:r}}function Y(e,t){if(e.length===0)throw new TypeError("Context evaluation requires at least one scenario report");const n=X;for(const r of n)if(!Number.isFinite(t[r]))throw new TypeError(`Context evaluation threshold ${r} must be a finite number`);const s=Object.fromEntries(n.map(r=>[r,W(e.reduce((c,a)=>c+a.metrics[r],0)/e.length)])),i=n.filter(r=>s[r]<t[r]).map(r=>`${r}:${s[r]}<${t[r]}`);return{scenario_count:e.length,aggregate:s,scenarios:[...e],passed:i.length===0,failures:i}}async function se(e,t,n){const s=[];for(const i of e)s.push(await J(i,t));return Y(s,n)}export{X as CONTEXT_EVALUATION_METRIC_NAMES,q as CONTEXT_RELEVANCE_SERVICE,m as CONTEXT_RELEVANCE_SIGNAL_NAMES,oe as buildItemContextRelevanceCandidates,w as defaultScoreContextCandidates,G as evaluateContextRanking,se as runContextEvaluationCorpus,J as runContextEvaluationScenario,B as scoreContextCandidates,ie as scoreContextCandidatesWithActiveExtensions,Y as summarizeContextEvaluationReports};
2
2
  //# sourceMappingURL=context-relevance.js.map
@@ -1,3 +1,3 @@
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]="179e487f-baf9-59d1-a438-3ae0c12b00eb")}catch{}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import fs from"node:fs/promises";import path from"node:path";import{createHash,randomUUID}from"node:crypto";import{buildItemContextRelevanceCandidates}from"./context-relevance.js";import{readItemMetadataDerivedIndexState}from"./item-metadata-index.js";import{readLatestSubstantiveHistoryEvents}from"../core/history/event-index.js";import{canonicalizeContextRecencyCoordinate}from"./context/recency.js";const CONTEXT_SIGNAL_STORE_FORMAT_VERSION=3,CONTEXT_SIGNAL_SET_VERSION=2,STORED_CONTEXT_SIGNAL_NAMES=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],CONTEXT_RECENCY_SOURCES=new Set(["substantive_history","release_cohort","created_at"]),CONTEXT_SIGNAL_STORE_WARNING_DETAILS={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function isNormalizedSignal(value){return typeof value=="number"&&Number.isFinite(value)&&value>=0&&value<=1}function compactSignals(signals){const compact={};for(const name of STORED_CONTEXT_SIGNAL_NAMES){const value=signals[name];if(value!==void 0){if(!isNormalizedSignal(value))throw new TypeError(`Context relevance signal ${name} must be a finite number from 0 to 1`);compact[name]=value}}return compact}function normalizedCountsById(items,count){const counts=items.map(item=>[item.id,count(item)]),maximum=Math.max(0,...counts.map(([,value])=>value));return Object.fromEntries(counts.map(([id,value])=>[id,maximum===0?0:value/maximum]))}function deriveGraphProximity(items){const degree=new Map(items.map(item=>[item.id,0])),increment=id=>{degree.set(id,(degree.get(id)??0)+1)};for(const item of items){typeof item.parent=="string"&&item.parent.trim()&&(increment(item.id),increment(item.parent.trim()));for(const dependency of item.dependencies??[])typeof dependency.id!="string"||!dependency.id.trim()||(increment(item.id),increment(dependency.id.trim()))}const maximum=Math.max(0,...degree.values());return Object.fromEntries(items.map(item=>[item.id,maximum===0?0:degree.get(item.id)/maximum]))}function stableSnapshotOptions(items,options){return{...options,activityDensity:options.activityDensity??normalizedCountsById(items,item=>(item.comments?.length??0)+(item.notes?.length??0)+(item.learnings?.length??0)+(item.test_runs?.length??0)),graphProximity:options.graphProximity??deriveGraphProximity(items)}}function recencyEvidenceFingerprint(candidates){const hash=createHash("sha256");for(const{id,signal_provenance:{recency:evidence}}of[...candidates].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([id,evidence.source,evidence.coordinate,evidence.history_op??null,evidence.event_class??null]));return`sha256:${hash.digest("hex")}`}function parseSnapshotItem(value){if(!isRecord(value))return null;const signalProvenance=value.signal_provenance;if(![typeof value.id=="string",isRecord(value.signals),isRecord(signalProvenance)].every(Boolean))return null;const recency=signalProvenance.recency;if(!isRecord(recency))return null;const coordinate=canonicalizeContextRecencyCoordinate(recency.coordinate);if(coordinate===null)return null;const supportedSignals=new Set(STORED_CONTEXT_SIGNAL_NAMES),signalEntries=Object.entries(value.signals);return!signalEntries.every(([name,signal])=>supportedSignals.has(name)&&isNormalizedSignal(signal))||![typeof recency.source=="string"&&CONTEXT_RECENCY_SOURCES.has(recency.source),["undefined","string"].includes(typeof recency.history_op),[void 0,"substantive","maintenance"].includes(recency.event_class),recency.source==="substantive_history"?recency.event_class===void 0||recency.event_class==="substantive":recency.history_op===void 0&&recency.event_class===void 0].every(Boolean)?null:{id:value.id,signals:Object.fromEntries(signalEntries),signal_provenance:{recency:{source:recency.source,coordinate,history_op:recency.history_op,event_class:recency.event_class}}}}function parseSnapshotItems(values,expectedRecencyEvidenceFingerprint){const items=Array.from(values,parseSnapshotItem);if(items.some(item=>item===null))return null;const validItems=items;return new Set(validItems.map(item=>item.id)).size!==validItems.length||validItems.some(item=>item.id.trim().length===0)||expectedRecencyEvidenceFingerprint!==recencyEvidenceFingerprint(validItems)?null:validItems.sort((left,right)=>left.id.localeCompare(right.id))}function parseContextSignalSnapshot(value){if(!isRecord(value)||value.format_version!==CONTEXT_SIGNAL_STORE_FORMAT_VERSION||value.signal_set_version!==CONTEXT_SIGNAL_SET_VERSION||typeof value.source_cursor!="string"||value.source_cursor.trim().length===0||typeof value.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(value.recency_evidence_fingerprint)||typeof value.generated_at!="string"||!Number.isFinite(Date.parse(value.generated_at))||value.source!=="derived_index"&&value.source!=="scan_fallback"||!Array.isArray(value.items))return null;const items=parseSnapshotItems(value.items,value.recency_evidence_fingerprint);return items===null?null:{format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:value.source_cursor,recency_evidence_fingerprint:value.recency_evidence_fingerprint,generated_at:value.generated_at,source:value.source,items}}function validateSnapshotOptions(options){if(typeof options.sourceCursor!="string"||options.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(options.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(options.source!=="derived_index"&&options.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function snapshotFromCandidates(candidates,options,fingerprint=recencyEvidenceFingerprint(candidates)){const candidateIds=candidates.map(({id})=>id);if(new Set(candidateIds).size!==candidateIds.length||candidateIds.some(id=>id.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");const rows=candidates.map(({id,signals,signal_provenance})=>({id,signals:compactSignals(signals),signal_provenance})).sort((left,right)=>left.id.localeCompare(right.id));return Object.freeze({format_version:CONTEXT_SIGNAL_STORE_FORMAT_VERSION,signal_set_version:CONTEXT_SIGNAL_SET_VERSION,source_cursor:options.sourceCursor,recency_evidence_fingerprint:fingerprint,generated_at:options.now,source:options.source,items:Object.freeze(rows.map(row=>Object.freeze(row)))})}function buildContextSignalSnapshot(items,options){return validateSnapshotOptions(options),snapshotFromCandidates(buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),options)}class JsonFileContextSignalStoreAdapter{filePath;constructor(filePath){if(typeof filePath!="string"||filePath.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=path.resolve(filePath)}async read(){try{return JSON.parse(await fs.readFile(this.filePath,"utf8"))}catch(error){if(isRecord(error)&&isFileAbsentError(error))return null;throw error}}async write(snapshot){const directory=path.dirname(this.filePath);await fs.mkdir(directory,{recursive:!0});const temporaryPath=path.join(directory,`.${path.basename(this.filePath)}.${randomUUID()}.tmp`);try{await fs.writeFile(temporaryPath,`${JSON.stringify(snapshot)}
2
- `,{encoding:"utf8",flag:"wx"}),await fs.rename(temporaryPath,this.filePath)}finally{try{await fs.rm(temporaryPath,{force:!0})}catch{}}}}class ContextSignalStore{adapter;constructor(adapter){this.adapter=adapter}async readOrRebuild(items,options){validateSnapshotOptions(options);const warnings=[];let snapshot=null;try{const serialized=await this.adapter.read();snapshot=parseContextSignalSnapshot(serialized),serialized!==null&&snapshot===null&&warnings.push("context_signal_store_invalid")}catch{warnings.push("context_signal_store_invalid")}const authoritativeIds=items.map(item=>item.id).sort((left,right)=>left.localeCompare(right)),snapshotIds=snapshot?.items.map(item=>item.id)??[],authoritativeCandidates=buildItemContextRelevanceCandidates(items,stableSnapshotOptions(items,options)),authoritativeFingerprint=recencyEvidenceFingerprint(authoritativeCandidates),fresh=snapshot!==null&&snapshot.source_cursor===options.sourceCursor&&snapshot.recency_evidence_fingerprint===authoritativeFingerprint&&snapshot.source===options.source&&snapshotIds.length===authoritativeIds.length&&snapshotIds.every((id,index)=>id===authoritativeIds[index]);let resolvedSnapshot;if(fresh&&snapshot!==null)resolvedSnapshot=snapshot;else{resolvedSnapshot=snapshotFromCandidates(authoritativeCandidates,options,authoritativeFingerprint);try{await this.adapter.write(resolvedSnapshot)}catch{warnings.push("context_signal_store_write_failed")}}const snapshotItemsById=new Map(resolvedSnapshot.items.map(item=>[item.id,item]));return{snapshot:resolvedSnapshot,candidates:authoritativeCandidates.map(candidate=>({...candidate,signals:{...candidate.signals,...snapshotItemsById.get(candidate.id)?.signals},signal_provenance:snapshotItemsById.get(candidate.id).signal_provenance})),cache_status:fresh?"fresh":"rebuilt",warnings,warning_details:warnings.map(warning=>CONTEXT_SIGNAL_STORE_WARNING_DETAILS[warning])}}}function fallbackWorkspaceCursor(items){const hash=createHash("sha256");for(const item of[...items].sort((left,right)=>left.id.localeCompare(right.id)))hash.update(JSON.stringify([item.id,item.updated_at,item.status,item.parent??null,item.priority??null,item.risk??null,(item.dependencies??[]).map(dependency=>dependency.id).sort(),item.comments?.length??0,item.notes?.length??0,item.learnings?.length??0,item.test_runs?.length??0]));return`scan:${hash.digest("hex")}`}async function readWorkspaceContextSignals(items,options){const hasSourceCursor=options.sourceCursor!==void 0,hasSource=options.source!==void 0;if(hasSourceCursor!==hasSource)throw new TypeError("Context signal source and source cursor must be provided together");if(options.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(options.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");const indexState=hasSourceCursor?null:await readItemMetadataDerivedIndexState(options.pmRoot),sourceCursor=options.sourceCursor??indexState?.source_cursor??fallbackWorkspaceCursor(items),source=options.source??(indexState===null?"scan_fallback":"derived_index"),store=new ContextSignalStore(new JsonFileContextSignalStoreAdapter(path.join(options.pmRoot,"runtime",options.storeKey?`context-signals-${options.storeKey}.json`:"context-signals.json"))),recencyEvidence=options.recencyEvidence??Object.fromEntries(Object.entries(await readLatestSubstantiveHistoryEvents(options.pmRoot,items.map(item=>item.id))).map(([id,event])=>[id,{source:"substantive_history",coordinate:event.entry.ts,history_op:event.entry.op,event_class:"substantive"}]));return store.readOrRebuild(items,{...options,recencyEvidence,sourceCursor,source})}export{CONTEXT_SIGNAL_SET_VERSION,CONTEXT_SIGNAL_STORE_FORMAT_VERSION,CONTEXT_SIGNAL_STORE_WARNING_DETAILS,ContextSignalStore,JsonFileContextSignalStoreAdapter,buildContextSignalSnapshot,parseContextSignalSnapshot,readWorkspaceContextSignals};
1
+ import{isFileAbsentError as T}from"../core/fs/fs-utils.js";import f from"node:fs/promises";import m from"node:path";import{createHash as w,randomUUID as N}from"node:crypto";import{buildItemContextRelevanceCandidates as v}from"./context-relevance.js";import{readItemMetadataDerivedIndexState as I}from"./item-metadata-index.js";import{readLatestSubstantiveHistoryEvents as R}from"../core/history/event-index.js";import{canonicalizeContextRecencyCoordinate as A}from"./context/recency.js";const h=3,g=2,b=["recency","activity_density","graph_proximity","priority_pressure","risk_pressure","knowledge_density"],j=new Set(["substantive_history","release_cohort","created_at"]),k={context_signal_store_invalid:{code:"context_signal_store_invalid",meaning:"The persisted context-signal snapshot was unreadable or invalid and was rebuilt from authoritative items.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot can be loaded without the warning."},context_signal_store_stale:{code:"context_signal_store_stale",meaning:"The persisted context-signal snapshot did not match the authoritative cursor or item corpus and was rebuilt.",recovery_command:"pm context",recovery_effect:"Re-read context and confirm the rebuilt snapshot is now fresh."},context_signal_store_write_failed:{code:"context_signal_store_write_failed",meaning:"Context signals were rebuilt in memory, but the derived snapshot could not be persisted.",recovery_command:"pm context",recovery_effect:"Retry the derived snapshot write and confirm the warning clears after storage access is restored."}};function d(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function S(e){return typeof e=="number"&&Number.isFinite(e)&&e>=0&&e<=1}function z(e){const t={};for(const r of b){const s=e[r];if(s!==void 0){if(!S(s))throw new TypeError(`Context relevance signal ${r} must be a finite number from 0 to 1`);t[r]=s}}return t}function F(e,t){const r=e.map(n=>[n.id,t(n)]),s=Math.max(0,...r.map(([,n])=>n));return Object.fromEntries(r.map(([n,i])=>[n,s===0?0:i/s]))}function D(e){const t=new Map(e.map(n=>[n.id,0])),r=n=>{t.set(n,(t.get(n)??0)+1)};for(const n of e){typeof n.parent=="string"&&n.parent.trim()&&(r(n.id),r(n.parent.trim()));for(const i of n.dependencies??[])typeof i.id!="string"||!i.id.trim()||(r(n.id),r(i.id.trim()))}const s=Math.max(0,...t.values());return Object.fromEntries(e.map(n=>[n.id,s===0?0:t.get(n.id)/s]))}function C(e,t){return{...t,activityDensity:t.activityDensity??F(e,r=>(r.comments?.length??0)+(r.notes?.length??0)+(r.learnings?.length??0)+(r.test_runs?.length??0)),graphProximity:t.graphProximity??D(e)}}function y(e){const t=w("sha256");for(const{id:r,signal_provenance:{recency:s}}of[...e].sort((n,i)=>n.id.localeCompare(i.id)))t.update(JSON.stringify([r,s.source,s.coordinate,s.history_op??null,s.event_class??null]));return`sha256:${t.digest("hex")}`}function P(e){if(!d(e))return null;const t=e.signal_provenance;if(![typeof e.id=="string",d(e.signals),d(t)].every(Boolean))return null;const r=t.recency;if(!d(r))return null;const s=A(r.coordinate);if(s===null)return null;const n=new Set(b),i=Object.entries(e.signals);return!i.every(([a,c])=>n.has(a)&&S(c))||![typeof r.source=="string"&&j.has(r.source),["undefined","string"].includes(typeof r.history_op),[void 0,"substantive","maintenance"].includes(r.event_class),r.source==="substantive_history"?r.event_class===void 0||r.event_class==="substantive":r.history_op===void 0&&r.event_class===void 0].every(Boolean)?null:{id:e.id,signals:Object.fromEntries(i),signal_provenance:{recency:{source:r.source,coordinate:s,history_op:r.history_op,event_class:r.event_class}}}}function $(e,t){const r=Array.from(e,P);if(r.some(n=>n===null))return null;const s=r;return new Set(s.map(n=>n.id)).size!==s.length||s.some(n=>n.id.trim().length===0)||t!==y(s)?null:s.sort((n,i)=>n.id.localeCompare(i.id))}function M(e){if(!d(e)||e.format_version!==h||e.signal_set_version!==g||typeof e.source_cursor!="string"||e.source_cursor.trim().length===0||typeof e.recency_evidence_fingerprint!="string"||!/^sha256:[a-f0-9]{64}$/u.test(e.recency_evidence_fingerprint)||typeof e.generated_at!="string"||!Number.isFinite(Date.parse(e.generated_at))||e.source!=="derived_index"&&e.source!=="scan_fallback"||!Array.isArray(e.items))return null;const t=$(e.items,e.recency_evidence_fingerprint);return t===null?null:{format_version:h,signal_set_version:g,source_cursor:e.source_cursor,recency_evidence_fingerprint:e.recency_evidence_fingerprint,generated_at:e.generated_at,source:e.source,items:t}}function E(e){if(typeof e.sourceCursor!="string"||e.sourceCursor.trim().length===0)throw new TypeError("Context signal source cursor must be non-empty");if(!Number.isFinite(Date.parse(e.now)))throw new TypeError("Context signal snapshot clock must be a valid timestamp");if(e.source!=="derived_index"&&e.source!=="scan_fallback")throw new TypeError("Context signal snapshot source must be derived_index or scan_fallback")}function O(e,t,r=y(e)){const s=e.map(({id:i})=>i);if(new Set(s).size!==s.length||s.some(i=>i.trim().length===0))throw new TypeError("Context signal snapshot item IDs must be unique and non-empty");const n=e.map(({id:i,signals:a,signal_provenance:c})=>({id:i,signals:z(a),signal_provenance:c})).sort((i,a)=>i.id.localeCompare(a.id));return Object.freeze({format_version:h,signal_set_version:g,source_cursor:t.sourceCursor,recency_evidence_fingerprint:r,generated_at:t.now,source:t.source,items:Object.freeze(n.map(i=>Object.freeze(i)))})}function Y(e,t){return E(t),O(v(e,C(e,t)),t)}class G{filePath;constructor(t){if(typeof t!="string"||t.trim().length===0)throw new TypeError("Context signal store path must be non-empty");this.filePath=m.resolve(t)}async read(){try{return JSON.parse(await f.readFile(this.filePath,"utf8"))}catch(t){if(d(t)&&T(t))return null;throw t}}async write(t){const r=m.dirname(this.filePath);await f.mkdir(r,{recursive:!0});const s=m.join(r,`.${m.basename(this.filePath)}.${N()}.tmp`);try{await f.writeFile(s,`${JSON.stringify(t)}
2
+ `,{encoding:"utf8",flag:"wx"}),await f.rename(s,this.filePath)}finally{try{await f.rm(s,{force:!0})}catch{}}}}class L{adapter;constructor(t){this.adapter=t}async readOrRebuild(t,r){E(r);const s=[];let n=null;try{const o=await this.adapter.read();n=M(o),o!==null&&n===null&&s.push("context_signal_store_invalid")}catch{s.push("context_signal_store_invalid")}const i=t.map(o=>o.id).sort((o,_)=>o.localeCompare(_)),a=n?.items.map(o=>o.id)??[],c=v(t,C(t,r)),p=y(c),l=n!==null&&n.source_cursor===r.sourceCursor&&n.recency_evidence_fingerprint===p&&n.source===r.source&&a.length===i.length&&a.every((o,_)=>o===i[_]);let u;if(l&&n!==null)u=n;else{u=O(c,r,p);try{await this.adapter.write(u)}catch{s.push("context_signal_store_write_failed")}}const x=new Map(u.items.map(o=>[o.id,o]));return{snapshot:u,candidates:c.map(o=>({...o,signals:{...o.signals,...x.get(o.id)?.signals},signal_provenance:x.get(o.id).signal_provenance})),cache_status:l?"fresh":"rebuilt",warnings:s,warning_details:s.map(o=>k[o])}}}function J(e){const t=w("sha256");for(const r of[...e].sort((s,n)=>s.id.localeCompare(n.id)))t.update(JSON.stringify([r.id,r.updated_at,r.status,r.parent??null,r.priority??null,r.risk??null,(r.dependencies??[]).map(s=>s.id).sort(),r.comments?.length??0,r.notes?.length??0,r.learnings?.length??0,r.test_runs?.length??0]));return`scan:${t.digest("hex")}`}async function Q(e,t){const r=t.sourceCursor!==void 0,s=t.source!==void 0;if(r!==s)throw new TypeError("Context signal source and source cursor must be provided together");if(t.storeKey!==void 0&&!/^[a-z0-9](?:[a-z0-9_-]*[a-z0-9])?$/u.test(t.storeKey))throw new TypeError("Context signal store key must be a filesystem-safe identifier");const n=r?null:await I(t.pmRoot),i=t.sourceCursor??n?.source_cursor??J(e),a=t.source??(n===null?"scan_fallback":"derived_index"),c=new L(new G(m.join(t.pmRoot,"runtime",t.storeKey?`context-signals-${t.storeKey}.json`:"context-signals.json"))),p=t.recencyEvidence??Object.fromEntries(Object.entries(await R(t.pmRoot,e.map(l=>l.id))).map(([l,u])=>[l,{source:"substantive_history",coordinate:u.entry.ts,history_op:u.entry.op,event_class:"substantive"}]));return c.readOrRebuild(e,{...t,recencyEvidence:p,sourceCursor:i,source:a})}export{g as CONTEXT_SIGNAL_SET_VERSION,h as CONTEXT_SIGNAL_STORE_FORMAT_VERSION,k as CONTEXT_SIGNAL_STORE_WARNING_DETAILS,L as ContextSignalStore,G as JsonFileContextSignalStoreAdapter,Y as buildContextSignalSnapshot,M as parseContextSignalSnapshot,Q as readWorkspaceContextSignals};
3
3
  //# sourceMappingURL=context-signal-store.js.map
@@ -1,2 +1,2 @@
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]="e76b38ce-b2aa-589b-9d17-0952eca9e7a2")}catch{}})();import{randomUUID}from"node:crypto";import{appendEvents,readEvents,resolveNow,ContextUsageValidationError,CONTEXT_USAGE_LIMITS}from"./context/usage-ledger.js";import{ContextUsageValidationError as ContextUsageValidationError2,CONTEXT_USAGE_LIMITS as CONTEXT_USAGE_LIMITS2}from"./context/usage-ledger.js";const DAY_MS=864e5,CONTEXT_USAGE_SERVING_RECEIPT=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function asObjectRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)?value:null}function attachContextUsageServingReceipt(result,receipt){const record=asObjectRecord(result);record!==null&&receipt!==null&&(record[CONTEXT_USAGE_SERVING_RECEIPT]=receipt)}function propagateContextUsageServingReceipt(source,target){const sourceRecord=asObjectRecord(source),targetRecord=asObjectRecord(target),receipt=sourceRecord?.[CONTEXT_USAGE_SERVING_RECEIPT];targetRecord!==null&&receipt!==void 0&&(targetRecord[CONTEXT_USAGE_SERVING_RECEIPT]=receipt)}function receiptFromResult(result){return asObjectRecord(result)?.[CONTEXT_USAGE_SERVING_RECEIPT]??null}function resultReceiptSaysOmitted(result){const record=asObjectRecord(result);for(const key of["read_output","context_intent"])if(asObjectRecord(record?.[key])?.result_omitted===!0)return!0;return!1}function addContextUsageId(ids,value){typeof value=="string"&&value.trim().length>0&&ids.add(value.trim())}function addContextUsageDirectRows(ids,value){if(Array.isArray(value))for(const row of value)addContextUsageId(ids,asObjectRecord(row)?.id)}function addContextUsageIdList(ids,value){if(Array.isArray(value))for(const itemId of value)addContextUsageId(ids,itemId)}function collectNextResultItemIds(record,ids){const rows=asObjectRecord(record.recommended)===null?[]:[record.recommended];for(const key of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(record[key])&&rows.push(...record[key]);for(const value of rows){const row=asObjectRecord(value);addContextUsageId(ids,row?.id);for(const blocker of Array.isArray(row?.blockers)?row.blockers:[])addContextUsageId(ids,asObjectRecord(blocker)?.id);for(const unblockedId of Array.isArray(row?.unblocks)?row.unblocks:[])addContextUsageId(ids,unblockedId)}}function collectContextResultItemIds(record,ids){for(const key of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])addContextUsageDirectRows(ids,record[key]);for(const value of Array.isArray(record.blockers)?record.blockers:[])addContextUsageId(ids,asObjectRecord(value)?.blocked_by);collectContextNestedItemIds(record,ids)}function collectContextNestedItemIds(record,ids){for(const value of Array.isArray(record.hierarchy)?record.hierarchy:[]){const node=asObjectRecord(value);addContextUsageId(ids,node?.id),addContextUsageDirectRows(ids,node?.children)}for(const key of["files","workload"])for(const value of Array.isArray(record[key])?record[key]:[])addContextUsageIdList(ids,asObjectRecord(value)?.items);const agenda=asObjectRecord(record.agenda);for(const value of Array.isArray(agenda?.events)?agenda.events:[])addContextUsageId(ids,asObjectRecord(value)?.item_id);const tests=asObjectRecord(record.tests);addContextUsageIdList(ids,tests?.items_failing)}function collectContextUsageDeliveredItemIds(result,surface){const record=asObjectRecord(result);if(record===null||resultReceiptSaysOmitted(result))return[];const ids=new Set;return surface==="next"?collectNextResultItemIds(record,ids):collectContextResultItemIds(record,ids),[...ids]}async function finalizeContextUsageDelivery(options){const receipt=receiptFromResult(options.result);if(receipt===null)return!1;const resultOmitted=resultReceiptSaysOmitted(options.result);return await recordContextUsageDelivery({pmRoot:options.pmRoot,receipt,deliveredItemIds:collectContextUsageDeliveredItemIds(options.result,receipt.surface),resultOmitted}),!0}async function recordContextUsageServing(options){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",options.enabled===!1].includes(!0))return null;if(!options.author.trim()||options.rows.some(row=>!row.id.trim()||!Number.isInteger(row.rank)||row.rank<1))throw new ContextUsageValidationError("Context usage serving requires an author and valid ranked rows");const normalizedRows=options.rows.map(row=>({id:row.id.trim(),rank:row.rank,included:row.included}));if(new Set(normalizedRows.map(row=>row.id)).size!==normalizedRows.length)throw new ContextUsageValidationError("Context usage serving requires unique normalized row ids");const recordedRows=normalizedRows.slice(0,CONTEXT_USAGE_LIMITS.max_serving_rows),receipt={serve_id:randomUUID(),author:options.author.trim(),surface:options.surface,rows:normalizedRows,recorded_item_ids:recordedRows.map(row=>row.id)};return receipt.storage=await appendEvents(options,[{kind:"serve",schema_version:2,serve_id:receipt.serve_id,at:resolveNow(options).iso,author:options.author.trim(),surface:options.surface,profile:options.profile.trim()||"balanced",rows:recordedRows,candidate_count:normalizedRows.length,omitted_row_count:normalizedRows.length-recordedRows.length,result_omitted:!1,packed_item_ids:recordedRows.filter(row=>row.included).map(row=>row.id)}]),receipt}async function recordContextUsageDelivery(options){if(options.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)return;const rankedIds=new Set(options.receipt.rows.map(row=>row.id)),deliveredItemIds=[...new Set(options.deliveredItemIds.map(id=>id.trim()))];if(deliveredItemIds.some(id=>id.length===0||!rankedIds.has(id))||options.resultOmitted&&deliveredItemIds.length>0)throw new ContextUsageValidationError("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");const recordedIds=new Set(options.receipt.recorded_item_ids??options.receipt.rows.map(row=>row.id)),delivery={kind:"delivery",schema_version:2,serve_id:options.receipt.serve_id,at:resolveNow(options).iso,author:options.receipt.author,surface:options.receipt.surface,result_omitted:options.resultOmitted,delivered_item_ids:deliveredItemIds.filter(id=>recordedIds.has(id))};await appendEvents(options,[delivery],delivery.serve_id)}async function recordContextUsageTouch(options){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)){if(!options.author.trim()||!options.itemId.trim()||!options.intent.trim())throw new ContextUsageValidationError("Context usage touch requires author, itemId, and intent");await appendEvents(options,[{kind:"touch",at:resolveNow(options).iso,author:options.author.trim(),item_id:options.itemId.trim(),intent:options.intent.trim()}])}}async function recordContextUsageTouches(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1||options.itemIds.length===0)return;const author=options.author.trim(),intent=options.intent.trim();if(!author||!intent)throw new ContextUsageValidationError("Context usage touch requires author and intent");const itemIds=new Set;for(const itemId of options.itemIds){if(typeof itemId!="string")throw new ContextUsageValidationError("Context usage touch requires string itemIds");const trimmedId=itemId.trim();if(!trimmedId)throw new ContextUsageValidationError("Context usage touch requires non-empty itemId");itemIds.add(trimmedId)}const at=resolveNow(options).iso,events=[...itemIds].map(itemId=>({kind:"touch",at,author,item_id:itemId,intent}));await appendEvents(options,events)}function findTouchTimeInHorizon(touches,itemId,servedAt,horizonMs){return touches.find(({entry,time})=>entry.item_id===itemId&&time>=servedAt&&time-servedAt<=horizonMs)?.time}function firstDeliveriesByServeId(events,author){const deliveries=new Map;for(const event of events)event.kind==="delivery"&&event.schema_version===2&&event.author===author&&!deliveries.has(event.serve_id)&&deliveries.set(event.serve_id,event);return deliveries}async function readContextUsageAffinity(options){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||options.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};const events=await readEvents(options),now=resolveNow(options).ms,horizonMs=(options.horizonHours??24)*36e5;if(![Number.isFinite(horizonMs),horizonMs>0].every(Boolean))throw new ContextUsageValidationError("Context usage horizonHours must be positive");const author=options.author.trim(),touches=events.filter(event=>event.kind==="touch").filter(event=>event.author===author).map(entry=>({entry,time:Date.parse(entry.at)})),scores=new Map;let servingEvents=0,untrustedServingEvents=0,positiveJudgments=0;const deliveries=firstDeliveriesByServeId(events,author);events.filter(event=>event.kind==="serve").filter(event=>event.author===author).forEach(event=>{if(![event.schema_version===2,!!event.serve_id].every(Boolean)){untrustedServingEvents+=1;return}servingEvents+=1;const servedAt=Date.parse(event.at),delivery=deliveries.get(event.serve_id),deliveredIds=new Set(delivery?.delivered_item_ids??[]);for(const row of event.rows){if(!deliveredIds.has(row.id))continue;const touchTime=findTouchTimeInHorizon(touches,row.id,servedAt,horizonMs);if(touchTime===void 0)continue;positiveJudgments+=1;const ageDays=Math.max(0,(now-touchTime)/DAY_MS);scores.set(row.id,(scores.get(row.id)??0)+Math.exp(-ageDays/14))}});const maximum=Math.max(0,...scores.values());return{affinity:Object.fromEntries([...scores.entries()].map(([id,score])=>[id,maximum===0?.05:.05+.95*score/maximum])),positive_judgments:positiveJudgments,serving_events:servingEvents,untrusted_serving_events:untrustedServingEvents}}export{CONTEXT_USAGE_LIMITS2 as CONTEXT_USAGE_LIMITS,ContextUsageValidationError2 as ContextUsageValidationError,attachContextUsageServingReceipt,collectContextUsageDeliveredItemIds,finalizeContextUsageDelivery,propagateContextUsageServingReceipt,readContextUsageAffinity,recordContextUsageDelivery,recordContextUsageServing,recordContextUsageTouch,recordContextUsageTouches};
1
+ import{randomUUID as p}from"node:crypto";import{appendEvents as _,readEvents as T,resolveNow as f,ContextUsageValidationError as d,CONTEXT_USAGE_LIMITS as U}from"./context/usage-ledger.js";import{ContextUsageValidationError as Z,CONTEXT_USAGE_LIMITS as $}from"./context/usage-ledger.js";const D=864e5,h=Symbol.for("@unbrained/pm-cli/context-usage-serving-receipt");function a(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}function j(e,t){const r=a(e);r!==null&&t!==null&&(r[h]=t)}function H(e,t){const r=a(e),i=a(t),n=r?.[h];i!==null&&n!==void 0&&(i[h]=n)}function R(e){return a(e)?.[h]??null}function x(e){const t=a(e);for(const r of["read_output","context_intent"])if(a(t?.[r])?.result_omitted===!0)return!0;return!1}function u(e,t){typeof t=="string"&&t.trim().length>0&&e.add(t.trim())}function A(e,t){if(Array.isArray(t))for(const r of t)u(e,a(r)?.id)}function k(e,t){if(Array.isArray(t))for(const r of t)u(e,r)}function M(e,t){const r=a(e.recommended)===null?[]:[e.recommended];for(const i of["ready","decision_needed","gate_needed","containers","blocked","held_by_others"])Array.isArray(e[i])&&r.push(...e[i]);for(const i of r){const n=a(i);u(t,n?.id);for(const s of Array.isArray(n?.blockers)?n.blockers:[])u(t,a(s)?.id);for(const s of Array.isArray(n?.unblocks)?n.unblocks:[])u(t,s)}}function N(e,t){for(const r of["high_level","low_level","blocked_fallback","recently_created","unparented","activity","progress","blockers","staleness"])A(t,e[r]);for(const r of Array.isArray(e.blockers)?e.blockers:[])u(t,a(r)?.blocked_by);O(e,t)}function O(e,t){for(const n of Array.isArray(e.hierarchy)?e.hierarchy:[]){const s=a(n);u(t,s?.id),A(t,s?.children)}for(const n of["files","workload"])for(const s of Array.isArray(e[n])?e[n]:[])k(t,a(s)?.items);const r=a(e.agenda);for(const n of Array.isArray(r?.events)?r.events:[])u(t,a(n)?.item_id);const i=a(e.tests);k(t,i?.items_failing)}function z(e,t){const r=a(e);if(r===null||x(e))return[];const i=new Set;return t==="next"?M(r,i):N(r,i),[...i]}async function V(e){const t=R(e.result);if(t===null)return!1;const r=x(e.result);return await B({pmRoot:e.pmRoot,receipt:t,deliveredItemIds:z(e.result,t.surface),resultOmitted:r}),!0}async function F(e){if([process.env.PM_CONTEXT_USAGE_DISABLED==="1",e.enabled===!1].includes(!0))return null;if(!e.author.trim()||e.rows.some(n=>!n.id.trim()||!Number.isInteger(n.rank)||n.rank<1))throw new d("Context usage serving requires an author and valid ranked rows");const t=e.rows.map(n=>({id:n.id.trim(),rank:n.rank,included:n.included}));if(new Set(t.map(n=>n.id)).size!==t.length)throw new d("Context usage serving requires unique normalized row ids");const r=t.slice(0,U.max_serving_rows),i={serve_id:p(),author:e.author.trim(),surface:e.surface,rows:t,recorded_item_ids:r.map(n=>n.id)};return i.storage=await _(e,[{kind:"serve",schema_version:2,serve_id:i.serve_id,at:f(e).iso,author:e.author.trim(),surface:e.surface,profile:e.profile.trim()||"balanced",rows:r,candidate_count:t.length,omitted_row_count:t.length-r.length,result_omitted:!1,packed_item_ids:r.filter(n=>n.included).map(n=>n.id)}]),i}async function B(e){if(e.receipt===null||process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return;const t=new Set(e.receipt.rows.map(s=>s.id)),r=[...new Set(e.deliveredItemIds.map(s=>s.trim()))];if(r.some(s=>s.length===0||!t.has(s))||e.resultOmitted&&r.length>0)throw new d("Context usage delivery requires emitted ranked ids and zero ids for an omitted result");const i=new Set(e.receipt.recorded_item_ids??e.receipt.rows.map(s=>s.id)),n={kind:"delivery",schema_version:2,serve_id:e.receipt.serve_id,at:f(e).iso,author:e.receipt.author,surface:e.receipt.surface,result_omitted:e.resultOmitted,delivered_item_ids:r.filter(s=>i.has(s))};await _(e,[n],n.serve_id)}async function J(e){if(!(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)){if(!e.author.trim()||!e.itemId.trim()||!e.intent.trim())throw new d("Context usage touch requires author, itemId, and intent");await _(e,[{kind:"touch",at:f(e).iso,author:e.author.trim(),item_id:e.itemId.trim(),intent:e.intent.trim()}])}}async function Y(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1||e.itemIds.length===0)return;const t=e.author.trim(),r=e.intent.trim();if(!t||!r)throw new d("Context usage touch requires author and intent");const i=new Set;for(const c of e.itemIds){if(typeof c!="string")throw new d("Context usage touch requires string itemIds");const l=c.trim();if(!l)throw new d("Context usage touch requires non-empty itemId");i.add(l)}const n=f(e).iso,s=[...i].map(c=>({kind:"touch",at:n,author:t,item_id:c,intent:r}));await _(e,s)}function G(e,t,r,i){return e.find(({entry:n,time:s})=>n.item_id===t&&s>=r&&s-r<=i)?.time}function q(e,t){const r=new Map;for(const i of e)i.kind==="delivery"&&i.schema_version===2&&i.author===t&&!r.has(i.serve_id)&&r.set(i.serve_id,i);return r}async function K(e){if(process.env.PM_CONTEXT_USAGE_DISABLED==="1"||e.enabled===!1)return{affinity:{},positive_judgments:0,serving_events:0,untrusted_serving_events:0};const t=await T(e),r=f(e).ms,i=(e.horizonHours??24)*36e5;if(![Number.isFinite(i),i>0].every(Boolean))throw new d("Context usage horizonHours must be positive");const n=e.author.trim(),s=t.filter(o=>o.kind==="touch").filter(o=>o.author===n).map(o=>({entry:o,time:Date.parse(o.at)})),c=new Map;let l=0,g=0,y=0;const C=q(t,n);t.filter(o=>o.kind==="serve").filter(o=>o.author===n).forEach(o=>{if(![o.schema_version===2,!!o.serve_id].every(Boolean)){g+=1;return}l+=1;const v=Date.parse(o.at),E=C.get(o.serve_id),S=new Set(E?.delivered_item_ids??[]);for(const m of o.rows){if(!S.has(m.id))continue;const I=G(s,m.id,v,i);if(I===void 0)continue;y+=1;const b=Math.max(0,(r-I)/D);c.set(m.id,(c.get(m.id)??0)+Math.exp(-b/14))}});const w=Math.max(0,...c.values());return{affinity:Object.fromEntries([...c.entries()].map(([o,v])=>[o,w===0?.05:.05+.95*v/w])),positive_judgments:y,serving_events:l,untrusted_serving_events:g}}export{$ as CONTEXT_USAGE_LIMITS,Z as ContextUsageValidationError,j as attachContextUsageServingReceipt,z as collectContextUsageDeliveredItemIds,V as finalizeContextUsageDelivery,H as propagateContextUsageServingReceipt,K as readContextUsageAffinity,B as recordContextUsageDelivery,F as recordContextUsageServing,J as recordContextUsageTouch,Y as recordContextUsageTouches};
2
2
  //# sourceMappingURL=context-usage.js.map
@@ -1,2 +1,2 @@
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]="8a0c0e0d-7d3b-55c6-984b-b6570362cf78")}catch{}})();function unavailable(requested,reason){return{requested_tokens:requested,feasible_tokens:null,minimum_feasible_tokens:null,minimum_status:"unavailable",basis:"canonical_retry",reason}}function nativeUpperBound(input,probe){let upper=Math.min(Number.MAX_SAFE_INTEGER,Math.max(input.initialBudget,input.requested+1));for(let attempt=0;attempt<16;attempt+=1){if(probe(upper)!=="native_floor")return upper;if(upper===Number.MAX_SAFE_INTEGER)return;upper=Math.min(Number.MAX_SAFE_INTEGER,upper*2)}}function findContextBudgetRecovery(input){if(input.workUnits>1e6)return unavailable(input.requested,"query_cost_limit");const cache=new Map;let feasible;const probe=tokens=>{let outcome=cache.get(tokens);return outcome===void 0&&(outcome=input.probe(tokens),cache.set(tokens,outcome)),outcome==="fits"&&(feasible=Math.min(feasible??tokens,tokens)),outcome},upper=nativeUpperBound(input,probe);if(upper===void 0)return unavailable(input.requested,"search_limit");let left=0,right=upper;for(let step=0;step<24&&right-left>1;step+=1){const middle=left+Math.floor((right-left)/2);probe(middle)==="native_floor"?left=middle:right=middle}const verificationLimit=Math.min(feasible??upper,4096,Math.floor(1e5/Math.max(1,input.workUnits)));for(let tokens=1;tokens<=verificationLimit;tokens+=1)if(probe(tokens)==="fits")return{requested_tokens:input.requested,feasible_tokens:tokens,minimum_feasible_tokens:tokens,minimum_status:"exact",basis:"canonical_retry"};return feasible===void 0?unavailable(input.requested,"output_constraints"):{requested_tokens:input.requested,feasible_tokens:feasible,minimum_feasible_tokens:null,minimum_status:"feasible_only",basis:"canonical_retry"}}export{findContextBudgetRecovery};
1
+ function l(e,r){return{requested_tokens:e,feasible_tokens:null,minimum_feasible_tokens:null,minimum_status:"unavailable",basis:"canonical_retry",reason:r}}function _(e,r){let i=Math.min(Number.MAX_SAFE_INTEGER,Math.max(e.initialBudget,e.requested+1));for(let s=0;s<16;s+=1){if(r(i)!=="native_floor")return i;if(i===Number.MAX_SAFE_INTEGER)return;i=Math.min(Number.MAX_SAFE_INTEGER,i*2)}}function m(e){if(e.workUnits>1e6)return l(e.requested,"query_cost_limit");const r=new Map;let i;const s=t=>{let n=r.get(t);return n===void 0&&(n=e.probe(t),r.set(t,n)),n==="fits"&&(i=Math.min(i??t,t)),n},o=_(e,s);if(o===void 0)return l(e.requested,"search_limit");let a=0,u=o;for(let t=0;t<24&&u-a>1;t+=1){const n=a+Math.floor((u-a)/2);s(n)==="native_floor"?a=n:u=n}const f=Math.min(i??o,4096,Math.floor(1e5/Math.max(1,e.workUnits)));for(let t=1;t<=f;t+=1)if(s(t)==="fits")return{requested_tokens:e.requested,feasible_tokens:t,minimum_feasible_tokens:t,minimum_status:"exact",basis:"canonical_retry"};return i===void 0?l(e.requested,"output_constraints"):{requested_tokens:e.requested,feasible_tokens:i,minimum_feasible_tokens:null,minimum_status:"feasible_only",basis:"canonical_retry"}}export{m as findContextBudgetRecovery};
2
2
  //# sourceMappingURL=context-budget-recovery.js.map
@@ -1,2 +1,2 @@
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]="196b7f2d-b09b-5432-b4ef-9cdf82e92731")}catch{}})();import{assertInitializedTracker}from"./environment/tracker-preflight.js";import{getActiveCommandContext,getActiveExtensionRegistrations}from"../core/extensions/index.js";import{resolveItemTypeRegistry}from"../core/item/type-registry.js";import{isTerminalStatus}from"../core/item/status.js";import{resolveRuntimeStatusRegistry}from"../core/schema/runtime-schema.js";import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{formatBuiltInOutput}from"../core/output/output.js";import{listAllItemMetadataLight,locateItem,readLocatedItem}from"../core/store/item-store.js";import{resolvePmRoot}from"../core/store/paths.js";import{readSettings}from"../core/store/settings.js";import{estimatePmOutputTokens}from"./cli-contracts/agent-output-contracts.js";import{renderPmCommand}from"./command-line.js";import{createPmCliExpectedError}from"./errors.js";import{isReadOutputBudgetExceeded,normalizeReadOutputIncludeModeOptions,PM_READ_OUTPUT_SURFACE_CONTRACTS}from"./read-output-contracts.js";import{READ_OUTPUT_INVOCATION_PROVENANCE}from"./read-output/provenance.js";import{attachReadOutputContracts}from"./context-intent-contracts.js";import{attachOutputTokenAccounting}from"./output-token-accounting.js";import{assertProjectionModeChoice}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph,collectDanglingDependencyReferences,resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./graph/cache.js";import{buildRelationshipContext,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET}from"./relationship-context.js";import{createRelationshipKindRegistry}from"./relationships.js";const DEPS_FORMAT_VALUES=["tree","graph","context"],DEPS_COLLAPSE_VALUES=["none","repeated"],DEPS_DIRECTION_VALUES=["outgoing","incoming","both"],DEFAULT_DEPS_TREE_MAX_DEPTH=32,DEFAULT_DEPS_TREE_NODE_LIMIT=200,DEFAULT_DEPS_TREE_EDGE_LIMIT=400,DEFAULT_DEPS_TREE_TOKEN_BUDGET=16e3;function parseFormat(raw){const candidate=raw?.trim().toLowerCase()??"tree";if(DEPS_FORMAT_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --format value "${raw}". Use "tree", "graph", or "context".`,EXIT_CODE.USAGE)}function parsePositiveInteger(raw,flag){if(raw===void 0)return;const value=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(value)||value<1)throw new PmCliError(`Invalid --${flag} value "${raw}". Use a positive integer.`,EXIT_CODE.USAGE);return value}function parseMaxDepth(raw){if(raw===void 0)return;const normalized=typeof raw=="number"?raw:Number(raw.trim());if(!Number.isInteger(normalized)||normalized<0)throw new PmCliError(`Invalid --max-depth value "${raw}". Use a non-negative integer.`,EXIT_CODE.USAGE);return normalized}function parseCollapse(raw){const candidate=raw?.trim().toLowerCase()??"none";if(DEPS_COLLAPSE_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --collapse value "${raw}". Use "none" or "repeated".`,EXIT_CODE.USAGE)}function parseDirection(raw){const candidate=raw?.trim().toLowerCase()??"both";if(DEPS_DIRECTION_VALUES.includes(candidate))return candidate;throw new PmCliError(`Invalid --direction value "${raw}". Use "outgoing", "incoming", or "both".`,EXIT_CODE.USAGE)}function parseKinds(raw,registry=createRelationshipKindRegistry()){if(raw===void 0)return;const values=(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0);if(values.length===0)return;const kinds=new Set;for(const value of values){const definition=registry.resolve(value);if(!definition){const known=registry.list().map(entry=>entry.kind).join(", ");throw new PmCliError(`Invalid --kind value "${value}". Registered kinds: ${known}.`,EXIT_CODE.USAGE)}kinds.add(definition.kind)}return[...kinds].sort()}function normalizeDependencies(dependencies){if(!dependencies||dependencies.length===0)return[];const sorted=dependencies.map(({id,kind})=>({id:id.trim(),kind:kind.trim().toLowerCase()})).sort((left,right)=>{const byKind=left.kind.localeCompare(right.kind);return byKind!==0?byKind:left.id.localeCompare(right.id)}),deduped=new Map;for(const dependency of sorted){const key=`${dependency.kind.toLowerCase()}::${dependency.id.toLowerCase()}`;deduped.has(key)||deduped.set(key,{id:dependency.id,kind:dependency.kind})}return[...deduped.values()]}function toIndexedItem(item){return{id:item.id,title:item.title,type:item.type,status:item.status,dependencies:normalizeDependencies(item.dependencies)}}function estimateTreeNodeTokens(node){return estimatePmOutputTokens(new TextEncoder().encode(JSON.stringify({...node,dependencies:void 0})).byteLength)}function appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth){for(const dependency of item.dependencies){const edgeTokens=Math.max(1,Math.ceil(JSON.stringify({from:baseNode.id,to:dependency.id,kind:dependency.kind}).length/3));if(budget.nodes>=budget.nodeLimit){baseNode.truncated=!0,budget.reasons.add("node_limit");break}if(budget.edges>=budget.edgeLimit){baseNode.truncated=!0,budget.reasons.add("edge_limit");break}if(budget.estimatedTokens+edgeTokens>=budget.tokenBudget){baseNode.truncated=!0,budget.reasons.add("token_budget");break}budget.edges+=1,budget.estimatedTokens+=edgeTokens,baseNode.dependencies.push(toTreeNode(dependency.id,index,nextLineage,maxDepth,collapse,expanded,budget,depth+1,dependency.kind))}}function shouldStopTreeNodeExpansion(node,item,lookupId,maxDepth,collapse,expanded,budget,depth){return budget.estimatedTokens>=budget.tokenBudget&&item?.dependencies.length?(node.truncated=!0,budget.reasons.add("token_budget"),!0):!item||node.cycle?!0:maxDepth!==void 0&&depth>=maxDepth?(item.dependencies.length>0&&(node.truncated=!0,budget.reasons.add("max_depth")),!0):collapse==="repeated"&&expanded.has(lookupId)?(node.collapsed=!0,!0):!1}function toTreeNode(id,index,lineage,maxDepth,collapse,expanded,budget,depth=0,via){const lookupId=id.trim().toLowerCase(),item=index.get(lookupId),baseNode={id:item?.id??id,title:item?.title,type:item?.type,status:item?.status,via,missing:!item,cycle:lineage.has(lookupId),dependencies:[]};if(budget.nodes+=1,budget.estimatedTokens+=estimateTreeNodeTokens(baseNode),shouldStopTreeNodeExpansion(baseNode,item,lookupId,maxDepth,collapse,expanded,budget,depth))return baseNode;collapse==="repeated"&&expanded.add(lookupId);const nextLineage=new Set(lineage);return nextLineage.add(lookupId),appendTreeDependencies(baseNode,item,index,nextLineage,maxDepth,collapse,expanded,budget,depth),baseNode}function mergeGraphNode(existing,candidate){return!existing||existing.missing&&!candidate.missing?candidate:{...existing,title:existing.title??candidate.title,type:existing.type??candidate.type,status:existing.status??candidate.status}}function toGraph(root){const nodesById=new Map,edgesByKey=new Map,pending=[root];for(;pending.length>0;){const node=pending.pop();nodesById.set(node.id,mergeGraphNode(nodesById.get(node.id),{id:node.id,title:node.title,type:node.type,status:node.status,missing:node.missing}));for(const child of node.dependencies){nodesById.set(child.id,mergeGraphNode(nodesById.get(child.id),{id:child.id,title:child.title,type:child.type,status:child.status,missing:child.missing}));const relationKind=child.via??"related",edgeKey=`${node.id}::${child.id}::${relationKind}`;edgesByKey.has(edgeKey)||edgesByKey.set(edgeKey,{from:node.id,to:child.id,kind:relationKind}),child.cycle||pending.push(child)}}const nodes=[...nodesById.values()].sort((left,right)=>left.id.localeCompare(right.id)),edges=[...edgesByKey.values()].sort((left,right)=>{const byFrom=left.from.localeCompare(right.from);if(byFrom!==0)return byFrom;const byTo=left.to.localeCompare(right.to);return byTo!==0?byTo:left.kind.localeCompare(right.kind)}),missingIds=nodes.filter(node=>node.missing).map(node=>node.id);return{root_id:root.id,nodes,edges,missing_ids:missingIds}}function countDependencyGraph(rootId,index,maxDepth){const nodeIds=new Set,edgeKeys=new Set,missingIds=new Set,expanded=new Set,pending=[{id:rootId,depth:0}];let pendingIndex=0;for(;pendingIndex<pending.length;){const current=pending[pendingIndex++],lookupId=current.id.trim().toLowerCase();nodeIds.add(lookupId);const item=index.get(lookupId);if(!item){missingIds.add(lookupId);continue}if(!(maxDepth!==void 0&&current.depth>=maxDepth)&&!expanded.has(lookupId)){expanded.add(lookupId);for(const dependency of item.dependencies)edgeKeys.add(`${lookupId}::${dependency.id.trim().toLowerCase()}::${dependency.kind}`),pending.push({id:dependency.id,depth:current.depth+1})}}return{node_count:nodeIds.size,edge_count:edgeKeys.size,edge_basis:"deduplicated_directed",missing_count:missingIds.size}}function parseDepsContextOptions(options,registry=createRelationshipKindRegistry()){const maxDepth=parseMaxDepth(options.maxDepth),nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit"),edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit"),tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget"),kinds=parseKinds(options.kind,registry);return{direction:parseDirection(options.direction),...kinds===void 0?{}:{kinds},...maxDepth===void 0?{}:{maxDepth},...nodeLimit===void 0?{}:{nodeLimit},...edgeLimit===void 0?{}:{edgeLimit},...tokenBudget===void 0?{}:{tokenBudget},...options.cursor?.trim()?{cursor:options.cursor.trim()}:{}}}function buildContextFromAssembly(assembly,rootId,options,rootEvidence){return buildRelationshipContext(assembly.graph,rootId,assembly.details.map(detail=>detail.id===rootId&&rootEvidence.length>0?{...detail,evidence:rootEvidence}:detail),options)}function buildDepsRelationshipContext(rootId,items,options,rootEvidence=[]){const assembly=assembleWorkspaceRelationshipGraph(items);return buildContextFromAssembly(assembly,rootId,parseDepsContextOptions(options,assembly.graph.registry()),rootEvidence)}function appendEvidencePointers(evidence,label,values,limit){for(const value of values.slice(0,limit)){const trimmed=value?.trim();trimmed&&evidence.push(`${label}:${trimmed}`)}}async function collectRootEvidence(pmRoot,id,settings,typeToFolder){const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)return[];const{document}=await readLocatedItem(located,{schema:settings.schema}),metadata=document.metadata,files=metadata.files??[],tests=metadata.tests??[],docs=metadata.docs??[],counts=[["files",files.length],["tests",tests.length],["docs",docs.length],["comments",(metadata.comments??[]).length],["notes",(metadata.notes??[]).length],["learnings",(metadata.learnings??[]).length]];if(counts.every(([,count])=>count===0))return[];const evidence=[`linked:${counts.map(([key,count])=>`${key}=${count}`).join(",")}`];return appendEvidencePointers(evidence,"file",files.map(file=>file.path),3),appendEvidencePointers(evidence,"test",tests.map(test=>test.command??test.path),2),appendEvidencePointers(evidence,"doc",docs.map(doc=>doc.path),2),evidence}function createContextDepsResult(params){const{canonicalId,context,missingCount,missingReferences,referenceLimit,summaryOnly}=params;return{id:canonicalId,format:"context",node_count:context.nodes.length+1,edge_count:context.edges.length,edge_basis:"deduplicated_directed",missing_count:missingCount,missing_scope:"traversal",missing_reference_count:missingReferences.length,...summaryOnly?{}:{missing_references:missingReferences.slice(0,referenceLimit),context}}}function includesContextMissingReference(params){const{row,missingReachableSet,packetIds,filteredKinds,registry}=params;if(row.no_active_blocker_sentinel||!missingReachableSet.has(row.target_id.trim().toLowerCase())||!packetIds.has(row.holder_id))return!1;if(filteredKinds===void 0)return!0;const definition=registry.resolve(row.kind);return definition!==void 0&&(filteredKinds.has(definition.kind)||definition.inverse!==void 0&&filteredKinds.has(definition.inverse))}function discloseDepsOutput(result,rendering){const activeCommand=getActiveCommandContext(),commandOptions=rendering.commandOptionsOverride??(activeCommand?.command==="deps"?activeCommand.options:rendering.commandOptions);return attachReadOutputContracts("deps",{...commandOptions,...rendering.global,resolvedOutputFormat:rendering.format},result)}function renderDepsOutput(result,rendering){const disclosed=discloseDepsOutput(result,rendering),render=value=>formatBuiltInOutput(value,rendering.format,rendering.global.lean===!0);return render(rendering.global.tokenAccounting===!0?attachOutputTokenAccounting(disclosed,render):disclosed)}function settleRenderedTokenCount(result,rendering,assign){let embeddedTokens;for(;;){const measuredTokens=estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(result,rendering)).byteLength);if(measuredTokens===embeddedTokens)return measuredTokens;assign(measuredTokens),embeddedTokens=measuredTokens}}function isContextBudgetFloorError(error){return error instanceof TypeError&&error.message.startsWith("Relationship context tokenBudget cannot fit ")}function enforceContextRenderedTokenBudget(params){const{assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount,missingReferences}=params,referenceLimit=contextOptions.edgeLimit??40;let emittedReferenceLimit=Math.min(referenceLimit,missingReferences.length),internalTokenBudget=contextOptions.tokenBudget,requestedTokenBudget;for(;;){const context=buildContextFromAssembly(assembly,canonicalId,{...contextOptions,...internalTokenBudget===void 0?{}:{tokenBudget:internalTokenBudget}},rootEvidence);requestedTokenBudget??=context.meta.tokenBudget,internalTokenBudget??=requestedTokenBudget;const result=createContextDepsResult({canonicalId,context,missingCount,missingReferences,referenceLimit:emittedReferenceLimit,summaryOnly});if(summaryOnly){if(estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!0,rendering.legacyAliasCounts),rendering)).byteLength)>requestedTokenBudget)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return result}if(context.meta.tokenBudget=requestedTokenBudget,context.meta.usedTokens=settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{context.meta.usedTokens=tokens}),context.meta.usedTokens<=requestedTokenBudget)return result;if(emittedReferenceLimit>0){emittedReferenceLimit-=1;continue}const currentInternalBudget=internalTokenBudget,scaledInternalBudget=currentInternalBudget*requestedTokenBudget/context.meta.usedTokens;internalTokenBudget=Math.min(currentInternalBudget-1,Math.max(1,Math.floor(scaledInternalBudget*.9)))}}function createContextRetryPlan(params,budget){const options=params.contextOptions,global2={...params.rendering.global,outputFormat:params.rendering.format},args=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","context","--output-format",params.rendering.format,"--token-budget"],budgetIndex=args.length;args.push(String(budget));const provided=new Set(["--pm-path","--format","--output-format","--token-budget"]),commandOptions={format:"context",tokenBudget:budget,kind:options.kinds},values=[["--max-depth","maxDepth",options.maxDepth],["--node-limit","nodeLimit",options.nodeLimit],["--edge-limit","edgeLimit",options.edgeLimit],["--direction","direction",options.direction],["--cursor","cursor",options.cursor],["--output-include","outputInclude",global2.outputInclude],["--output-limit","outputLimit",global2.outputLimit],["--output-budget","outputBudget",global2.outputBudget],["--output-session","outputSession",global2.outputSession],["--output-cursor","outputCursor",global2.outputCursor]];for(const[flag,key,value]of values)value!==void 0&&(args.push(flag,String(value)),provided.add(flag),commandOptions[key]=value);for(const kind of options.kinds??[])args.push("--kind",kind),provided.add("--kind");const booleans=[["--summary","summary",params.summaryOnly],["--full","full",params.rendering.commandOptions.full],["--json","json",global2.json],["--lean","lean",global2.lean],["--output-row-contract","outputRowContract",global2.outputRowContract],["--token-accounting","tokenAccounting",global2.tokenAccounting],["--no-extensions","noExtensions",global2.noExtensions],["--no-pager","noPager",global2.noPager]];for(const[flag,key,enabled]of booleans)enabled===!0&&(args.push(flag),provided.add(flag),commandOptions[key]=!0);const contract=PM_READ_OUTPUT_SURFACE_CONTRACTS.find(candidate=>candidate.command==="deps");return Reflect.set(commandOptions,READ_OUTPUT_INVOCATION_PROVENANCE,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(contract.dimensions).flatMap(dimension=>dimension.legacy_aliases.flatMap(alias=>provided.has(alias.flag)?[alias.flag]:[]))}),normalizeReadOutputIncludeModeOptions("deps",commandOptions),assertProjectionModeChoice(commandOptions.summary===!0,commandOptions.full===!0,"--summary"),global2.outputInclude=commandOptions.outputInclude,{args,budgetIndex,summaryOnly:commandOptions.summary===!0,rendering:{...params.rendering,global:global2,commandOptionsOverride:commandOptions}}}function probeContextRetry(params,plan,budget){const rendering={...plan.rendering,commandOptionsOverride:{...plan.rendering.commandOptionsOverride,tokenBudget:budget}};let result;try{result=enforceContextRenderedTokenBudget({...params,contextOptions:{...params.contextOptions,tokenBudget:budget},summaryOnly:plan.summaryOnly,rootEvidence:plan.summaryOnly?[]:params.rootEvidence,rendering})}catch(error){if(!isContextBudgetFloorError(error))throw error;return"native_floor"}const disclosed=discloseDepsOutput(attachDepsProjection(result,plan.summaryOnly,rendering.legacyAliasCounts),rendering);return isReadOutputBudgetExceeded(disclosed)?"output_constraints":"fits"}async function createContextBudgetRefusal(params,cause){const requested=params.contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,plan=createContextRetryPlan(params,requested),workUnits=(plan.summaryOnly?1:1+Math.min(params.contextOptions.edgeLimit??40,params.missingReferences.length))*(params.assembly.details.reduce((sum,node)=>sum+node.id.length+node.title.length+node.status.length+(node.type?.length??0),params.assembly.graph.edges().length+params.missingReferences.length)+(plan.summaryOnly?[]:params.rootEvidence).reduce((sum,pointer)=>sum+pointer.length,0)),{findContextBudgetRecovery}=await import("./dependencies/context-budget-recovery.js"),bounds=findContextBudgetRecovery({requested,initialBudget:DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET,workUnits,probe:budget=>probeContextRetry(params,plan,budget)}),inspectionArgs=["--pm-path",params.pmRoot,"item","deps",params.canonicalId,"--format","tree","--summary"],inspection=renderPmCommand(inspectionArgs),retryArgs=bounds.feasible_tokens===null?inspectionArgs:[...plan.args];bounds.feasible_tokens!==null&&(retryArgs[plan.budgetIndex]=String(bounds.feasible_tokens));const retry=renderPmCommand(retryArgs);return createPmCliExpectedError("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:EXIT_CODE.USAGE,cause,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(requested),required:bounds.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+bounds.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[retry,inspection],nextSteps:[retry],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:bounds,suggested_retry_args:retryArgs,suggested_retry:retry,next_best_command:inspection,fallback_candidates:[{source:"relationship_summary",command:inspection,reason:"Inspect bounded counts separately from context rows."}]}}})}async function buildContextDepsResult(params){const{pmRoot,assembly,canonicalId,options,rootEvidence,summaryOnly,rendering}=params,contextOptions=parseDepsContextOptions(options,assembly.graph.registry()),reachable=assembly.graph.closure(canonicalId,{direction:contextOptions.direction,...contextOptions.kinds===void 0?{}:{kinds:contextOptions.kinds},maxDepth:contextOptions.maxDepth??3}),missingReachable=reachable.value.filter(nodeId=>assembly.missingIdSet.has(nodeId.toLowerCase())),missingReachableSet=new Set(missingReachable.map(nodeId=>nodeId.toLowerCase())),relationshipRegistry=assembly.graph.registry(),filteredKinds=contextOptions.kinds?new Set(contextOptions.kinds.map(kind=>relationshipRegistry.require(kind).kind)):void 0,packetIds=new Set([canonicalId,...reachable.value]),missingReferences=[...assembly.dangling.active,...assembly.dangling.legacy_terminal].filter(row=>includesContextMissingReference({row,missingReachableSet,packetIds,filteredKinds,registry:relationshipRegistry})),budgetParams={pmRoot,assembly,canonicalId,contextOptions,rootEvidence,summaryOnly,rendering,missingCount:missingReachable.length,missingReferences};try{return enforceContextRenderedTokenBudget(budgetParams)}catch(error){if(error instanceof PmCliError&&error.code==="invalid_query_cursor"){const plan=createContextRetryPlan({...budgetParams,contextOptions:{...contextOptions,cursor:void 0},rendering:{...rendering,global:{...rendering.global,outputCursor:void 0}}},contextOptions.tokenBudget??DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET),retry=renderPmCommand(plan.args);throw new PmCliError(error.message,error.exitCode,{...error.context,nextSteps:[...error.context.nextSteps,retry],recovery:{suggested_retry:retry,suggested_retry_args:plan.args}})}throw isContextBudgetFloorError(error)?await createContextBudgetRefusal(budgetParams,error):error}}function trimDeepestDependency(tree){const pending=[tree];let parentToTrim;for(;pending.length>0;){const current=pending.pop();current.dependencies.length>0&&(parentToTrim=current,pending.push(...current.dependencies))}return parentToTrim?(parentToTrim.dependencies.pop(),parentToTrim.truncated=!0,!0):!1}function buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,rendering){const effectiveMaxDepth=maxDepth??DEFAULT_DEPS_TREE_MAX_DEPTH,nodeLimit=parsePositiveInteger(options.nodeLimit,"node-limit")??DEFAULT_DEPS_TREE_NODE_LIMIT,edgeLimit=parsePositiveInteger(options.edgeLimit,"edge-limit")??DEFAULT_DEPS_TREE_EDGE_LIMIT,tokenBudget=parsePositiveInteger(options.tokenBudget,"token-budget")??DEFAULT_DEPS_TREE_TOKEN_BUDGET,budget={nodeLimit,edgeLimit,tokenBudget,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},tree=toTreeNode(id,index,new Set,effectiveMaxDepth,format==="graph"?"repeated":collapse,new Set,budget),totals=countDependencyGraph(id,index,void 0);let result;for(;;){const graph=toGraph(tree),truncation=budget.reasons.size===0?void 0:{reasons:[...budget.reasons].sort(),limits:{max_depth:effectiveMaxDepth,node_limit:nodeLimit,edge_limit:edgeLimit,token_budget:tokenBudget},estimated_tokens:0,total_node_count:totals.node_count,total_edge_count:totals.edge_count,omitted_node_count:Math.max(0,totals.node_count-graph.nodes.length),omitted_edge_count:Math.max(0,totals.edge_count-graph.edges.length)},baseResult={id,format,node_count:graph.nodes.length,edge_count:graph.edges.length,edge_basis:"deduplicated_directed",missing_count:graph.missing_ids.length,...truncation?{truncation}:{}};if(result=format==="tree"?{...baseResult,tree}:{...baseResult,graph},(result.truncation===void 0?estimatePmOutputTokens(new TextEncoder().encode(renderDepsOutput(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering)).byteLength):settleRenderedTokenCount(attachDepsProjection(result,!1,rendering.legacyAliasCounts),rendering,tokens=>{result.truncation.estimated_tokens=tokens}))<=tokenBudget)return result;if(!trimDeepestDependency(tree))return budget.reasons.add("token_budget"),result;budget.reasons.add("token_budget")}}function attachDepsProjection(result,summaryOnly,legacyAliasCounts={}){const group={name:result.format==="tree"?"dependency_tree":result.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},boundedGroups=result.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...result,legacy_alias_counts:legacyAliasCounts,projection:{mode:summaryOnly?"summary":"full",declared_field_groups:[group,...boundedGroups],included_field_groups:summaryOnly?[]:[group.name]}}}async function runDeps(id,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const format=parseFormat(options.format),maxDepth=parseMaxDepth(options.maxDepth),collapse=parseCollapse(options.collapse);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const summaryOnly=options.summary===!0,settings=await readSettings(pmRoot),typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),index=new Map(items.map(item=>[item.id.trim().toLowerCase(),toIndexedItem(item)])),dangling=collectDanglingDependencyReferences(items,status=>isTerminalStatus(status,statusRegistry));for(const reference of[...dangling.active,...dangling.legacy_terminal]){const holder=index.get(reference.holder_id.trim().toLowerCase()),referenceKind=reference.kind.trim().toLowerCase();holder&&!holder.dependencies.some(dependency=>dependency.id.trim().toLowerCase()===reference.target_id.trim().toLowerCase()&&dependency.kind===referenceKind)&&holder.dependencies.push({id:reference.target_id,kind:referenceKind})}if(!index.has(id.trim().toLowerCase()))throw new PmCliError(`Item ${id} not found`,EXIT_CODE.NOT_FOUND);const outputFormat=global2.outputFormat??(global2.json===!0||global2.json===void 0&&global2.defaultOutputFormat==="json"?"json":"toon");if(format==="context"){const canonicalId=index.get(id.trim().toLowerCase()).id,rootEvidence=summaryOnly?[]:await collectRootEvidence(pmRoot,canonicalId,settings,typeRegistry.type_to_folder),isTerminal=status=>isTerminalStatus(status,statusRegistry),relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));return attachDepsProjection(await buildContextDepsResult({pmRoot,assembly:lookup.assembly,canonicalId,options,rootEvidence,summaryOnly,rendering:{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts:lookup.assembly.legacyAliasCounts}}),summaryOnly,lookup.assembly.legacyAliasCounts)}const legacyAliasCounts=Object.fromEntries(Object.entries(assembleWorkspaceRelationshipGraph(items,status=>isTerminalStatus(status,statusRegistry)).legacyAliasCounts));return summaryOnly?attachDepsProjection({id,format,...countDependencyGraph(id,index,maxDepth)},!0,legacyAliasCounts):attachDepsProjection(buildTreeOrGraphDepsResult(id,format,options,index,maxDepth,collapse,{format:outputFormat,global:global2,commandOptions:options,legacyAliasCounts}),!1,legacyAliasCounts)}export{DEPS_COLLAPSE_VALUES,DEPS_DIRECTION_VALUES,DEPS_FORMAT_VALUES,buildDepsRelationshipContext,parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger,runDeps};
1
+ import{assertInitializedTracker as V}from"./environment/tracker-preflight.js";import{getActiveCommandContext as W,getActiveExtensionRegistrations as X}from"../core/extensions/index.js";import{resolveItemTypeRegistry as H}from"../core/item/type-registry.js";import{isTerminalStatus as O}from"../core/item/status.js";import{resolveRuntimeStatusRegistry as J}from"../core/schema/runtime-schema.js";import{EXIT_CODE as C}from"../core/shared/constants.js";import{PmCliError as x}from"../core/shared/errors.js";import{formatBuiltInOutput as Q}from"../core/output/output.js";import{listAllItemMetadataLight as Y,locateItem as Z,readLocatedItem as ee}from"../core/store/item-store.js";import{resolvePmRoot as te}from"../core/store/paths.js";import{readSettings as ne}from"../core/store/settings.js";import{estimatePmOutputTokens as E}from"./cli-contracts/agent-output-contracts.js";import{renderPmCommand as R}from"./command-line.js";import{createPmCliExpectedError as oe}from"./errors.js";import{isReadOutputBudgetExceeded as se,normalizeReadOutputIncludeModeOptions as ie,PM_READ_OUTPUT_SURFACE_CONTRACTS as re}from"./read-output-contracts.js";import{READ_OUTPUT_INVOCATION_PROVENANCE as de}from"./read-output/provenance.js";import{attachReadOutputContracts as ce}from"./context-intent-contracts.js";import{attachOutputTokenAccounting as ae}from"./output-token-accounting.js";import{assertProjectionModeChoice as A}from"./output-projection.js";import{assembleWorkspaceRelationshipGraph as b,collectDanglingDependencyReferences as ue,resolveWorkspaceRelationshipKindRegistry as me}from"./graph/assembly.js";import{computeWorkspaceGraphFingerprint as le,workspaceGraphCache as pe}from"./graph/cache.js";import{buildRelationshipContext as fe,DEFAULT_RELATIONSHIP_CONTEXT_TOKEN_BUDGET as L}from"./relationship-context.js";import{createRelationshipKindRegistry as D}from"./relationships.js";const ge=["tree","graph","context"],he=["none","repeated"],ye=["outgoing","incoming","both"],_e=32,ke=200,xe=400,Ce=16e3;function ve(e){const t=e?.trim().toLowerCase()??"tree";if(ge.includes(t))return t;throw new x(`Invalid --format value "${e}". Use "tree", "graph", or "context".`,C.USAGE)}function w(e,t){if(e===void 0)return;const o=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(o)||o<1)throw new x(`Invalid --${t} value "${e}". Use a positive integer.`,C.USAGE);return o}function B(e){if(e===void 0)return;const t=typeof e=="number"?e:Number(e.trim());if(!Number.isInteger(t)||t<0)throw new x(`Invalid --max-depth value "${e}". Use a non-negative integer.`,C.USAGE);return t}function we(e){const t=e?.trim().toLowerCase()??"none";if(he.includes(t))return t;throw new x(`Invalid --collapse value "${e}". Use "none" or "repeated".`,C.USAGE)}function Ee(e){const t=e?.trim().toLowerCase()??"both";if(ye.includes(t))return t;throw new x(`Invalid --direction value "${e}". Use "outgoing", "incoming", or "both".`,C.USAGE)}function Te(e,t=D()){if(e===void 0)return;const o=(Array.isArray(e)?e:[e]).flatMap(s=>s.split(",")).map(s=>s.trim()).filter(s=>s.length>0);if(o.length===0)return;const n=new Set;for(const s of o){const m=t.resolve(s);if(!m){const r=t.list().map(i=>i.kind).join(", ");throw new x(`Invalid --kind value "${s}". Registered kinds: ${r}.`,C.USAGE)}n.add(m.kind)}return[...n].sort()}function Oe(e){if(!e||e.length===0)return[];const t=e.map(({id:n,kind:s})=>({id:n.trim(),kind:s.trim().toLowerCase()})).sort((n,s)=>{const m=n.kind.localeCompare(s.kind);return m!==0?m:n.id.localeCompare(s.id)}),o=new Map;for(const n of t){const s=`${n.kind.toLowerCase()}::${n.id.toLowerCase()}`;o.has(s)||o.set(s,{id:n.id,kind:n.kind})}return[...o.values()]}function Re(e){return{id:e.id,title:e.title,type:e.type,status:e.status,dependencies:Oe(e.dependencies)}}function be(e){return E(new TextEncoder().encode(JSON.stringify({...e,dependencies:void 0})).byteLength)}function Le(e,t,o,n,s,m,r,i,d){for(const l of t.dependencies){const a=Math.max(1,Math.ceil(JSON.stringify({from:e.id,to:l.id,kind:l.kind}).length/3));if(i.nodes>=i.nodeLimit){e.truncated=!0,i.reasons.add("node_limit");break}if(i.edges>=i.edgeLimit){e.truncated=!0,i.reasons.add("edge_limit");break}if(i.estimatedTokens+a>=i.tokenBudget){e.truncated=!0,i.reasons.add("token_budget");break}i.edges+=1,i.estimatedTokens+=a,e.dependencies.push(P(l.id,o,n,s,m,r,i,d+1,l.kind))}}function Ie(e,t,o,n,s,m,r,i){return r.estimatedTokens>=r.tokenBudget&&t?.dependencies.length?(e.truncated=!0,r.reasons.add("token_budget"),!0):!t||e.cycle?!0:n!==void 0&&i>=n?(t.dependencies.length>0&&(e.truncated=!0,r.reasons.add("max_depth")),!0):s==="repeated"&&m.has(o)?(e.collapsed=!0,!0):!1}function P(e,t,o,n,s,m,r,i=0,d){const l=e.trim().toLowerCase(),a=t.get(l),u={id:a?.id??e,title:a?.title,type:a?.type,status:a?.status,via:d,missing:!a,cycle:o.has(l),dependencies:[]};if(r.nodes+=1,r.estimatedTokens+=be(u),Ie(u,a,l,n,s,m,r,i))return u;s==="repeated"&&m.add(l);const c=new Set(o);return c.add(l),Le(u,a,t,c,n,s,m,r,i),u}function U(e,t){return!e||e.missing&&!t.missing?t:{...e,title:e.title??t.title,type:e.type??t.type,status:e.status??t.status}}function Se(e){const t=new Map,o=new Map,n=[e];for(;n.length>0;){const i=n.pop();t.set(i.id,U(t.get(i.id),{id:i.id,title:i.title,type:i.type,status:i.status,missing:i.missing}));for(const d of i.dependencies){t.set(d.id,U(t.get(d.id),{id:d.id,title:d.title,type:d.type,status:d.status,missing:d.missing}));const l=d.via??"related",a=`${i.id}::${d.id}::${l}`;o.has(a)||o.set(a,{from:i.id,to:d.id,kind:l}),d.cycle||n.push(d)}}const s=[...t.values()].sort((i,d)=>i.id.localeCompare(d.id)),m=[...o.values()].sort((i,d)=>{const l=i.from.localeCompare(d.from);if(l!==0)return l;const a=i.to.localeCompare(d.to);return a!==0?a:i.kind.localeCompare(d.kind)}),r=s.filter(i=>i.missing).map(i=>i.id);return{root_id:e.id,nodes:s,edges:m,missing_ids:r}}function M(e,t,o){const n=new Set,s=new Set,m=new Set,r=new Set,i=[{id:e,depth:0}];let d=0;for(;d<i.length;){const l=i[d++],a=l.id.trim().toLowerCase();n.add(a);const u=t.get(a);if(!u){m.add(a);continue}if(!(o!==void 0&&l.depth>=o)&&!r.has(a)){r.add(a);for(const c of u.dependencies)s.add(`${a}::${c.id.trim().toLowerCase()}::${c.kind}`),i.push({id:c.id,depth:l.depth+1})}}return{node_count:n.size,edge_count:s.size,edge_basis:"deduplicated_directed",missing_count:m.size}}function $(e,t=D()){const o=B(e.maxDepth),n=w(e.nodeLimit,"node-limit"),s=w(e.edgeLimit,"edge-limit"),m=w(e.tokenBudget,"token-budget"),r=Te(e.kind,t);return{direction:Ee(e.direction),...r===void 0?{}:{kinds:r},...o===void 0?{}:{maxDepth:o},...n===void 0?{}:{nodeLimit:n},...s===void 0?{}:{edgeLimit:s},...m===void 0?{}:{tokenBudget:m},...e.cursor?.trim()?{cursor:e.cursor.trim()}:{}}}function N(e,t,o,n){return fe(e.graph,t,e.details.map(s=>s.id===t&&n.length>0?{...s,evidence:n}:s),o)}function at(e,t,o,n=[]){const s=b(t);return N(s,e,$(o,s.graph.registry()),n)}function I(e,t,o,n){for(const s of o.slice(0,n)){const m=s?.trim();m&&e.push(`${t}:${m}`)}}async function Ae(e,t,o,n){const s=await Z(e,t,o.id_prefix,o.item_format,n);if(!s)return[];const{document:m}=await ee(s,{schema:o.schema}),r=m.metadata,i=r.files??[],d=r.tests??[],l=r.docs??[],a=[["files",i.length],["tests",d.length],["docs",l.length],["comments",(r.comments??[]).length],["notes",(r.notes??[]).length],["learnings",(r.learnings??[]).length]];if(a.every(([,c])=>c===0))return[];const u=[`linked:${a.map(([c,p])=>`${c}=${p}`).join(",")}`];return I(u,"file",i.map(c=>c.path),3),I(u,"test",d.map(c=>c.command??c.path),2),I(u,"doc",l.map(c=>c.path),2),u}function De(e){const{canonicalId:t,context:o,missingCount:n,missingReferences:s,referenceLimit:m,summaryOnly:r}=e;return{id:t,format:"context",node_count:o.nodes.length+1,edge_count:o.edges.length,edge_basis:"deduplicated_directed",missing_count:n,missing_scope:"traversal",missing_reference_count:s.length,...r?{}:{missing_references:s.slice(0,m),context:o}}}function Be(e){const{row:t,missingReachableSet:o,packetIds:n,filteredKinds:s,registry:m}=e;if(t.no_active_blocker_sentinel||!o.has(t.target_id.trim().toLowerCase())||!n.has(t.holder_id))return!1;if(s===void 0)return!0;const r=m.resolve(t.kind);return r!==void 0&&(s.has(r.kind)||r.inverse!==void 0&&s.has(r.inverse))}function F(e,t){const o=W(),n=t.commandOptionsOverride??(o?.command==="deps"?o.options:t.commandOptions);return ce("deps",{...n,...t.global,resolvedOutputFormat:t.format},e)}function S(e,t){const o=F(e,t),n=s=>Q(s,t.format,t.global.lean===!0);return n(t.global.tokenAccounting===!0?ae(o,n):o)}function G(e,t,o){let n;for(;;){const s=E(new TextEncoder().encode(S(e,t)).byteLength);if(s===n)return s;o(s),n=s}}function j(e){return e instanceof TypeError&&e.message.startsWith("Relationship context tokenBudget cannot fit ")}function K(e){const{assembly:t,canonicalId:o,contextOptions:n,rootEvidence:s,summaryOnly:m,rendering:r,missingCount:i,missingReferences:d}=e,l=n.edgeLimit??40;let a=Math.min(l,d.length),u=n.tokenBudget,c;for(;;){const p=N(t,o,{...n,...u===void 0?{}:{tokenBudget:u}},s);c??=p.meta.tokenBudget,u??=c;const h=De({canonicalId:o,context:p,missingCount:i,missingReferences:d,referenceLimit:a,summaryOnly:m});if(m){if(E(new TextEncoder().encode(S(v(h,!0,r.legacyAliasCounts),r)).byteLength)>c)throw new TypeError("Relationship context tokenBudget cannot fit the rendered summary");return h}if(p.meta.tokenBudget=c,p.meta.usedTokens=G(v(h,!1,r.legacyAliasCounts),r,f=>{p.meta.usedTokens=f}),p.meta.usedTokens<=c)return h;if(a>0){a-=1;continue}const y=u,g=y*c/p.meta.usedTokens;u=Math.min(y-1,Math.max(1,Math.floor(g*.9)))}}function q(e,t){const o=e.contextOptions,n={...e.rendering.global,outputFormat:e.rendering.format},s=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","context","--output-format",e.rendering.format,"--token-budget"],m=s.length;s.push(String(t));const r=new Set(["--pm-path","--format","--output-format","--token-budget"]),i={format:"context",tokenBudget:t,kind:o.kinds},d=[["--max-depth","maxDepth",o.maxDepth],["--node-limit","nodeLimit",o.nodeLimit],["--edge-limit","edgeLimit",o.edgeLimit],["--direction","direction",o.direction],["--cursor","cursor",o.cursor],["--output-include","outputInclude",n.outputInclude],["--output-limit","outputLimit",n.outputLimit],["--output-budget","outputBudget",n.outputBudget],["--output-session","outputSession",n.outputSession],["--output-cursor","outputCursor",n.outputCursor]];for(const[u,c,p]of d)p!==void 0&&(s.push(u,String(p)),r.add(u),i[c]=p);for(const u of o.kinds??[])s.push("--kind",u),r.add("--kind");const l=[["--summary","summary",e.summaryOnly],["--full","full",e.rendering.commandOptions.full],["--json","json",n.json],["--lean","lean",n.lean],["--output-row-contract","outputRowContract",n.outputRowContract],["--token-accounting","tokenAccounting",n.tokenAccounting],["--no-extensions","noExtensions",n.noExtensions],["--no-pager","noPager",n.noPager]];for(const[u,c,p]of l)p===!0&&(s.push(u),r.add(u),i[c]=!0);const a=re.find(u=>u.command==="deps");return Reflect.set(i,de,{canonical_include_modes:[],cli_invocation_observed:!0,explicit_legacy_aliases:Object.values(a.dimensions).flatMap(u=>u.legacy_aliases.flatMap(c=>r.has(c.flag)?[c.flag]:[]))}),ie("deps",i),A(i.summary===!0,i.full===!0,"--summary"),n.outputInclude=i.outputInclude,{args:s,budgetIndex:m,summaryOnly:i.summary===!0,rendering:{...e.rendering,global:n,commandOptionsOverride:i}}}function Pe(e,t,o){const n={...t.rendering,commandOptionsOverride:{...t.rendering.commandOptionsOverride,tokenBudget:o}};let s;try{s=K({...e,contextOptions:{...e.contextOptions,tokenBudget:o},summaryOnly:t.summaryOnly,rootEvidence:t.summaryOnly?[]:e.rootEvidence,rendering:n})}catch(r){if(!j(r))throw r;return"native_floor"}const m=F(v(s,t.summaryOnly,n.legacyAliasCounts),n);return se(m)?"output_constraints":"fits"}async function Ue(e,t){const o=e.contextOptions.tokenBudget??L,n=q(e,o),m=(n.summaryOnly?1:1+Math.min(e.contextOptions.edgeLimit??40,e.missingReferences.length))*(e.assembly.details.reduce((c,p)=>c+p.id.length+p.title.length+p.status.length+(p.type?.length??0),e.assembly.graph.edges().length+e.missingReferences.length)+(n.summaryOnly?[]:e.rootEvidence).reduce((c,p)=>c+p.length,0)),{findContextBudgetRecovery:r}=await import("./dependencies/context-budget-recovery.js"),i=r({requested:o,initialBudget:L,workUnits:m,probe:c=>Pe(e,n,c)}),d=["--pm-path",e.pmRoot,"item","deps",e.canonicalId,"--format","tree","--summary"],l=R(d),a=i.feasible_tokens===null?d:[...n.args];i.feasible_tokens!==null&&(a[n.budgetIndex]=String(i.feasible_tokens));const u=R(a);return oe("Relationship context tokenBudget cannot fit the required rendered packet",{exitCode:C.USAGE,cause:t,context:{code:"invalid_argument_value",field:"tokenBudget",value:String(o),required:i.feasible_tokens===null?"Inspect the compact summary and review the output constraints.":"Retry the preserved context query with --token-budget "+i.feasible_tokens+".",why:"Budget advice is verified against the current query. A minimum is reported only after every smaller positive budget is checked.",examples:[u,l],nextSteps:[u],recovery:{recovery_mode:"compact",suggested_flags:["--token-budget"],token_budget:i,suggested_retry_args:a,suggested_retry:u,next_best_command:l,fallback_candidates:[{source:"relationship_summary",command:l,reason:"Inspect bounded counts separately from context rows."}]}}})}async function Me(e){const{pmRoot:t,assembly:o,canonicalId:n,options:s,rootEvidence:m,summaryOnly:r,rendering:i}=e,d=$(s,o.graph.registry()),l=o.graph.closure(n,{direction:d.direction,...d.kinds===void 0?{}:{kinds:d.kinds},maxDepth:d.maxDepth??3}),a=l.value.filter(f=>o.missingIdSet.has(f.toLowerCase())),u=new Set(a.map(f=>f.toLowerCase())),c=o.graph.registry(),p=d.kinds?new Set(d.kinds.map(f=>c.require(f).kind)):void 0,h=new Set([n,...l.value]),y=[...o.dangling.active,...o.dangling.legacy_terminal].filter(f=>Be({row:f,missingReachableSet:u,packetIds:h,filteredKinds:p,registry:c})),g={pmRoot:t,assembly:o,canonicalId:n,contextOptions:d,rootEvidence:m,summaryOnly:r,rendering:i,missingCount:a.length,missingReferences:y};try{return K(g)}catch(f){if(f instanceof x&&f.code==="invalid_query_cursor"){const k=q({...g,contextOptions:{...d,cursor:void 0},rendering:{...i,global:{...i.global,outputCursor:void 0}}},d.tokenBudget??L),_=R(k.args);throw new x(f.message,f.exitCode,{...f.context,nextSteps:[...f.context.nextSteps,_],recovery:{suggested_retry:_,suggested_retry_args:k.args}})}throw j(f)?await Ue(g,f):f}}function $e(e){const t=[e];let o;for(;t.length>0;){const n=t.pop();n.dependencies.length>0&&(o=n,t.push(...n.dependencies))}return o?(o.dependencies.pop(),o.truncated=!0,!0):!1}function Ne(e,t,o,n,s,m,r){const i=s??_e,d=w(o.nodeLimit,"node-limit")??ke,l=w(o.edgeLimit,"edge-limit")??xe,a=w(o.tokenBudget,"token-budget")??Ce,u={nodeLimit:d,edgeLimit:l,tokenBudget:a,nodes:0,edges:0,estimatedTokens:0,reasons:new Set},c=P(e,n,new Set,i,t==="graph"?"repeated":m,new Set,u),p=M(e,n,void 0);let h;for(;;){const y=Se(c),g=u.reasons.size===0?void 0:{reasons:[...u.reasons].sort(),limits:{max_depth:i,node_limit:d,edge_limit:l,token_budget:a},estimated_tokens:0,total_node_count:p.node_count,total_edge_count:p.edge_count,omitted_node_count:Math.max(0,p.node_count-y.nodes.length),omitted_edge_count:Math.max(0,p.edge_count-y.edges.length)},f={id:e,format:t,node_count:y.nodes.length,edge_count:y.edges.length,edge_basis:"deduplicated_directed",missing_count:y.missing_ids.length,...g?{truncation:g}:{}};if(h=t==="tree"?{...f,tree:c}:{...f,graph:y},(h.truncation===void 0?E(new TextEncoder().encode(S(v(h,!1,r.legacyAliasCounts),r)).byteLength):G(v(h,!1,r.legacyAliasCounts),r,_=>{h.truncation.estimated_tokens=_}))<=a)return h;if(!$e(c))return u.reasons.add("token_budget"),h;u.reasons.add("token_budget")}}function v(e,t,o={}){const n={name:e.format==="tree"?"dependency_tree":e.format==="graph"?"dependency_graph":"relationship_context",restore_with:"--full"},s=e.context?.meta.truncated?[{name:"relationship_context_bounds",restore_with:"--token-budget <n> --node-limit <n> --edge-limit <n> --max-depth <n>"}]:[];return{...e,legacy_alias_counts:o,projection:{mode:t?"summary":"full",declared_field_groups:[n,...s],included_field_groups:t?[]:[n.name]}}}async function ut(e,t,o){const n=te(process.cwd(),o.path);await V(n);const s=ve(t.format),m=B(t.maxDepth),r=we(t.collapse);A(t.summary===!0,t.full===!0,"--summary");const i=t.summary===!0,d=await ne(n),l=H(d,X()),a=await Y(n,d.item_format,l.type_to_folder,void 0,d.schema),u=J(d.schema),c=new Map(a.map(g=>[g.id.trim().toLowerCase(),Re(g)])),p=ue(a,g=>O(g,u));for(const g of[...p.active,...p.legacy_terminal]){const f=c.get(g.holder_id.trim().toLowerCase()),k=g.kind.trim().toLowerCase();f&&!f.dependencies.some(_=>_.id.trim().toLowerCase()===g.target_id.trim().toLowerCase()&&_.kind===k)&&f.dependencies.push({id:g.target_id,kind:k})}if(!c.has(e.trim().toLowerCase()))throw new x(`Item ${e} not found`,C.NOT_FOUND);const h=o.outputFormat??(o.json===!0||o.json===void 0&&o.defaultOutputFormat==="json"?"json":"toon");if(s==="context"){const g=c.get(e.trim().toLowerCase()).id,f=i?[]:await Ae(n,g,d,l.type_to_folder),k=z=>O(z,u),_=me(),T=pe().lookup(n,le(a,k,_),()=>b(a,k,_));return v(await Me({pmRoot:n,assembly:T.assembly,canonicalId:g,options:t,rootEvidence:f,summaryOnly:i,rendering:{format:h,global:o,commandOptions:t,legacyAliasCounts:T.assembly.legacyAliasCounts}}),i,T.assembly.legacyAliasCounts)}const y=Object.fromEntries(Object.entries(b(a,g=>O(g,u)).legacyAliasCounts));return i?v({id:e,format:s,...M(e,c,m)},!0,y):v(Ne(e,s,t,c,m,r,{format:h,global:o,commandOptions:t,legacyAliasCounts:y}),!1,y)}export{he as DEPS_COLLAPSE_VALUES,ye as DEPS_DIRECTION_VALUES,ge as DEPS_FORMAT_VALUES,at as buildDepsRelationshipContext,Ee as parseDirection,Te as parseKinds,B as parseMaxDepth,w as parsePositiveInteger,ut as runDeps};
2
2
  //# sourceMappingURL=dependencies.js.map
@@ -1,2 +1,2 @@
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]="414326ff-8d4d-577d-b724-ab32b3f311ac")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";import{toErrorMessage}from"../core/shared/primitives.js";import{DEPENDENCY_KIND_VALUES}from"../types/index.js";import{locateItem,readLocatedItem}from"../core/store/item-store.js";import{isExternalDependencySourceKind}from"./dependency-provenance.js";import{resolveWorkspaceRelationshipKindRegistry}from"./graph/assembly.js";import{assertRelationshipEdgeAllowed}from"./relationships.js";function requireDependencyKind(value,registry=resolveWorkspaceRelationshipKindRegistry()){const definition=registry.resolve(value);if(definition)return definition.kind;const builtinKinds=new Set(DEPENDENCY_KIND_VALUES),allowed=[...DEPENDENCY_KIND_VALUES,...registry.list().filter(({kind})=>!builtinKinds.has(kind)).flatMap(({kind,aliases})=>[kind,...aliases])];throw new PmCliError(`Invalid dependency kind value "${value}". Allowed: ${allowed.join(", ")}`,EXIT_CODE.USAGE,{field:"kind",value,recovery:{allowed_values:allowed},required:`dependency kind must be one of: ${allowed.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function assertValidBareDependencyFlagValue(value,structured,flag="--dep"){if(!structured&&/[:,=]/.test(value))throw new PmCliError(`Invalid ${flag} value "${value}". Use a bare item id or id=<id>,kind=<kind>.`,EXIT_CODE.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag,value,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function assertDependencyEdgesAllowed(holderId,dependencies,registry=resolveWorkspaceRelationshipKindRegistry()){for(const dependency of dependencies??[])try{assertRelationshipEdgeAllowed(holderId,dependency.id,dependency.kind,registry)}catch(error){throw new PmCliError(toErrorMessage(error),EXIT_CODE.USAGE,{code:"dependency_edge_not_allowed",why:`${holderId} -> ${dependency.id} (${dependency.kind}) violates the active relationship-kind policy`})}}async function readDependencyEndpointCreatedAt(located,schema){return(await readLocatedItem(located,{schema})).document.metadata.created_at}async function resolveDependencyHolderCreatedAt(holder,context){if(holder.createdAt!==void 0)return holder.createdAt;const located=await locateItem(context.pmRoot,holder.id,context.idPrefix,context.itemFormat,context.typeToFolder);return located===null?void 0:readDependencyEndpointCreatedAt(located,context.schema)}function dependencyTemporalOrderError(params){const definition=params.registry.require(params.dependency.kind);return new PmCliError(`${definition.kind} requires source ${params.holder.id} to be created after target ${params.dependency.id}`,EXIT_CODE.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${params.holder.id}.created_at must be later than ${params.dependency.id}.created_at for ${definition.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:params.holder.id,source_created_at:params.sourceCreatedAt,target_id:params.dependency.id,target_created_at:params.targetCreatedAt,temporal_order:definition.temporalOrder})}async function assertTemporalDependencyChronology(params){const temporalDependencies=params.dependencies.filter(dependency=>params.registry.resolve(dependency.kind)?.temporalOrder==="source_after_target"&&!params.missingTargets.includes(dependency.id));if(temporalDependencies.length===0||params.holders.length===0)return;const locatedTargets=new Map(params.resolutions.flatMap(({target,located})=>located===null?[]:[[target,located]])),targetCreatedAt=new Map(await Promise.all([...new Set(temporalDependencies.map(({id})=>id))].map(async target=>[target,await readDependencyEndpointCreatedAt(locatedTargets.get(target),params.context.schema)])));for(const holder of params.holders){const sourceCreatedAt=await resolveDependencyHolderCreatedAt(holder,params.context);if(sourceCreatedAt!==void 0)for(const dependency of temporalDependencies){const targetTimestamp=targetCreatedAt.get(dependency.id),sourceTime=Date.parse(sourceCreatedAt),targetTime=Date.parse(targetTimestamp);if(!(Number.isFinite(sourceTime)&&Number.isFinite(targetTime)&&sourceTime>targetTime))throw dependencyTemporalOrderError({holder,dependency,sourceCreatedAt,targetCreatedAt:targetTimestamp,registry:params.registry})}}}async function assertDependencyTargetsResolvable(params){const registry=params.registry??resolveWorkspaceRelationshipKindRegistry(),localDependencies=(params.dependencies??[]).filter(dependency=>!isExternalDependencySourceKind(dependency.source_kind)),localTargets=[...new Set(localDependencies.map(dependency=>dependency.id))],resolutions=await Promise.all(localTargets.map(async target=>({target,located:await locateItem(params.pmRoot,target,params.idPrefix,params.itemFormat,params.typeToFolder)}))),missingTargets=resolutions.filter(({located})=>located===null).map(({target})=>target).sort((left,right)=>left<right?-1:1);if(missingTargets.length>0&&params.allowUnresolved!==!0)throw new PmCliError(`Dependency target${missingTargets.length===1?"":"s"} not found: ${missingTargets.join(", ")}`,EXIT_CODE.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:missingTargets,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${missingTargets.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:missingTargets,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${missingTargets[0]}" --limit 10`}});return await assertTemporalDependencyChronology({dependencies:localDependencies,missingTargets,resolutions,holders:params.holders??[],registry,context:params}),missingTargets.map(target=>`dependency_target_unresolved:${target}`)}export{assertDependencyEdgesAllowed,assertDependencyTargetsResolvable,assertValidBareDependencyFlagValue,requireDependencyKind};
1
+ import{EXIT_CODE as s}from"../core/shared/constants.js";import{PmCliError as a}from"../core/shared/errors.js";import{toErrorMessage as m}from"../core/shared/primitives.js";import{DEPENDENCY_KIND_VALUES as g}from"../types/index.js";import{locateItem as f,readLocatedItem as h}from"../core/store/item-store.js";import{isExternalDependencySourceKind as _}from"./dependency-provenance.js";import{resolveWorkspaceRelationshipKindRegistry as c}from"./graph/assembly.js";import{assertRelationshipEdgeAllowed as w}from"./relationships.js";function U(e,t=c()){const i=t.resolve(e);if(i)return i.kind;const o=new Set(g),n=[...g,...t.list().filter(({kind:r})=>!o.has(r)).flatMap(({kind:r,aliases:d})=>[r,...d])];throw new a(`Invalid dependency kind value "${e}". Allowed: ${n.join(", ")}`,s.USAGE,{field:"kind",value:e,recovery:{allowed_values:n},required:`dependency kind must be one of: ${n.join(", ")}.`,nextSteps:["Choose a registered kind, or install and enable the extension that registers this kind before retrying."]})}function F(e,t,i="--dep"){if(!t&&/[:,=]/.test(e))throw new a(`Invalid ${i} value "${e}". Use a bare item id or id=<id>,kind=<kind>.`,s.USAGE,{code:"dependency_flag_value_invalid",reason:"malformed_dependency_shorthand",flag:i,value:e,required:"Use a bare item id or an explicit id=<id>,kind=<kind> entry."})}function q(e,t,i=c()){for(const o of t??[])try{w(e,o.id,o.kind,i)}catch(n){throw new a(m(n),s.USAGE,{code:"dependency_edge_not_allowed",why:`${e} -> ${o.id} (${o.kind}) violates the active relationship-kind policy`})}}async function y(e,t){return(await h(e,{schema:t})).document.metadata.created_at}async function v(e,t){if(e.createdAt!==void 0)return e.createdAt;const i=await f(t.pmRoot,e.id,t.idPrefix,t.itemFormat,t.typeToFolder);return i===null?void 0:y(i,t.schema)}function k(e){const t=e.registry.require(e.dependency.kind);return new a(`${t.kind} requires source ${e.holder.id} to be created after target ${e.dependency.id}`,s.USAGE,{code:"dependency_temporal_order_invalid",reason:"source_not_after_target",required:`${e.holder.id}.created_at must be later than ${e.dependency.id}.created_at for ${t.kind}.`,why:"Chronological recurrence direction must be validated before the relationship is persisted.",source_id:e.holder.id,source_created_at:e.sourceCreatedAt,target_id:e.dependency.id,target_created_at:e.targetCreatedAt,temporal_order:t.temporalOrder})}async function $(e){const t=e.dependencies.filter(n=>e.registry.resolve(n.kind)?.temporalOrder==="source_after_target"&&!e.missingTargets.includes(n.id));if(t.length===0||e.holders.length===0)return;const i=new Map(e.resolutions.flatMap(({target:n,located:r})=>r===null?[]:[[n,r]])),o=new Map(await Promise.all([...new Set(t.map(({id:n})=>n))].map(async n=>[n,await y(i.get(n),e.context.schema)])));for(const n of e.holders){const r=await v(n,e.context);if(r!==void 0)for(const d of t){const l=o.get(d.id),u=Date.parse(r),p=Date.parse(l);if(!(Number.isFinite(u)&&Number.isFinite(p)&&u>p))throw k({holder:n,dependency:d,sourceCreatedAt:r,targetCreatedAt:l,registry:e.registry})}}}async function N(e){const t=e.registry??c(),i=(e.dependencies??[]).filter(d=>!_(d.source_kind)),o=[...new Set(i.map(d=>d.id))],n=await Promise.all(o.map(async d=>({target:d,located:await f(e.pmRoot,d,e.idPrefix,e.itemFormat,e.typeToFolder)}))),r=n.filter(({located:d})=>d===null).map(({target:d})=>d).sort((d,l)=>d<l?-1:1);if(r.length>0&&e.allowUnresolved!==!0)throw new a(`Dependency target${r.length===1?"":"s"} not found: ${r.join(", ")}`,s.NOT_FOUND,{code:"dependency_target_not_found",reason:"unresolved_local_dependency",required:"Every local dependency target must exist before the edge is committed.",why:"Fail-fast target resolution prevents dangling graph nodes and preserves reliable traversal semantics.",unresolved_targets:r,examples:["--dep id=<existing-item-id>,kind=related","--dep id=<external-id>,kind=related,source_kind=external","--allow-unresolved-deps --dep id=<future-item-id>,kind=related"],nextSteps:[`Create or correct ${r.length===1?"the target":"the targets"}, then retry the mutation.`,"Use source_kind=external for a cross-workspace reference.","Use --allow-unresolved-deps only when the dangling local edge is intentional."],recovery:{recovery_mode:"compact",missing:r,suggested_flags:["--allow-unresolved-deps"],suggested_retry:`pm search "${r[0]}" --limit 10`}});return await $({dependencies:i,missingTargets:r,resolutions:n,holders:e.holders??[],registry:t,context:e}),r.map(d=>`dependency_target_unresolved:${d}`)}export{q as assertDependencyEdgesAllowed,N as assertDependencyTargetsResolvable,F as assertValidBareDependencyFlagValue,U as requireDependencyKind};
2
2
  //# sourceMappingURL=dependency-flag-validation.js.map
@@ -1,2 +1,2 @@
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]="6c580b70-76eb-51db-8587-99b73dd20875")}catch{}})();import{normalizeItemId}from"../core/item/id.js";import{isExternalDependencyReference,isExternalDependencySourceKind}from"../core/item/dependency-reference.js";import{isExternalDependencyReference as isExternalDependencyReference2,isExternalDependencySourceKind as isExternalDependencySourceKind2}from"../core/item/dependency-reference.js";const EXTERNAL_DEPENDENCY_SOURCE_KIND="global",EXTERNAL_DEPENDENCY_SOURCE_KIND_ALIAS="external",EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES=["open","closed","unknown"],externalDependencyResolvers=new Map,MAX_EXTERNAL_TITLE_LENGTH=240,MAX_EXTERNAL_SOURCE_LENGTH=2048;function boundedExternalText(value,fallback,maximumLength){return(value?.trim()||fallback).slice(0,maximumLength)}function isExternalDependencyResolverResult(value){if(typeof value!="object"||value===null||Array.isArray(value))return!1;const candidate=value;return typeof candidate.status=="string"&&(candidate.title==null||typeof candidate.title=="string")&&(candidate.source==null||typeof candidate.source=="string")&&(candidate.checkedAt==null||typeof candidate.checkedAt=="string")}function registerExternalDependencyResolver(resolver){const name=resolver.name.trim();if(name.length===0)throw new Error("External dependency resolver name must not be empty");if(externalDependencyResolvers.has(name))throw new Error(`External dependency resolver already registered: ${name}`);const registeredResolver={name,supports:reference=>resolver.supports(reference),resolve:reference=>resolver.resolve(reference)};return externalDependencyResolvers.set(name,registeredResolver),()=>{externalDependencyResolvers.get(name)===registeredResolver&&externalDependencyResolvers.delete(name)}}async function resolveExternalDependencyReference(reference,options={}){const id=reference.trim();if(!isExternalDependencyReference(id))return null;const resolvers=[...externalDependencyResolvers.values()].filter(resolver=>{try{return resolver.supports(id)}catch{return!1}}),outcomes=await Promise.allSettled(resolvers.map(resolver=>Promise.resolve().then(()=>resolver.resolve(id))));for(const[index,outcome]of outcomes.entries()){if(outcome.status!=="fulfilled"||!isExternalDependencyResolverResult(outcome.value))continue;const resolver=resolvers[index],candidate=outcome.value,status=EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES.includes(candidate.status)?candidate.status:"unknown",title=boundedExternalText(candidate.title,"",MAX_EXTERNAL_TITLE_LENGTH),source=boundedExternalText(candidate.source,id,MAX_EXTERNAL_SOURCE_LENGTH),observedAtMs=Date.parse(candidate.checkedAt?.trim()??""),checkedAt=Number.isFinite(observedAtMs)?new Date(observedAtMs).toISOString():options.now?.()??new Date().toISOString();return{id,status,resolved:status==="closed",title:title.length>0?title:null,source,checked_at:checkedAt,resolver:resolver.name}}return null}function normalizeDependencySourceKind(sourceKind){const trimmed=sourceKind?.trim();if(trimmed)return isExternalDependencySourceKind(trimmed)?EXTERNAL_DEPENDENCY_SOURCE_KIND:trimmed}function normalizeDependencySeedId(id,prefix,sourceKind){return normalizeItemReference(id,prefix,sourceKind)}function normalizeItemReference(reference,prefix,sourceKind){const trimmed=reference.trim();return isExternalDependencySourceKind(sourceKind)||isExternalDependencyReference(trimmed)?trimmed:normalizeItemId(trimmed,prefix)}export{EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES,EXTERNAL_DEPENDENCY_SOURCE_KIND,EXTERNAL_DEPENDENCY_SOURCE_KIND_ALIAS,isExternalDependencyReference2 as isExternalDependencyReference,isExternalDependencySourceKind2 as isExternalDependencySourceKind,normalizeDependencySeedId,normalizeDependencySourceKind,normalizeItemReference,registerExternalDependencyResolver,resolveExternalDependencyReference};
1
+ import{normalizeItemId as D}from"../core/item/id.js";import{isExternalDependencyReference as d,isExternalDependencySourceKind as p}from"../core/item/dependency-reference.js";import{isExternalDependencyReference as b,isExternalDependencySourceKind as C}from"../core/item/dependency-reference.js";const R="global",h="external",_=["open","closed","unknown"],c=new Map,A=240,N=2048;function E(t,e,n){return(t?.trim()||e).slice(0,n)}function S(t){if(typeof t!="object"||t===null||Array.isArray(t))return!1;const e=t;return typeof e.status=="string"&&(e.title==null||typeof e.title=="string")&&(e.source==null||typeof e.source=="string")&&(e.checkedAt==null||typeof e.checkedAt=="string")}function w(t){const e=t.name.trim();if(e.length===0)throw new Error("External dependency resolver name must not be empty");if(c.has(e))throw new Error(`External dependency resolver already registered: ${e}`);const n={name:e,supports:r=>t.supports(r),resolve:r=>t.resolve(r)};return c.set(e,n),()=>{c.get(e)===n&&c.delete(e)}}async function I(t,e={}){const n=t.trim();if(!d(n))return null;const r=[...c.values()].filter(o=>{try{return o.supports(n)}catch{return!1}}),f=await Promise.allSettled(r.map(o=>Promise.resolve().then(()=>o.resolve(n))));for(const[o,i]of f.entries()){if(i.status!=="fulfilled"||!S(i.value))continue;const m=r[o],s=i.value,l=_.includes(s.status)?s.status:"unknown",u=E(s.title,"",A),x=E(s.source,n,N),a=Date.parse(s.checkedAt?.trim()??""),y=Number.isFinite(a)?new Date(a).toISOString():e.now?.()??new Date().toISOString();return{id:n,status:l,resolved:l==="closed",title:u.length>0?u:null,source:x,checked_at:y,resolver:m.name}}return null}function L(t){const e=t?.trim();if(e)return p(e)?R:e}function k(t,e,n){return v(t,e,n)}function v(t,e,n){const r=t.trim();return p(n)||d(r)?r:D(r,e)}export{_ as EXTERNAL_DEPENDENCY_RESOLUTION_STATUSES,R as EXTERNAL_DEPENDENCY_SOURCE_KIND,h as EXTERNAL_DEPENDENCY_SOURCE_KIND_ALIAS,b as isExternalDependencyReference,C as isExternalDependencySourceKind,k as normalizeDependencySeedId,L as normalizeDependencySourceKind,v as normalizeItemReference,w as registerExternalDependencyResolver,I as resolveExternalDependencyReference};
2
2
  //# sourceMappingURL=dependency-provenance.js.map
package/dist/sdk/docs.js CHANGED
@@ -1,2 +1,2 @@
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]="b1de9573-b582-502d-8fb1-9e6ba3a521b0")}catch{}})();import{renameArtifactsResultKey,runLinkedArtifacts}from"./linked-artifacts.js";async function runDocs(id,options,global2){const result=await runLinkedArtifacts(id,options,global2,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return renameArtifactsResultKey(result,"docs")}export{runDocs};
1
+ import{renameArtifactsResultKey as r,runLinkedArtifacts as s}from"./linked-artifacts.js";async function c(t,e,a){const o=await s(t,e,a,{metadataKey:"docs",op:"docs_add",bareNoun:"doc",supportsAppendStable:!1});return r(o,"docs")}export{c as runDocs};
2
2
  //# sourceMappingURL=docs.js.map
@@ -1,2 +1,2 @@
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]="499dfc08-cf70-55fe-8868-65c3107e3a91")}catch{}})();import{resolvePmRoot}from"../core/store/paths.js";import{findDuplicateClusters}from"./similarity.js";async function runDuplicates(global2,options={}){const result=await findDuplicateClusters({pmRoot:resolvePmRoot(process.cwd(),global2.path),exhaustive:options.exhaustive,...options.status===void 0?{}:{statuses:options.status.flatMap(status=>status.split(",").map(value=>value.trim()).filter(Boolean))},...options.since===void 0?{}:{since:options.since},...options.threshold===void 0?{}:{threshold:options.threshold},...options.limit===void 0?{}:{limit:options.limit}});return{...result,clusters:result.clusters.map(cluster=>{const canonicalId=cluster.id;return{...cluster,canonical_id:canonicalId,close_command:`pm close <duplicate-id> --duplicate-of ${canonicalId}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}export{runDuplicates};
1
+ import{resolvePmRoot as l}from"../core/store/paths.js";import{findDuplicateClusters as d}from"./similarity.js";async function n(c,e={}){const a=await d({pmRoot:l(process.cwd(),c.path),exhaustive:e.exhaustive,...e.status===void 0?{}:{statuses:e.status.flatMap(t=>t.split(",").map(i=>i.trim()).filter(Boolean))},...e.since===void 0?{}:{since:e.since},...e.threshold===void 0?{}:{threshold:e.threshold},...e.limit===void 0?{}:{limit:e.limit}});return{...a,clusters:a.clusters.map(t=>{const i=t.id;return{...t,canonical_id:i,close_command:`pm close <duplicate-id> --duplicate-of ${i}`}}),guidance:{strategy:"review_then_close_duplicate",command:"pm close <duplicate-id> --duplicate-of <canonical-id>"}}}export{n as runDuplicates};
2
2
  //# sourceMappingURL=duplicates.js.map
@@ -1,2 +1,2 @@
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]="62b04ebf-f842-5a88-8817-ed9b17350034")}catch{}})();import{classifyHostEnvironmentFault,translateHostEnvironmentFault,withHostEnvironmentBoundary}from"../../core/fs/host-environment-errors.js";export{classifyHostEnvironmentFault,translateHostEnvironmentFault,withHostEnvironmentBoundary};
1
+ import{classifyHostEnvironmentFault as o,translateHostEnvironmentFault as r,withHostEnvironmentBoundary as a}from"../../core/fs/host-environment-errors.js";export{o as classifyHostEnvironmentFault,r as translateHostEnvironmentFault,a as withHostEnvironmentBoundary};
2
2
  //# sourceMappingURL=host-environment-errors.js.map
@@ -1,3 +1,3 @@
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]="27729f1f-7de5-5907-943e-88b4b6093842")}catch{}})();import fs from"node:fs";import path from"node:path";import{createRequire}from"node:module";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{BASELINE_ITEM_FORMAT_VERSION,requiredItemFormatVersion}from"../../core/item/item-format-version.js";import{resolveWorkspaceRoot}from"../../core/store/paths.js";const PACKAGE_NAME="@unbrained/pm-cli",MUTATING_COMMANDS=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),GLOBAL_VALUE_FLAGS=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),VERSION_PATTERN=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN="2026.8.31";function hasAnyToken(argv,tokens){return argv.some(token=>tokens.includes(token.split("=",1)[0]))}function isPackageMutation(argv,positionals){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(positionals[0]??"")||hasAnyToken(argv,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}const MIXED_COMMAND_CLASSIFIERS={changelog:(argv,positionals)=>{if(positionals[0]==="generate")return!hasAnyToken(argv,["--check"]);const exportIndex=argv.indexOf("export");return positionals[0]==="export"&&(hasAnyToken(argv,["--output"])||exportIndex>=0&&argv[exportIndex+1]!==void 0&&!argv[exportIndex+1].startsWith("-"))},comments:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),config:(_argv,positionals)=>(positionals[0]==="project"||positionals[0]==="global"?positionals[1]:positionals[0])==="set",deps:()=>!1,docs:argv=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:isPackageMutation,files:(argv,positionals)=>hasAnyToken(argv,["--add","--add-glob","--migrate","--remove"])||positionals[0]==="discover"&&hasAnyToken(argv,["--apply"]),health:argv=>!hasAnyToken(argv,["--check-only","--no-refresh","--skip-vectors"]),learnings:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),merge:(_argv,positionals)=>positionals[0]!=="report",notes:argv=>hasAnyToken(argv,["--add","--delete","--edit","--file","--stdin"]),package:isPackageMutation,packages:isPackageMutation,profile:(_argv,positionals)=>positionals[0]==="apply",schema:(argv,positionals)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(positionals[0]??"")&&!(hasAnyToken(argv,["--infer"])&&!hasAnyToken(argv,["--apply"])),telemetry:(_argv,positionals)=>positionals.slice(0,2).some(token=>["clear","flush"].includes(token)),templates:(_argv,positionals)=>positionals[0]==="save",test:argv=>hasAnyToken(argv,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:argv=>hasAnyToken(argv,["--auto-fix","--prune-missing"]),vcs:(_argv,positionals)=>["abandon","create","merge","propose","ref-create"].includes(positionals[0]??""),workspace:(_argv,positionals)=>positionals[0]==="snapshot"&&["create","delete","restore"].includes(positionals[1]??"")};function parseDateVersion(value){const match=value.match(VERSION_PATTERN);return match?[Number(match[1]),Number(match[2]),Number(match[3]),Number(match[4]??0)]:null}function comparePmDateVersions(left,right){const leftParts=parseDateVersion(left),rightParts=parseDateVersion(right);if(!leftParts||!rightParts)return null;for(let index=0;index<leftParts.length;index+=1){const delta=leftParts[index]-rightParts[index];if(delta!==0)return Math.sign(delta)}return 0}function historyItemHashVersionForRuntime(version){return comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1?3:2}function findIncompatibleHistoryEpochPin(pins,writerItemHashVersion){if(writerItemHashVersion===3)return pins.filter(pin=>pin.history_epoch_compatible===!1).map(pin=>({...pin,declaration:pin.declaration??pin.version})).sort((left,right)=>comparePmDateVersions(left.version,right.version))[0]}function readJsonRecord(filePath){try{const parsed=JSON.parse(fs.readFileSync(filePath,"utf8"));return typeof parsed=="object"&&parsed!==null&&!Array.isArray(parsed)?parsed:null}catch{return null}}function rangeUpperBounds(alternative){const comparators=[...alternative.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(match=>({inclusive:match[1]==="<=",version:match[2]})),hyphen=alternative.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return hyphen?[...comparators,{inclusive:!0,version:hyphen[1]}]:comparators}function analyzeHistoryEpochRange(specification){const alternativeBounds=specification.split("||").map(alternative=>rangeUpperBounds(alternative));return{bounded:alternativeBounds.some(bounds=>bounds.length>0),compatible:alternativeBounds.some(bounds=>bounds.every(bound=>{const comparison=comparePmDateVersions(HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,bound.version);return comparison!==null&&(bound.inclusive?comparison!==1:comparison===-1)}))}}function dependencyDeclarations(packageJson){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(field=>{const dependencies=packageJson[field];if(typeof dependencies!="object"||dependencies===null)return[];const value=dependencies[PACKAGE_NAME];return typeof value=="string"?[value.trim()]:[]})}function dependencyPins(packageJson){return dependencyDeclarations(packageJson).flatMap(specification=>{const version=/^[<!]/u.test(specification)?void 0:specification.match(VERSION_PATTERN)?.[0];if(!version)return[];const exact=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(specification),range=analyzeHistoryEpochRange(specification);return[{version,constraint:exact?"exact":range.bounded?"range":"minimum",...exact?{}:{declaration:specification},history_epoch_compatible:exact?comparePmDateVersions(version,HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN)!==-1:range.compatible}]})}function packageLockPin(projectRoot){const packages=readJsonRecord(path.join(projectRoot,"package-lock.json"))?.packages;if(typeof packages!="object"||packages===null)return;const installed=packages["node_modules/@unbrained/pm-cli"];if(typeof installed!="object"||installed===null)return;const version=installed.version;return typeof version=="string"?version:void 0}function textLockPin(projectRoot,file){try{const lines=fs.readFileSync(path.join(projectRoot,file),"utf8").split(/\r?\n/u),packageLineIndex=lines.findIndex(line=>line.includes(PACKAGE_NAME));if(packageLineIndex<0)return;const packageIndent=lines[packageLineIndex].match(/^\s*/u)[0].length,entry=[lines[packageLineIndex]];for(let index=packageLineIndex+1;index<lines.length;index+=1){const line=lines[index],trimmed=line.trim(),indent=line.match(/^\s*/u)[0].length;if(trimmed.length>0&&indent<=packageIndent)break;entry.push(line)}return entry.join(`
2
- `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??entry[0].match(VERSION_PATTERN)?.[0]}catch{return}}function discoverProjectRuntimeVersionPins(projectRoot){const pins=[],projectPackage=readJsonRecord(path.join(projectRoot,"package.json"));projectPackage&&pins.push(...dependencyPins(projectPackage).map(pin=>({...pin,source:"package.json"})));const installedVersion=readJsonRecord(path.join(projectRoot,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof installedVersion=="string"&&parseDateVersion(installedVersion)&&pins.push({version:installedVersion,source:"installed-package",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(installedVersion)===3});const packageLockVersion=packageLockPin(projectRoot);packageLockVersion&&parseDateVersion(packageLockVersion)&&pins.push({version:packageLockVersion,source:"package-lock.json",constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(packageLockVersion)===3});for(const file of["pnpm-lock.yaml","yarn.lock"]){const version=textLockPin(projectRoot,file);version&&pins.push({version,source:file,constraint:"exact",history_epoch_compatible:historyItemHashVersionForRuntime(version)===3})}return pins}function assertProjectRuntimeFormatGuard(projectRoot,formatVersion){if(formatVersion<=1)return;const{minVersion,lt}=createRequire(import.meta.url)("semver"),declaration=dependencyDeclarations(readJsonRecord(path.join(projectRoot,"package.json"))??{}).find(specification=>{try{const minimum=minVersion(specification);return minimum!==null&&lt(minimum,"2026.10.10")}catch{return!1}}),incompatible=declaration===void 0?discoverProjectRuntimeVersionPins(projectRoot).find(pin=>comparePmDateVersions(pin.version,"2026.10.10")===-1):{version:declaration,source:"package.json"};if(incompatible)throw new PmCliError(`The project selects pm ${incompatible.version}, which cannot safely refuse item format ${formatVersion}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:incompatible.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function stampRequiredItemFormat(metadata,pmRoot){const requiredFormat=requiredItemFormatVersion(metadata);requiredFormat<=BASELINE_ITEM_FORMAT_VERSION||(assertProjectRuntimeFormatGuard(resolveWorkspaceRoot(pmRoot),requiredFormat),metadata.pm_format_version=requiredFormat)}function commandTokenFromArgv(argv){for(let index=0;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}if(!token.startsWith("-"))return{command:token.toLowerCase(),index}}}function isProjectMutatingInvocation(argv){const commandToken=commandTokenFromArgv(argv);if(!commandToken||hasAnyToken(argv,["--help","-h","--dry-run"]))return!1;const{command,index:commandIndex}=commandToken,positionals=[];for(let index=commandIndex+1;index<argv.length;index+=1){const token=argv[index];if(GLOBAL_VALUE_FLAGS.has(token)){index+=1;continue}token.startsWith("-")||positionals.push(token.toLowerCase())}const mixedClassifier=MIXED_COMMAND_CLASSIFIERS[command];return mixedClassifier?mixedClassifier(argv,positionals):MUTATING_COMMANDS.has(command)}function inspectProjectRuntimeCompatibility(options){const command=commandTokenFromArgv(options.argv)?.command,mutating=isProjectMutatingInvocation(options.argv),pins=discoverProjectRuntimeVersionPins(options.projectRoot).filter(pin=>comparePmDateVersions(pin.version,options.executingVersion)!==null).sort((left,right)=>comparePmDateVersions(right.version,left.version)),newest=pins[0],stale=newest!==void 0&&comparePmDateVersions(options.executingVersion,newest.version)===-1,writerItemHashVersion=historyItemHashVersionForRuntime(options.executingVersion),incompatibleEpochPin=findIncompatibleHistoryEpochPin(pins,writerItemHashVersion),historyEpochIncompatible=mutating&&incompatibleEpochPin!==void 0,warning=stale&&!mutating?{code:"project_runtime_stale_read",executing_version:options.executingVersion,project_version:newest.version,source:newest.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${PACKAGE_NAME} ${newest.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!mutating||!stale&&!historyEpochIncompatible||options.allowStale===!0,executing_version:options.executingVersion,...newest?{project_version:newest.version,source:newest.source}:{},...command?{command}:{},mutating,stale,history_epoch_incompatible:historyEpochIncompatible,writer_item_hash_version:writerItemHashVersion,...incompatibleEpochPin?{incompatible_project_version:incompatibleEpochPin.declaration,incompatible_source:incompatibleEpochPin.source}:{},...warning?{warning}:{},override_applied:mutating&&(stale||historyEpochIncompatible)&&options.allowStale===!0}}function assertProjectRuntimeCompatibility(options){const result=inspectProjectRuntimeCompatibility(options);if(result.compatible)return result;throw result.history_epoch_incompatible?new PmCliError(`pm ${result.executing_version} cannot write item-hash epoch ${result.writer_item_hash_version} into a project pinned to pm ${result.incompatible_project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:result.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${result.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${PACKAGE_NAME} pin to ${HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new PmCliError(`pm ${result.executing_version} cannot mutate a project pinned to newer pm ${result.project_version}.`,EXIT_CODE.CONFLICT,{code:"project_runtime_stale_mutation",reason:result.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${PACKAGE_NAME} ${result.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,PmCliError,assertProjectRuntimeCompatibility,assertProjectRuntimeFormatGuard,comparePmDateVersions,discoverProjectRuntimeVersionPins,historyItemHashVersionForRuntime,inspectProjectRuntimeCompatibility,isProjectMutatingInvocation,stampRequiredItemFormat};
1
+ import w from"node:fs";import m from"node:path";import{createRequire as L}from"node:module";import{EXIT_CODE as b}from"../../core/shared/constants.js";import{PmCliError as f}from"../../core/shared/errors.js";import{BASELINE_ITEM_FORMAT_VERSION as P,requiredItemFormatVersion as C}from"../../core/item/item-format-version.js";import{resolveWorkspaceRoot as T}from"../../core/store/paths.js";const h="@unbrained/pm-cli",N=new Set(["append","claim","changelog","close","close-many","close-task","comments","config","copy","create","dedupe-merge","delete","deps","docs","extension","event","events","files","focus","gc","history-author-acknowledge","history-compact","history-redact","history-repair","init","install","item","learnings","meet","merge","normalize","notes","package","packages","pause-task","plan","profile","reindex","release","remind","restore","schema","start-task","test","test-all","test-runs","test-runs-worker","telemetry","templates","twin","update","update-many","upgrade","vcs","workspace"]),I=new Set(["--author","--expect-hash","--output-budget","--output-format","--output-include","--output-limit","--output-session","--path","--pm-path"]),k=/\b(\d{4})\.(\d{1,2})\.(\d{1,2})(?:-(\d+))?\b/u,g="2026.8.31";function c(t,e){return t.some(n=>e.includes(n.split("=",1)[0]))}function j(t,e){return["activate","adopt","adopt-all","deactivate","init","install","migrate","reload","uninstall"].includes(e[0]??"")||c(t,["--activate","--adopt","--adopt-all","--deactivate","--fix-managed-state","--init","--install","--output","--reload","--scaffold","--uninstall"])}const R={changelog:(t,e)=>{if(e[0]==="generate")return!c(t,["--check"]);const n=t.indexOf("export");return e[0]==="export"&&(c(t,["--output"])||n>=0&&t[n+1]!==void 0&&!t[n+1].startsWith("-"))},comments:t=>c(t,["--add","--delete","--edit","--file","--stdin"]),config:(t,e)=>(e[0]==="project"||e[0]==="global"?e[1]:e[0])==="set",deps:()=>!1,docs:t=>c(t,["--add","--add-glob","--migrate","--remove"]),duplicates:()=>!1,events:()=>!1,extension:j,files:(t,e)=>c(t,["--add","--add-glob","--migrate","--remove"])||e[0]==="discover"&&c(t,["--apply"]),health:t=>!c(t,["--check-only","--no-refresh","--skip-vectors"]),learnings:t=>c(t,["--add","--delete","--edit","--file","--stdin"]),merge:(t,e)=>e[0]!=="report",notes:t=>c(t,["--add","--delete","--edit","--file","--stdin"]),package:j,packages:j,profile:(t,e)=>e[0]==="apply",schema:(t,e)=>["add-field","add-status","add-type","remove-field","remove-status","remove-type","remap-status","rename-field","rename-type"].includes(e[0]??"")&&!(c(t,["--infer"])&&!c(t,["--apply"])),telemetry:(t,e)=>e.slice(0,2).some(n=>["clear","flush"].includes(n)),templates:(t,e)=>e[0]==="save",test:t=>c(t,["--update","--update-index","--add","--add-json","--background","--measure","--remove","--resume","--run","--stop"]),validate:t=>c(t,["--auto-fix","--prune-missing"]),vcs:(t,e)=>["abandon","create","merge","propose","ref-create"].includes(e[0]??""),workspace:(t,e)=>e[0]==="snapshot"&&["create","delete","restore"].includes(e[1]??"")};function _(t){const e=t.match(k);return e?[Number(e[1]),Number(e[2]),Number(e[3]),Number(e[4]??0)]:null}function u(t,e){const n=_(t),o=_(e);if(!n||!o)return null;for(let r=0;r<n.length;r+=1){const i=n[r]-o[r];if(i!==0)return Math.sign(i)}return 0}function v(t){return u(t,g)!==-1?3:2}function V(t,e){if(e===3)return t.filter(n=>n.history_epoch_compatible===!1).map(n=>({...n,declaration:n.declaration??n.version})).sort((n,o)=>u(n.version,o.version))[0]}function y(t){try{const e=JSON.parse(w.readFileSync(t,"utf8"));return typeof e=="object"&&e!==null&&!Array.isArray(e)?e:null}catch{return null}}function M(t){const e=[...t.matchAll(/(<=|<)\s*v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/gu)].map(o=>({inclusive:o[1]==="<=",version:o[2]})),n=t.match(/\b\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?\s+-\s+v?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/u);return n?[...e,{inclusive:!0,version:n[1]}]:e}function O(t){const e=t.split("||").map(n=>M(n));return{bounded:e.some(n=>n.length>0),compatible:e.some(n=>n.every(o=>{const r=u(g,o.version);return r!==null&&(o.inclusive?r!==1:r===-1)}))}}function S(t){return["dependencies","devDependencies","optionalDependencies","peerDependencies"].flatMap(e=>{const n=t[e];if(typeof n!="object"||n===null)return[];const o=n[h];return typeof o=="string"?[o.trim()]:[]})}function F(t){return S(t).flatMap(e=>{const n=/^[<!]/u.test(e)?void 0:e.match(k)?.[0];if(!n)return[];const o=/^(?:=|v)?\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?$/u.test(e),r=O(e);return[{version:n,constraint:o?"exact":r.bounded?"range":"minimum",...o?{}:{declaration:e},history_epoch_compatible:o?u(n,g)!==-1:r.compatible}]})}function $(t){const n=y(m.join(t,"package-lock.json"))?.packages;if(typeof n!="object"||n===null)return;const o=n["node_modules/@unbrained/pm-cli"];if(typeof o!="object"||o===null)return;const r=o.version;return typeof r=="string"?r:void 0}function D(t,e){try{const n=w.readFileSync(m.join(t,e),"utf8").split(/\r?\n/u),o=n.findIndex(d=>d.includes(h));if(o<0)return;const r=n[o].match(/^\s*/u)[0].length,i=[n[o]];for(let d=o+1;d<n.length;d+=1){const l=n[d],p=l.trim(),x=l.match(/^\s*/u)[0].length;if(p.length>0&&x<=r)break;i.push(l)}return i.join(`
2
+ `).match(/^\s*version(?::\s*|\s+)["']?(\d{4}\.\d{1,2}\.\d{1,2}(?:-\d+)?)/mu)?.[1]??i[0].match(k)?.[0]}catch{return}}function A(t){const e=[],n=y(m.join(t,"package.json"));n&&e.push(...F(n).map(s=>({...s,source:"package.json"})));const r=y(m.join(t,"node_modules","@unbrained","pm-cli","package.json"))?.version;typeof r=="string"&&_(r)&&e.push({version:r,source:"installed-package",constraint:"exact",history_epoch_compatible:v(r)===3});const i=$(t);i&&_(i)&&e.push({version:i,source:"package-lock.json",constraint:"exact",history_epoch_compatible:v(i)===3});for(const s of["pnpm-lock.yaml","yarn.lock"]){const a=D(t,s);a&&e.push({version:a,source:s,constraint:"exact",history_epoch_compatible:v(a)===3})}return e}function q(t,e){if(e<=1)return;const{minVersion:n,lt:o}=L(import.meta.url)("semver"),r=S(y(m.join(t,"package.json"))??{}).find(s=>{try{const a=n(s);return a!==null&&o(a,"2026.10.10")}catch{return!1}}),i=r===void 0?A(t).find(s=>u(s.version,"2026.10.10")===-1):{version:r,source:"package.json"};if(i)throw new f(`The project selects pm ${i.version}, which cannot safely refuse item format ${e}.`,b.CONFLICT,{code:"project_runtime_item_format_incompatible",reason:i.source,required:"Upgrade project pins, installed SDKs, CI hosts and Git merge drivers before writing guarded item formats.",nextSteps:["Use a pm runtime supporting the required item format throughout the project; preserve original item and history bytes, and never re-anchor history to satisfy an older host."]})}function Y(t,e){const n=C(t);n<=P||(q(T(e),n),t.pm_format_version=n)}function E(t){for(let e=0;e<t.length;e+=1){const n=t[e];if(I.has(n)){e+=1;continue}if(!n.startsWith("-"))return{command:n.toLowerCase(),index:e}}}function H(t){const e=E(t);if(!e||c(t,["--help","-h","--dry-run"]))return!1;const{command:n,index:o}=e,r=[];for(let s=o+1;s<t.length;s+=1){const a=t[s];if(I.has(a)){s+=1;continue}a.startsWith("-")||r.push(a.toLowerCase())}const i=R[n];return i?i(t,r):N.has(n)}function U(t){const e=E(t.argv)?.command,n=H(t.argv),o=A(t.projectRoot).filter(p=>u(p.version,t.executingVersion)!==null).sort((p,x)=>u(x.version,p.version)),r=o[0],i=r!==void 0&&u(t.executingVersion,r.version)===-1,s=v(t.executingVersion),a=V(o,s),d=n&&a!==void 0,l=i&&!n?{code:"project_runtime_stale_read",executing_version:t.executingVersion,project_version:r.version,source:r.source,message:"This read is using an older pm runtime than the project requires.",next_steps:[`Run the command through the project's installed ${h} ${r.version}.`,"Install the project dependencies with its declared package manager if the local executable is missing."]}:void 0;return{compatible:!n||!i&&!d||t.allowStale===!0,executing_version:t.executingVersion,...r?{project_version:r.version,source:r.source}:{},...e?{command:e}:{},mutating:n,stale:i,history_epoch_incompatible:d,writer_item_hash_version:s,...a?{incompatible_project_version:a.declaration,incompatible_source:a.source}:{},...l?{warning:l}:{},override_applied:n&&(i||d)&&t.allowStale===!0}}function Q(t){const e=U(t);if(e.compatible)return e;throw e.history_epoch_incompatible?new f(`pm ${e.executing_version} cannot write item-hash epoch ${e.writer_item_hash_version} into a project pinned to pm ${e.incompatible_project_version}.`,b.CONFLICT,{code:"project_runtime_history_epoch_incompatible",reason:e.incompatible_source,why:`The pinned runtime cannot read item_hash_version ${e.writer_item_hash_version}; allowing the write would break its health and validation gates.`,nextSteps:[`Upgrade the project's ${h} pin to ${g} or newer before mutating tracker history.`,"For an intentional coordinated migration only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]}):new f(`pm ${e.executing_version} cannot mutate a project pinned to newer pm ${e.project_version}.`,b.CONFLICT,{code:"project_runtime_stale_mutation",reason:e.source,why:"An older runtime can write storage, history, and merge contracts it does not understand.",nextSteps:[`Run this command through the project's installed ${h} ${e.project_version}.`,"For an intentional recovery only, set PM_ALLOW_STALE_CLI=1 for this invocation and record why.","Read-only commands remain available without an override."]})}export{g as HISTORY_ITEM_HASH_VERSION_3_INTRODUCED_IN,f as PmCliError,Q as assertProjectRuntimeCompatibility,q as assertProjectRuntimeFormatGuard,u as comparePmDateVersions,A as discoverProjectRuntimeVersionPins,v as historyItemHashVersionForRuntime,U as inspectProjectRuntimeCompatibility,H as isProjectMutatingInvocation,Y as stampRequiredItemFormat};
3
3
  //# sourceMappingURL=project-runtime-compatibility.js.map
@@ -1,2 +1,2 @@
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]="6d1f8e03-97b4-5d83-b85c-e47f39c07d48")}catch{}})();const SOURCE_CONTEXT_ACCESS_ENV="PM_SOURCE_CONTEXT_ACCESS",SOURCE_CONTEXT_WRITE_OVERRIDE_ENV="PM_ALLOW_SOURCE_CONTEXT_WRITES";function resolveSourceContextWritePolicy(environment){const declaredAccess=environment[SOURCE_CONTEXT_ACCESS_ENV],access=declaredAccess===void 0||declaredAccess.trim().toLowerCase()==="write"?"write":"read_only",writeOverrideApplied=access==="read_only"&&environment[SOURCE_CONTEXT_WRITE_OVERRIDE_ENV]?.trim()==="1";return{access,write_override_applied:writeOverrideApplied,source_writes_allowed:access==="write"||writeOverrideApplied}}export{SOURCE_CONTEXT_ACCESS_ENV,SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,resolveSourceContextWritePolicy};
1
+ const o="PM_SOURCE_CONTEXT_ACCESS",E="PM_ALLOW_SOURCE_CONTEXT_WRITES";function i(r){const t=r[o],e=t===void 0||t.trim().toLowerCase()==="write"?"write":"read_only",_=e==="read_only"&&r[E]?.trim()==="1";return{access:e,write_override_applied:_,source_writes_allowed:e==="write"||_}}export{o as SOURCE_CONTEXT_ACCESS_ENV,E as SOURCE_CONTEXT_WRITE_OVERRIDE_ENV,i as resolveSourceContextWritePolicy};
2
2
  //# sourceMappingURL=source-context.js.map
@@ -1,2 +1,2 @@
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]="5c8194ff-d877-51b8-bd54-d206f85a979c")}catch{}})();import{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery}from"../../core/store/tracker-preflight.js";export{assertInitializedTracker,assertReadableTrackerRoot,buildTrackerInitializationRecovery};
1
+ import{assertInitializedTracker as a,assertReadableTrackerRoot as i,buildTrackerInitializationRecovery as t}from"../../core/store/tracker-preflight.js";export{a as assertInitializedTracker,i as assertReadableTrackerRoot,t as buildTrackerInitializationRecovery};
2
2
  //# sourceMappingURL=tracker-preflight.js.map
@@ -1,2 +1,2 @@
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]="7df4fe91-e8a4-540f-8737-c67f2efa460e")}catch{}})();const PM_ERROR_CODE_EXIT_CLASS_CONTRACTS=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],ERROR_CLASS_BY_EXIT_CODE=new Map(PM_ERROR_CODE_EXIT_CLASS_CONTRACTS.map(contract=>[contract.exit_code,contract.class]));function normalizeContractList(values){return[...new Set(values.map(value=>value.trim()).filter(Boolean))].sort()}function normalizeOwnedStates(states){if(!states)return[];const seenStates=new Set,seenProbes=new Set;return states.map(state=>{const normalizedState=state.state.trim(),probeId=state.probe_id.trim(),entrypoints=normalizeContractList(state.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(normalizedState)||!/^[a-z][a-z0-9-]*$/.test(probeId)||entrypoints.length===0||seenStates.has(normalizedState)||seenProbes.has(probeId))throw new TypeError("Invalid pm refusal state contract");return seenStates.add(normalizedState),seenProbes.add(probeId),{state:normalizedState,probe_id:probeId,entrypoints,expected_exit_class:state.expected_exit_class}}).sort((left,right)=>left.state.localeCompare(right.state))}function isValidNormalizedErrorCodeContract(declaration,sources,emittingCommands,canonicalCode,aliases){return![[1,2,3,4,5].includes(declaration.exit_code),declaration.meaning.trim().length>0,declaration.recovery.trim().length>0,sources.length>0,emittingCommands.length>0,/^[a-z][a-z0-9_]*$/.test(canonicalCode),aliases.every(alias=>/^[a-z][a-z0-9_]*$/.test(alias)),ERROR_CLASS_BY_EXIT_CODE.get(declaration.exit_code)===declaration.class].includes(!1)}function resolveCanonicalErrorCodeDeclaration(declaration,byCode){let current=declaration;const path=new Set;for(;current.canonical_code!==current.code;){if(path.has(current.code))throw new TypeError(`Alias cycle in pm error code catalog: ${declaration.code}`);path.add(current.code);const target=byCode.get(current.canonical_code);if(!target)throw new TypeError(`Invalid pm error code contract: ${declaration.code}`);current=target}return current}function validateErrorCodeAliases(declarations){const byCode=new Map(declarations.map(entry=>[entry.code,entry]));for(const declaration of declarations){const canonical=resolveCanonicalErrorCodeDeclaration(declaration,byCode);if(canonical.exit_code!==declaration.exit_code||canonical.class!==declaration.class)throw new TypeError(`Alias transport mismatch for pm error code: ${declaration.code}`);const expectedAliases=declarations.filter(candidate=>candidate.code!==canonical.code&&candidate.canonical_code===canonical.code).map(candidate=>candidate.code).sort();if(declaration.code===canonical.code?JSON.stringify(declaration.aliases)!==JSON.stringify(expectedAliases):declaration.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${declaration.code}`)}}function definePmErrorCodeCatalog(declarations){const seen=new Set,normalized=declarations.map(declaration=>{const code=declaration.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(code))throw new TypeError(`Invalid pm error code: ${JSON.stringify(declaration.code)}`);if(seen.has(code))throw new TypeError(`Duplicate pm error code: ${code}`);seen.add(code);const sources=normalizeContractList(declaration.sources),emittingCommands=normalizeContractList(declaration.emitting_commands),canonicalCode=(declaration.canonical_code??code).trim(),aliases=normalizeContractList(declaration.aliases??[]),ownedStates=normalizeOwnedStates(declaration.owned_states);if(!isValidNormalizedErrorCodeContract(declaration,sources,emittingCommands,canonicalCode,aliases))throw new TypeError(`Invalid pm error code contract: ${code}`);if(ownedStates.some(state=>state.expected_exit_class!==declaration.class))throw new TypeError(`Invalid pm refusal state exit class: ${code}`);return Object.freeze({...declaration,code,meaning:declaration.meaning.trim(),recovery:declaration.recovery.trim(),sources,emitting_commands:emittingCommands,canonical_code:canonicalCode,aliases,owned_states:ownedStates})});return validateErrorCodeAliases(normalized),Object.freeze(normalized.sort((left,right)=>left.code.localeCompare(right.code)))}function resolveCanonicalPmErrorCodeContract(code,catalog){const emitted=resolvePmErrorCodeContract(code,catalog);return resolvePmErrorCodeContract(emitted.canonical_code??emitted.code,catalog)}function resolvePmErrorCodeContract(code,catalog){const normalized=code.trim(),contract=catalog.find(entry=>entry.code===normalized);if(!contract)throw new TypeError(`Unknown pm error code "${normalized}"`);return contract}export{PM_ERROR_CODE_EXIT_CLASS_CONTRACTS,definePmErrorCodeCatalog,resolveCanonicalPmErrorCodeContract,resolvePmErrorCodeContract};
1
+ const _=[{exit_code:1,class:"generic_failure"},{exit_code:2,class:"usage"},{exit_code:3,class:"not_found"},{exit_code:4,class:"conflict"},{exit_code:5,class:"dependency_failed"}],f=new Map(_.map(t=>[t.exit_code,t.class]));function i(t){return[...new Set(t.map(n=>n.trim()).filter(Boolean))].sort()}function w(t){if(!t)return[];const n=new Set,o=new Set;return t.map(e=>{const r=e.state.trim(),c=e.probe_id.trim(),s=i(e.entrypoints);if(!/^[a-z][a-z0-9_]*$/.test(r)||!/^[a-z][a-z0-9-]*$/.test(c)||s.length===0||n.has(r)||o.has(c))throw new TypeError("Invalid pm refusal state contract");return n.add(r),o.add(c),{state:r,probe_id:c,entrypoints:s,expected_exit_class:e.expected_exit_class}}).sort((e,r)=>e.state.localeCompare(r.state))}function u(t,n,o,e,r){return![[1,2,3,4,5].includes(t.exit_code),t.meaning.trim().length>0,t.recovery.trim().length>0,n.length>0,o.length>0,/^[a-z][a-z0-9_]*$/.test(e),r.every(c=>/^[a-z][a-z0-9_]*$/.test(c)),f.get(t.exit_code)===t.class].includes(!1)}function C(t,n){let o=t;const e=new Set;for(;o.canonical_code!==o.code;){if(e.has(o.code))throw new TypeError(`Alias cycle in pm error code catalog: ${t.code}`);e.add(o.code);const r=n.get(o.canonical_code);if(!r)throw new TypeError(`Invalid pm error code contract: ${t.code}`);o=r}return o}function h(t){const n=new Map(t.map(o=>[o.code,o]));for(const o of t){const e=C(o,n);if(e.exit_code!==o.exit_code||e.class!==o.class)throw new TypeError(`Alias transport mismatch for pm error code: ${o.code}`);const r=t.filter(c=>c.code!==e.code&&c.canonical_code===e.code).map(c=>c.code).sort();if(o.code===e.code?JSON.stringify(o.aliases)!==JSON.stringify(r):o.aliases.length>0)throw new TypeError(`Invalid pm error code contract: ${o.code}`)}}function x(t){const n=new Set,o=t.map(e=>{const r=e.code.trim();if(!/^[a-z][a-z0-9_]*$/.test(r))throw new TypeError(`Invalid pm error code: ${JSON.stringify(e.code)}`);if(n.has(r))throw new TypeError(`Duplicate pm error code: ${r}`);n.add(r);const c=i(e.sources),s=i(e.emitting_commands),a=(e.canonical_code??r).trim(),d=i(e.aliases??[]),l=w(e.owned_states);if(!u(e,c,s,a,d))throw new TypeError(`Invalid pm error code contract: ${r}`);if(l.some(p=>p.expected_exit_class!==e.class))throw new TypeError(`Invalid pm refusal state exit class: ${r}`);return Object.freeze({...e,code:r,meaning:e.meaning.trim(),recovery:e.recovery.trim(),sources:c,emitting_commands:s,canonical_code:a,aliases:d,owned_states:l})});return h(o),Object.freeze(o.sort((e,r)=>e.code.localeCompare(r.code)))}function E(t,n){const o=m(t,n);return m(o.canonical_code??o.code,n)}function m(t,n){const o=t.trim(),e=n.find(r=>r.code===o);if(!e)throw new TypeError(`Unknown pm error code "${o}"`);return e}export{_ as PM_ERROR_CODE_EXIT_CLASS_CONTRACTS,x as definePmErrorCodeCatalog,E as resolveCanonicalPmErrorCodeContract,m as resolvePmErrorCodeContract};
2
2
  //# sourceMappingURL=error-code-catalog.js.map