@unbrained/pm-cli 2026.10.3 → 2026.10.5

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 (742) hide show
  1. package/.claude-plugin/marketplace.json +2 -2
  2. package/CHANGELOG.md +28 -2
  3. package/dist/cli/after-command-context-usage.js +1 -1
  4. package/dist/cli/argv-utils.js +1 -1
  5. package/dist/cli/bootstrap-args.js +1 -1
  6. package/dist/cli/bundle-integrity.js +2 -2
  7. package/dist/cli/command-namespaces.js +1 -1
  8. package/dist/cli/commander-usage.d.ts +1 -1
  9. package/dist/cli/commander-usage.js +7 -4
  10. package/dist/cli/commands/annotations/comments.js +1 -1
  11. package/dist/cli/commands/annotations/docs.js +1 -1
  12. package/dist/cli/commands/annotations/files.js +1 -1
  13. package/dist/cli/commands/annotations/learnings.js +1 -1
  14. package/dist/cli/commands/annotations/notes.js +1 -1
  15. package/dist/cli/commands/extension/describe.js +1 -1
  16. package/dist/cli/commands/extension/extension.js +1 -1
  17. package/dist/cli/commands/extension/scaffold.js +1 -1
  18. package/dist/cli/commands/extension/shared.js +1 -1
  19. package/dist/cli/commands/governance/gc.js +1 -1
  20. package/dist/cli/commands/governance/health.js +1 -1
  21. package/dist/cli/commands/governance/telemetry.js +1 -1
  22. package/dist/cli/commands/governance/validate.js +1 -1
  23. package/dist/cli/commands/history/activity.js +1 -1
  24. package/dist/cli/commands/history/history-compact.js +1 -1
  25. package/dist/cli/commands/history/history-redact.js +1 -1
  26. package/dist/cli/commands/history/history-repair.js +1 -1
  27. package/dist/cli/commands/history/history.js +1 -1
  28. package/dist/cli/commands/history/restore.js +1 -1
  29. package/dist/cli/commands/lifecycle/append.js +1 -1
  30. package/dist/cli/commands/lifecycle/claim.js +1 -1
  31. package/dist/cli/commands/lifecycle/close-many.js +1 -1
  32. package/dist/cli/commands/lifecycle/close.js +1 -1
  33. package/dist/cli/commands/lifecycle/copy.js +1 -1
  34. package/dist/cli/commands/lifecycle/create.js +1 -1
  35. package/dist/cli/commands/lifecycle/delete.js +1 -1
  36. package/dist/cli/commands/lifecycle/focus.js +1 -1
  37. package/dist/cli/commands/lifecycle/plan.js +1 -1
  38. package/dist/cli/commands/lifecycle/update-many.js +1 -1
  39. package/dist/cli/commands/lifecycle/update.js +1 -1
  40. package/dist/cli/commands/query/aggregate.js +1 -1
  41. package/dist/cli/commands/query/context.js +1 -1
  42. package/dist/cli/commands/query/deps.js +1 -1
  43. package/dist/cli/commands/query/duplicates.js +1 -1
  44. package/dist/cli/commands/query/eval.js +1 -1
  45. package/dist/cli/commands/query/get.js +1 -1
  46. package/dist/cli/commands/query/graph.js +1 -1
  47. package/dist/cli/commands/query/list.js +1 -1
  48. package/dist/cli/commands/query/next.js +1 -1
  49. package/dist/cli/commands/query/search.js +1 -1
  50. package/dist/cli/commands/query/stats.js +1 -1
  51. package/dist/cli/commands/test/test-all.js +1 -1
  52. package/dist/cli/commands/test/test-runs.js +1 -1
  53. package/dist/cli/commands/test/test.js +1 -1
  54. package/dist/cli/commands/workspace/config.js +1 -1
  55. package/dist/cli/commands/workspace/contracts.js +1 -1
  56. package/dist/cli/commands/workspace/init.js +1 -1
  57. package/dist/cli/commands/workspace/merge.js +1 -1
  58. package/dist/cli/commands/workspace/profile.js +1 -1
  59. package/dist/cli/commands/workspace/schema.js +1 -1
  60. package/dist/cli/commands/workspace/upgrade.js +1 -1
  61. package/dist/cli/context-intent-invocation.js +1 -1
  62. package/dist/cli/description-stdin.js +1 -1
  63. package/dist/cli/error-guidance.js +3 -1
  64. package/dist/cli/extension-command-help.js +5 -3
  65. package/dist/cli/extension-command-options.js +1 -1
  66. package/dist/cli/extension-recovery.js +1 -1
  67. package/dist/cli/help-content.js +5 -2
  68. package/dist/cli/help-json-payload.js +6 -3
  69. package/dist/cli/invocation-profile.js +2 -2
  70. package/dist/cli/main.js +5 -5
  71. package/dist/cli/migration-gates.js +1 -1
  72. package/dist/cli/option-values.js +1 -1
  73. package/dist/cli/public.js +1 -1
  74. package/dist/cli/register-annotations.js +1 -1
  75. package/dist/cli/register-assurance.js +1 -1
  76. package/dist/cli/register-files-lookup.js +1 -1
  77. package/dist/cli/register-history-activity.js +1 -1
  78. package/dist/cli/register-history-author.js +1 -1
  79. package/dist/cli/register-history-maintenance.js +2 -2
  80. package/dist/cli/register-list-query.js +10 -10
  81. package/dist/cli/register-mutation-options.js +1 -1
  82. package/dist/cli/register-mutation.js +2 -2
  83. package/dist/cli/register-operations.js +1 -1
  84. package/dist/cli/register-setup.js +1 -1
  85. package/dist/cli/register-structured-mutation.js +1 -1
  86. package/dist/cli/registration-helpers.js +1 -1
  87. package/dist/cli/runtime/activation.js +1 -1
  88. package/dist/cli/runtime/invocation-options.js +1 -1
  89. package/dist/cli/runtime/projection-retry.js +1 -1
  90. package/dist/cli/runtime/selection.js +1 -1
  91. package/dist/cli/runtime/telemetry-outcome.js +1 -1
  92. package/dist/cli/runtime-compatibility-boundary.d.ts +1 -1
  93. package/dist/cli/runtime-compatibility-boundary.js +4 -4
  94. package/dist/cli/schema/registration.js +2 -2
  95. package/dist/cli/schema-registration-helpers.js +1 -1
  96. package/dist/cli/search-refresh.js +1 -1
  97. package/dist/cli/stats-analytics-json.js +1 -1
  98. package/dist/cli/telemetry-flush.js +1 -1
  99. package/dist/cli-bundle/bundle-manifest.json +162 -162
  100. package/dist/cli-bundle/chunks/chunk-3CYOBJUK.js +3 -0
  101. package/dist/cli-bundle/chunks/chunk-5MNOWZPN.js +3 -0
  102. package/dist/cli-bundle/chunks/chunk-AJ7H6XUF.js +20 -0
  103. package/dist/cli-bundle/chunks/chunk-D332RXZ7.js +80 -0
  104. package/dist/cli-bundle/chunks/chunk-HRJ6G6ZG.js +31 -0
  105. package/dist/cli-bundle/chunks/chunk-KRVI56QE.js +6 -0
  106. package/dist/cli-bundle/chunks/chunk-N4YGSG6F.js +238 -0
  107. package/dist/cli-bundle/chunks/chunk-OOLYASYJ.js +2 -0
  108. package/dist/cli-bundle/chunks/chunk-R7CG2DB7.js +2 -0
  109. package/dist/cli-bundle/chunks/chunk-TGMONGWX.js +2 -0
  110. package/dist/cli-bundle/chunks/chunk-UZ7BIUCI.js +2 -0
  111. package/dist/cli-bundle/chunks/{chunk-44UGMMQ6.js → chunk-VZ63DEVJ.js} +3 -3
  112. package/dist/cli-bundle/chunks/chunk-WFZ4UEOB.js +2 -0
  113. package/dist/cli-bundle/chunks/chunk-YVBRASXO.js +8 -0
  114. package/dist/cli-bundle/chunks/{chunk-5XKF5SQV.js → chunk-Z66DWDAU.js} +91 -91
  115. package/dist/cli-bundle/chunks/{register-list-query-DYCGUQEW.js → register-list-query-75QXHIFH.js} +11 -11
  116. package/dist/cli-bundle/chunks/register-mutation-YS54SCHG.js +20 -0
  117. package/dist/cli-bundle/chunks/register-operations-6KHZQSYJ.js +2 -0
  118. package/dist/cli-bundle/chunks/register-setup-RTATEN2M.js +2 -0
  119. package/dist/cli-bundle/focused-chunks/{chunk-3BIYG72P.js → chunk-2CVX3KR3.js} +2 -2
  120. package/dist/cli-bundle/focused-chunks/chunk-5C3IDDW7.js +2 -0
  121. package/dist/cli-bundle/focused-chunks/{chunk-DBD4W4QP.js → chunk-ABV67XCC.js} +3 -3
  122. package/dist/cli-bundle/focused-chunks/chunk-B5RSLVE6.js +3 -0
  123. package/dist/cli-bundle/focused-chunks/chunk-C224METM.js +20 -0
  124. package/dist/cli-bundle/focused-chunks/chunk-CLDPTMQY.js +6 -0
  125. package/dist/cli-bundle/focused-chunks/chunk-DDRN42PB.js +8 -0
  126. package/dist/cli-bundle/focused-chunks/{chunk-EJN7DY3B.js → chunk-DOVTUKJQ.js} +2 -2
  127. package/dist/cli-bundle/focused-chunks/chunk-ECBOPEJE.js +75 -0
  128. package/dist/cli-bundle/focused-chunks/chunk-GITOYRUW.js +165 -0
  129. package/dist/cli-bundle/focused-chunks/chunk-GUIF3WVC.js +30 -0
  130. package/dist/cli-bundle/focused-chunks/chunk-LE4JUCRR.js +3 -0
  131. package/dist/cli-bundle/focused-chunks/{chunk-HFAW3FJQ.js → chunk-PSXFFQFT.js} +2 -2
  132. package/dist/cli-bundle/focused-chunks/chunk-RHIH6XIW.js +12 -0
  133. package/dist/cli-bundle/focused-chunks/chunk-UDYRVBOZ.js +2 -0
  134. package/dist/cli-bundle/focused-chunks/chunk-XV5RV4ZT.js +2 -0
  135. package/dist/cli-bundle/focused-chunks/{chunk-XRSCIYHR.js → chunk-YMU42COG.js} +2 -2
  136. package/dist/cli-bundle/main.js +28 -28
  137. package/dist/cli-bundle/sdk-authoring.js +1 -1
  138. package/dist/cli-bundle/sdk-contracts.js +2 -2
  139. package/dist/cli-bundle/sdk-core.js +32 -32
  140. package/dist/cli-bundle/sdk-governance.js +1 -1
  141. package/dist/cli-bundle/sdk-graph.js +1 -1
  142. package/dist/cli-bundle/sdk-merge.js +55 -55
  143. package/dist/cli-bundle/sdk-query.js +1 -1
  144. package/dist/cli-bundle/sdk-runtime.js +1 -1
  145. package/dist/cli-bundle/sdk-testing.js +1 -1
  146. package/dist/cli-bundle/sdk.js +10 -10
  147. package/dist/cli.js +1 -1
  148. package/dist/core/checkpoint/checkpoint-gc.js +1 -1
  149. package/dist/core/checkpoint/mutation-checkpoint.js +2 -2
  150. package/dist/core/config/nested-settings.js +1 -1
  151. package/dist/core/config/positional-value.js +1 -1
  152. package/dist/core/diagnostics/remediation.js +1 -1
  153. package/dist/core/extensions/activation-summary-markdown.js +2 -1
  154. package/dist/core/extensions/activation-summary.js +1 -1
  155. package/dist/core/extensions/activation-transaction.js +1 -1
  156. package/dist/core/extensions/capability-usage.js +1 -1
  157. package/dist/core/extensions/command-hook-context.js +1 -1
  158. package/dist/core/extensions/command-metadata-contract.js +1 -1
  159. package/dist/core/extensions/command-visibility-tier.js +1 -1
  160. package/dist/core/extensions/contribution-inventory.js +1 -1
  161. package/dist/core/extensions/exporter-output-contract.js +1 -1
  162. package/dist/core/extensions/extension-candidate.js +1 -1
  163. package/dist/core/extensions/extension-capability-aliases.js +1 -1
  164. package/dist/core/extensions/extension-hook-runtime.js +1 -1
  165. package/dist/core/extensions/extension-policy.js +1 -1
  166. package/dist/core/extensions/extension-registries.js +1 -1
  167. package/dist/core/extensions/extension-runtime-helpers.js +1 -1
  168. package/dist/core/extensions/extension-types.d.ts +8 -1
  169. package/dist/core/extensions/extension-types.js +1 -1
  170. package/dist/core/extensions/flag-definition-validation.js +1 -1
  171. package/dist/core/extensions/flag-value-types.js +1 -1
  172. package/dist/core/extensions/index.js +1 -1
  173. package/dist/core/extensions/item-field-types.js +1 -1
  174. package/dist/core/extensions/item-fields.js +1 -1
  175. package/dist/core/extensions/loader.js +1 -1
  176. package/dist/core/extensions/manifest-parser.js +1 -1
  177. package/dist/core/extensions/manifest-schema.js +1 -1
  178. package/dist/core/extensions/module-graph-snapshot.js +1 -1
  179. package/dist/core/extensions/preflight-ownership.js +1 -1
  180. package/dist/core/extensions/registration-contracts.js +1 -1
  181. package/dist/core/extensions/registration-validation.js +1 -1
  182. package/dist/core/extensions/registration-values.js +1 -1
  183. package/dist/core/extensions/reserved-host-flags.js +1 -1
  184. package/dist/core/extensions/runtime-registrations.js +1 -1
  185. package/dist/core/extensions/service-ownership.js +1 -1
  186. package/dist/core/extensions/version-compat.js +1 -1
  187. package/dist/core/fs/atomic-create.js +1 -1
  188. package/dist/core/fs/fs-utils.js +2 -2
  189. package/dist/core/fs/host-environment-errors.js +1 -1
  190. package/dist/core/fs/index.js +1 -1
  191. package/dist/core/fs/path-utils.js +1 -1
  192. package/dist/core/governance/content-fields.js +1 -1
  193. package/dist/core/governance/issue-codes.js +1 -1
  194. package/dist/core/governance/metadata-coverage.js +1 -1
  195. package/dist/core/history/digest.js +1 -1
  196. package/dist/core/history/drift-cache.js +3 -3
  197. package/dist/core/history/drift-scan.d.ts +4 -0
  198. package/dist/core/history/drift-scan.js +1 -1
  199. package/dist/core/history/event-classification.js +1 -1
  200. package/dist/core/history/event-index.js +8 -7
  201. package/dist/core/history/history-compact-bulk.js +1 -1
  202. package/dist/core/history/history-diff.js +1 -1
  203. package/dist/core/history/history-rewrite.js +1 -1
  204. package/dist/core/history/history-storage-stats.js +1 -1
  205. package/dist/core/history/history-stream-policy.js +1 -1
  206. package/dist/core/history/history.js +2 -2
  207. package/dist/core/history/identity.js +1 -1
  208. package/dist/core/history/index.js +1 -1
  209. package/dist/core/history/operation-contract.js +1 -1
  210. package/dist/core/history/projection.js +1 -1
  211. package/dist/core/history/read.js +1 -1
  212. package/dist/core/history/replay.js +2 -1
  213. package/dist/core/history/tombstone.js +1 -1
  214. package/dist/core/history/version-address.js +1 -1
  215. package/dist/core/history/workspace-history.js +2 -2
  216. package/dist/core/io/body-file.js +1 -1
  217. package/dist/core/io/bulk-ids-input.js +2 -1
  218. package/dist/core/item/actionability.js +1 -1
  219. package/dist/core/item/dependency-reference.js +1 -1
  220. package/dist/core/item/id.js +1 -1
  221. package/dist/core/item/index.js +1 -1
  222. package/dist/core/item/item-format-version.js +1 -1
  223. package/dist/core/item/item-format.js +6 -4
  224. package/dist/core/item/item-record.js +1 -1
  225. package/dist/core/item/item-type-definition.js +1 -1
  226. package/dist/core/item/parent-reference-policy.js +1 -1
  227. package/dist/core/item/parse.js +8 -2
  228. package/dist/core/item/plan-lifecycle.js +1 -1
  229. package/dist/core/item/priority.js +1 -1
  230. package/dist/core/item/sprint-release-format.js +1 -1
  231. package/dist/core/item/status-filter.js +1 -1
  232. package/dist/core/item/status.js +1 -1
  233. package/dist/core/item/toon-decode.js +1 -1
  234. package/dist/core/item/type-registry.js +1 -1
  235. package/dist/core/item/type-synonyms.js +1 -1
  236. package/dist/core/lock/index.js +1 -1
  237. package/dist/core/lock/lock-gc.js +1 -1
  238. package/dist/core/lock/lock.js +3 -3
  239. package/dist/core/output/mutation-projection.js +1 -1
  240. package/dist/core/output/output-control.js +1 -1
  241. package/dist/core/output/output.js +22 -10
  242. package/dist/core/output/query-summary.js +1 -1
  243. package/dist/core/output/tabular.js +3 -1
  244. package/dist/core/packages/manifest.js +1 -1
  245. package/dist/core/packages/root.js +1 -1
  246. package/dist/core/policy/workflow-policy-schema.js +1 -1
  247. package/dist/core/policy/workflow-policy-store.js +1 -1
  248. package/dist/core/policy/workflow-policy.js +1 -1
  249. package/dist/core/profile/profile-describe.js +1 -1
  250. package/dist/core/profile/profile-lint.js +1 -1
  251. package/dist/core/profile/profile-plan.js +1 -1
  252. package/dist/core/profile/profile-presets.js +25 -1
  253. package/dist/core/reproducibility/context.js +1 -1
  254. package/dist/core/schema/fields-file.js +2 -2
  255. package/dist/core/schema/item-types-file.js +2 -2
  256. package/dist/core/schema/runtime-field-filters.js +1 -1
  257. package/dist/core/schema/runtime-field-values.js +1 -1
  258. package/dist/core/schema/runtime-schema.js +2 -2
  259. package/dist/core/schema/status-defs-file.js +2 -2
  260. package/dist/core/schema/status-token.js +1 -1
  261. package/dist/core/schema/type-inference.js +1 -1
  262. package/dist/core/schema/type-presets.js +1 -1
  263. package/dist/core/schema/type-workflows.js +1 -1
  264. package/dist/core/search/background-refresh.js +2 -2
  265. package/dist/core/search/bm25.js +1 -1
  266. package/dist/core/search/cache.js +2 -2
  267. package/dist/core/search/corpus.js +1 -1
  268. package/dist/core/search/embedding-batches.js +1 -1
  269. package/dist/core/search/eval-thresholds.js +1 -1
  270. package/dist/core/search/eval.js +1 -1
  271. package/dist/core/search/http-client.js +1 -1
  272. package/dist/core/search/providers.js +1 -1
  273. package/dist/core/search/relevance.js +1 -1
  274. package/dist/core/search/semantic-defaults.js +1 -1
  275. package/dist/core/search/staleness.js +1 -1
  276. package/dist/core/search/vector-stores.js +2 -2
  277. package/dist/core/search/vectorization-metadata.js +1 -1
  278. package/dist/core/sentry/helpers.js +1 -1
  279. package/dist/core/sentry/instrument.js +1 -1
  280. package/dist/core/session/session-state.js +1 -1
  281. package/dist/core/shared/agent-session-context.js +1 -1
  282. package/dist/core/shared/author.js +5 -1
  283. package/dist/core/shared/command-line.js +1 -1
  284. package/dist/core/shared/command-types.js +1 -1
  285. package/dist/core/shared/conflict-markers.js +1 -1
  286. package/dist/core/shared/constants.js +1 -1
  287. package/dist/core/shared/errors.js +1 -1
  288. package/dist/core/shared/html-entity-decode.js +1 -1
  289. package/dist/core/shared/index.js +1 -1
  290. package/dist/core/shared/item-metadata-contract.js +1 -1
  291. package/dist/core/shared/lazy-module.js +1 -1
  292. package/dist/core/shared/levenshtein.js +1 -1
  293. package/dist/core/shared/memo.js +1 -1
  294. package/dist/core/shared/numeric-parsers.js +1 -1
  295. package/dist/core/shared/option-alias-visibility.js +1 -1
  296. package/dist/core/shared/primitives.js +1 -1
  297. package/dist/core/shared/secret-rules.js +1 -1
  298. package/dist/core/shared/serial-queue.js +1 -1
  299. package/dist/core/shared/serialization.js +1 -1
  300. package/dist/core/shared/split-comma-list.js +1 -1
  301. package/dist/core/shared/text-normalization.js +1 -1
  302. package/dist/core/shared/time.js +2 -1
  303. package/dist/core/store/index.js +1 -1
  304. package/dist/core/store/item-format-migration.js +1 -1
  305. package/dist/core/store/item-metadata-cache.js +1 -1
  306. package/dist/core/store/item-metadata-query-index.js +7 -7
  307. package/dist/core/store/item-metadata-read-work.js +1 -1
  308. package/dist/core/store/item-store.js +1 -1
  309. package/dist/core/store/paths.js +1 -1
  310. package/dist/core/store/settings-concurrency.js +1 -1
  311. package/dist/core/store/settings-read-cache.js +1 -1
  312. package/dist/core/store/settings-validator.js +1 -1
  313. package/dist/core/store/settings.d.ts +11 -2
  314. package/dist/core/store/settings.js +3 -3
  315. package/dist/core/store/tracker-preflight.js +1 -1
  316. package/dist/core/telemetry/consent.js +2 -2
  317. package/dist/core/telemetry/observability.js +1 -1
  318. package/dist/core/telemetry/policy.js +1 -1
  319. package/dist/core/telemetry/read-sampling.js +2 -2
  320. package/dist/core/telemetry/runtime.js +9 -5
  321. package/dist/core/test/background-runs.js +3 -3
  322. package/dist/core/test/item-test-run-tracking.js +1 -1
  323. package/dist/core/test/run-selectors.js +1 -1
  324. package/dist/core/validate/estimate-defaults.js +1 -1
  325. package/dist/core/validate/fix-planning.js +1 -1
  326. package/dist/core/validate/linked-artifact-reference.js +1 -1
  327. package/dist/core/validate/missing-by-type.js +1 -1
  328. package/dist/core/validate/missing-link-owners.js +1 -1
  329. package/dist/core/validate/stale-file-classification.js +1 -1
  330. package/dist/mcp/http-server.js +6 -4
  331. package/dist/mcp/legacy-adapter.js +1 -1
  332. package/dist/mcp/runtime-capabilities.js +1 -1
  333. package/dist/mcp/server.js +4 -4
  334. package/dist/mcp/tool-definitions.js +1 -1
  335. package/dist/sdk/actionability.js +1 -1
  336. package/dist/sdk/agent/closed-domain-contracts.js +1 -1
  337. package/dist/sdk/agent/command-recovery.js +1 -1
  338. package/dist/sdk/agent/command-suggestions.js +1 -1
  339. package/dist/sdk/agent/create-option-policy.js +1 -1
  340. package/dist/sdk/agent/identity-config.js +1 -1
  341. package/dist/sdk/agent/item-addressing.js +1 -1
  342. package/dist/sdk/agent/refusal-closure-census.js +2 -1
  343. package/dist/sdk/agent/refusal-closure.js +1 -1
  344. package/dist/sdk/agent/refusal-corpus-contracts.js +1 -1
  345. package/dist/sdk/agent/refusal-reachability.js +3 -1
  346. package/dist/sdk/agent/subcommand-recovery.js +1 -1
  347. package/dist/sdk/agent/task-transcript-contracts.js +1 -1
  348. package/dist/sdk/agent/tracker-preflight-contracts.js +1 -1
  349. package/dist/sdk/agent-capability-contracts.js +3 -1
  350. package/dist/sdk/agent-session-context.js +1 -1
  351. package/dist/sdk/annotations.js +1 -1
  352. package/dist/sdk/author-attribution.js +1 -1
  353. package/dist/sdk/authoring.js +1 -1
  354. package/dist/sdk/cli-bootstrap.js +1 -1
  355. package/dist/sdk/cli-contracts/agent-output-contracts.js +5 -3
  356. package/dist/sdk/cli-contracts/bootstrap-command-scanner.js +1 -1
  357. package/dist/sdk/cli-contracts/command-aliases.js +1 -1
  358. package/dist/sdk/cli-contracts/command-exit-contracts.js +1 -1
  359. package/dist/sdk/cli-contracts/commander-mutation-options.js +1 -1
  360. package/dist/sdk/cli-contracts/commander-types.js +1 -1
  361. package/dist/sdk/cli-contracts/completeness.js +1 -1
  362. package/dist/sdk/cli-contracts/enum-contracts.js +1 -1
  363. package/dist/sdk/cli-contracts/flag-contracts.js +1 -1
  364. package/dist/sdk/cli-contracts/flag-lexicon-contracts.js +2 -1
  365. package/dist/sdk/cli-contracts/grammar-contracts.js +1 -1
  366. package/dist/sdk/cli-contracts/registration-helpers.js +7 -7
  367. package/dist/sdk/cli-contracts/runtime-contracts.js +1 -1
  368. package/dist/sdk/cli-contracts/schemas/assurance-definition.js +1 -1
  369. package/dist/sdk/cli-contracts/string-lists.js +1 -1
  370. package/dist/sdk/cli-contracts/tool-option-contracts.js +1 -1
  371. package/dist/sdk/cli-contracts/tool-parameter-tables.js +1 -1
  372. package/dist/sdk/cli-contracts/tool-schema.js +1 -1
  373. package/dist/sdk/cli-contracts/typed-action-inputs.js +1 -1
  374. package/dist/sdk/cli-contracts.js +1 -1
  375. package/dist/sdk/cli-program.js +1 -1
  376. package/dist/sdk/command-line.js +1 -1
  377. package/dist/sdk/comments.js +1 -1
  378. package/dist/sdk/compile-cache.js +1 -1
  379. package/dist/sdk/completion/bash.js +2 -1
  380. package/dist/sdk/completion/fish.js +13 -7
  381. package/dist/sdk/completion/shared.js +1 -1
  382. package/dist/sdk/completion/zsh.js +14 -8
  383. package/dist/sdk/completion.js +1 -1
  384. package/dist/sdk/compose.js +1 -1
  385. package/dist/sdk/config.js +1 -1
  386. package/dist/sdk/context/recency.js +1 -1
  387. package/dist/sdk/context/semantic-session-attribution.js +1 -1
  388. package/dist/sdk/context/usage-egress.js +1 -1
  389. package/dist/sdk/context/usage-ledger.js +6 -3
  390. package/dist/sdk/context-intent-contracts.js +1 -1
  391. package/dist/sdk/context-intent-runtime.js +1 -1
  392. package/dist/sdk/context-packing.js +1 -1
  393. package/dist/sdk/context-relevance.js +1 -1
  394. package/dist/sdk/context-signal-store.js +2 -2
  395. package/dist/sdk/context-usage.js +1 -1
  396. package/dist/sdk/contracts.js +1 -1
  397. package/dist/sdk/core-governance.js +1 -1
  398. package/dist/sdk/core.js +1 -1
  399. package/dist/sdk/corpus-shape.js +1 -1
  400. package/dist/sdk/define.js +1 -1
  401. package/dist/sdk/dependencies.js +1 -1
  402. package/dist/sdk/dependency-flag-validation.js +1 -1
  403. package/dist/sdk/dependency-provenance.js +1 -1
  404. package/dist/sdk/docs.js +1 -1
  405. package/dist/sdk/duplicates.js +1 -1
  406. package/dist/sdk/environment/agent-environment.js +1 -1
  407. package/dist/sdk/environment/host-environment-errors.js +1 -1
  408. package/dist/sdk/environment/project-runtime-compatibility.js +2 -1
  409. package/dist/sdk/environment/source-context.js +1 -1
  410. package/dist/sdk/environment/tracker-preflight.js +1 -1
  411. package/dist/sdk/error-code-catalog.js +1 -1
  412. package/dist/sdk/error-runtime.js +1 -1
  413. package/dist/sdk/errors.js +1 -1
  414. package/dist/sdk/eval.js +1 -1
  415. package/dist/sdk/extension/author-manifest.js +1 -1
  416. package/dist/sdk/extension/bundled-catalog.js +1 -1
  417. package/dist/sdk/extension/concurrency.js +1 -1
  418. package/dist/sdk/extension/copy-scope.js +1 -1
  419. package/dist/sdk/extension/custom-field-collisions.js +1 -1
  420. package/dist/sdk/extension/describe.js +4 -2
  421. package/dist/sdk/extension/doctor.js +1 -1
  422. package/dist/sdk/extension/install-plan.js +1 -1
  423. package/dist/sdk/extension/install-receipts.js +1 -1
  424. package/dist/sdk/extension/install-runtime.js +3 -3
  425. package/dist/sdk/extension/install-snapshot.js +1 -1
  426. package/dist/sdk/extension/install-sources.js +5 -5
  427. package/dist/sdk/extension/managed-state.js +2 -2
  428. package/dist/sdk/extension/migrations.js +2 -2
  429. package/dist/sdk/extension/output-ownership.js +1 -1
  430. package/dist/sdk/extension/runtime-summary.js +1 -1
  431. package/dist/sdk/extension/scaffold.js +11 -4
  432. package/dist/sdk/extension/shared.js +1 -1
  433. package/dist/sdk/extension/source-resolution.js +1 -1
  434. package/dist/sdk/extension/static-inventory.js +1 -1
  435. package/dist/sdk/extension/update-check.js +1 -1
  436. package/dist/sdk/extension-command-context.js +1 -1
  437. package/dist/sdk/extension-contracts.js +1 -1
  438. package/dist/sdk/extension.js +1 -1
  439. package/dist/sdk/files.js +1 -1
  440. package/dist/sdk/flag-invocation-contracts.js +1 -1
  441. package/dist/sdk/generated/generated-error-code-catalog-part-1.js +1 -1
  442. package/dist/sdk/generated/generated-error-code-catalog-part-2.js +1 -1
  443. package/dist/sdk/generated-error-code-catalog.js +1 -1
  444. package/dist/sdk/governance/assurance-action-contracts.js +1 -1
  445. package/dist/sdk/governance/assurance-action.js +1 -1
  446. package/dist/sdk/governance/assurance-limits.js +1 -1
  447. package/dist/sdk/governance/assurance-mutation-error.js +1 -1
  448. package/dist/sdk/governance/assurance-presets.js +1 -1
  449. package/dist/sdk/governance/assurance-runtime.js +1 -1
  450. package/dist/sdk/governance/assurance.js +4 -4
  451. package/dist/sdk/governance/boundary-fixtures.js +1 -1
  452. package/dist/sdk/governance/closure-timestamps.js +1 -1
  453. package/dist/sdk/governance/coverage-assurance.js +1 -1
  454. package/dist/sdk/governance/defect-recurrence-coverage.js +1 -1
  455. package/dist/sdk/governance/defect-recurrence-graph.js +1 -1
  456. package/dist/sdk/governance/defect-recurrence-signals.js +1 -1
  457. package/dist/sdk/governance/defect-recurrence.js +1 -1
  458. package/dist/sdk/governance/extension-host-version.js +1 -1
  459. package/dist/sdk/governance/gc.js +1 -1
  460. package/dist/sdk/governance/health-merge-evidence.js +1 -1
  461. package/dist/sdk/governance/health.js +2 -1
  462. package/dist/sdk/governance/hierarchy-validation.js +1 -1
  463. package/dist/sdk/governance/linked-file-report.js +1 -1
  464. package/dist/sdk/governance/merge-receipt-history.js +1 -1
  465. package/dist/sdk/governance/provenance-health.js +4 -1
  466. package/dist/sdk/governance/reindex.js +5 -4
  467. package/dist/sdk/governance/stale-work.js +1 -1
  468. package/dist/sdk/governance/status-role-diagnostics.js +1 -1
  469. package/dist/sdk/governance/storage-integrity.js +1 -1
  470. package/dist/sdk/governance/tracked-runtime-cache.js +1 -1
  471. package/dist/sdk/governance/upgrade.js +2 -2
  472. package/dist/sdk/governance/validate-history-drift.js +1 -1
  473. package/dist/sdk/governance/validate-item-reader.js +1 -1
  474. package/dist/sdk/governance/validate-normalization.js +1 -1
  475. package/dist/sdk/governance/validate.js +1 -1
  476. package/dist/sdk/governance/workflow-completeness.js +1 -1
  477. package/dist/sdk/governance/workflow-policy.js +3 -3
  478. package/dist/sdk/governance/workspace-position.js +2 -1
  479. package/dist/sdk/governance.js +1 -1
  480. package/dist/sdk/graph/adapter.js +1 -1
  481. package/dist/sdk/graph/analytics.js +1 -1
  482. package/dist/sdk/graph/assembly.js +1 -1
  483. package/dist/sdk/graph/cache.js +1 -1
  484. package/dist/sdk/graph/centrality.js +1 -1
  485. package/dist/sdk/graph/conformance.js +1 -1
  486. package/dist/sdk/graph/deadline-scheduling.js +1 -1
  487. package/dist/sdk/graph/durable-cache.js +1 -1
  488. package/dist/sdk/graph/governance-contracts.js +1 -1
  489. package/dist/sdk/graph/governance.js +1 -1
  490. package/dist/sdk/graph/hierarchy-integrity.js +1 -1
  491. package/dist/sdk/graph/index.js +1 -1
  492. package/dist/sdk/graph/lifecycle-coverage.js +1 -1
  493. package/dist/sdk/graph/mutation-advisory.js +1 -1
  494. package/dist/sdk/graph/query-contracts.js +1 -1
  495. package/dist/sdk/graph/remediation.js +1 -1
  496. package/dist/sdk/graph/run.js +1 -1
  497. package/dist/sdk/graph/scheduling.js +1 -1
  498. package/dist/sdk/graph/traversal.js +1 -1
  499. package/dist/sdk/graph/workspace-relationship-kind-registry.js +1 -1
  500. package/dist/sdk/graph.js +1 -1
  501. package/dist/sdk/guide-topics.js +1 -1
  502. package/dist/sdk/guide.js +8 -1
  503. package/dist/sdk/history/attestation-command.js +1 -1
  504. package/dist/sdk/history/attestation-contract.js +1 -1
  505. package/dist/sdk/history/attestation-scan.js +1 -1
  506. package/dist/sdk/history/attestation.js +1 -1
  507. package/dist/sdk/history/maintenance.js +1 -1
  508. package/dist/sdk/history/salvage.js +3 -2
  509. package/dist/sdk/history/subject.js +1 -1
  510. package/dist/sdk/history-analytics.js +1 -1
  511. package/dist/sdk/history-compact.js +1 -1
  512. package/dist/sdk/history-mcp.js +1 -1
  513. package/dist/sdk/history-provenance.js +1 -1
  514. package/dist/sdk/history-read.js +1 -1
  515. package/dist/sdk/history-redact.js +1 -1
  516. package/dist/sdk/history-repair.js +1 -1
  517. package/dist/sdk/improvement-ledger-validation.js +1 -1
  518. package/dist/sdk/improvement-ledger.js +2 -2
  519. package/dist/sdk/index.js +1 -1
  520. package/dist/sdk/init-agent-guidance.js +16 -2
  521. package/dist/sdk/init.js +16 -2
  522. package/dist/sdk/invocation-author.js +1 -1
  523. package/dist/sdk/item-children.js +1 -1
  524. package/dist/sdk/item-metadata-index.js +1 -1
  525. package/dist/sdk/item-schedule.js +1 -1
  526. package/dist/sdk/item-transaction.js +1 -1
  527. package/dist/sdk/learnings.js +1 -1
  528. package/dist/sdk/lifecycle/append.js +4 -2
  529. package/dist/sdk/lifecycle/claim.js +1 -1
  530. package/dist/sdk/lifecycle/close-many.js +1 -1
  531. package/dist/sdk/lifecycle/close.js +1 -1
  532. package/dist/sdk/lifecycle/copy.js +1 -1
  533. package/dist/sdk/lifecycle/create.js +1 -1
  534. package/dist/sdk/lifecycle/delete.js +1 -1
  535. package/dist/sdk/lifecycle/event-validation-messages.js +1 -1
  536. package/dist/sdk/lifecycle/focus.js +1 -1
  537. package/dist/sdk/lifecycle/hierarchy-mutation-lock.js +1 -1
  538. package/dist/sdk/lifecycle/legacy-none-tokens.js +1 -1
  539. package/dist/sdk/lifecycle/lifecycle-transitions.js +1 -1
  540. package/dist/sdk/lifecycle/mcp-actions.js +1 -1
  541. package/dist/sdk/lifecycle/metadata-normalizers.js +1 -1
  542. package/dist/sdk/lifecycle/mutation-command-options.js +1 -1
  543. package/dist/sdk/lifecycle/plan-mutation-receipt.js +1 -1
  544. package/dist/sdk/lifecycle/plan.js +1 -1
  545. package/dist/sdk/lifecycle/recurrence-parsers.js +1 -1
  546. package/dist/sdk/lifecycle/reopen.js +1 -1
  547. package/dist/sdk/lifecycle/repeatable-metadata-parsers.js +2 -1
  548. package/dist/sdk/lifecycle/restore.js +1 -1
  549. package/dist/sdk/lifecycle/shared-unset-fields.js +1 -1
  550. package/dist/sdk/lifecycle/task-composition.js +1 -1
  551. package/dist/sdk/lifecycle/update-many.js +1 -1
  552. package/dist/sdk/lifecycle/update.js +2 -1
  553. package/dist/sdk/lifecycle-completion.js +1 -1
  554. package/dist/sdk/lifecycle-policy.js +1 -1
  555. package/dist/sdk/linked-artifacts.js +2 -1
  556. package/dist/sdk/mcp/apps.js +1 -1
  557. package/dist/sdk/mcp/authorization.js +1 -1
  558. package/dist/sdk/mcp/discovery.js +1 -1
  559. package/dist/sdk/mcp/interactions.js +1 -1
  560. package/dist/sdk/mcp/protocol.js +1 -1
  561. package/dist/sdk/mcp/skills.js +3 -1
  562. package/dist/sdk/mcp/subscriptions.js +1 -1
  563. package/dist/sdk/mcp/tasks.js +2 -2
  564. package/dist/sdk/mcp/transport.js +1 -1
  565. package/dist/sdk/merge/abandoned-receipts.js +1 -1
  566. package/dist/sdk/merge/driver.js +1 -1
  567. package/dist/sdk/merge/index.js +1 -1
  568. package/dist/sdk/merge/install.js +4 -2
  569. package/dist/sdk/merge/receipt-file-boundary.js +1 -1
  570. package/dist/sdk/merge/receipt-operation.js +1 -1
  571. package/dist/sdk/merge/receipt-schema.js +1 -1
  572. package/dist/sdk/merge/receipts.js +4 -4
  573. package/dist/sdk/merge/reconcile.js +1 -1
  574. package/dist/sdk/merge/three-way.js +3 -2
  575. package/dist/sdk/merge/worktree-config.js +1 -1
  576. package/dist/sdk/merge.js +1 -1
  577. package/dist/sdk/mutation-events.js +1 -1
  578. package/dist/sdk/mutation-guard.js +1 -1
  579. package/dist/sdk/notes.js +1 -1
  580. package/dist/sdk/output-contracts.js +1 -1
  581. package/dist/sdk/output-projection.js +1 -1
  582. package/dist/sdk/output-token-accounting.js +1 -1
  583. package/dist/sdk/output.js +2 -1
  584. package/dist/sdk/ownership-source.js +1 -1
  585. package/dist/sdk/package-import-adapters.js +1 -1
  586. package/dist/sdk/package-migrations.js +1 -1
  587. package/dist/sdk/package-runtime-options.js +1 -1
  588. package/dist/sdk/pagination.js +1 -1
  589. package/dist/sdk/profile.js +5 -1
  590. package/dist/sdk/provenance.js +1 -1
  591. package/dist/sdk/public-surface.json +1 -1
  592. package/dist/sdk/query/activity.js +1 -1
  593. package/dist/sdk/query/aggregate.js +1 -1
  594. package/dist/sdk/query/calendar.js +4 -1
  595. package/dist/sdk/query/complete-list.js +1 -1
  596. package/dist/sdk/query/context.js +2 -1
  597. package/dist/sdk/query/duplicate-candidates.js +1 -1
  598. package/dist/sdk/query/get.d.ts +14 -2
  599. package/dist/sdk/query/get.js +1 -1
  600. package/dist/sdk/query/history.js +1 -1
  601. package/dist/sdk/query/item-filter-options.js +1 -1
  602. package/dist/sdk/query/light-metadata.js +1 -1
  603. package/dist/sdk/query/list-filter-shared.js +1 -1
  604. package/dist/sdk/query/list.js +1 -1
  605. package/dist/sdk/query/multi-value-filters.js +1 -1
  606. package/dist/sdk/query/next-ready-budget.js +1 -1
  607. package/dist/sdk/query/next.js +2 -1
  608. package/dist/sdk/query/parsers.js +1 -1
  609. package/dist/sdk/query/projection-contracts.js +1 -1
  610. package/dist/sdk/query/search/corpus.js +2 -1
  611. package/dist/sdk/query/search/filters.js +1 -1
  612. package/dist/sdk/query/search/input.js +1 -1
  613. package/dist/sdk/query/search/lexical.js +1 -1
  614. package/dist/sdk/query/search/response.js +1 -1
  615. package/dist/sdk/query/search/semantic.js +3 -2
  616. package/dist/sdk/query/search/types.js +1 -1
  617. package/dist/sdk/query/search-contracts.js +1 -1
  618. package/dist/sdk/query/search-pagination.d.ts +1 -1
  619. package/dist/sdk/query/search-pagination.js +1 -1
  620. package/dist/sdk/query/search-rendering.js +1 -1
  621. package/dist/sdk/query/search.js +1 -1
  622. package/dist/sdk/query/workspace-contracts.js +1 -1
  623. package/dist/sdk/query.js +1 -1
  624. package/dist/sdk/read-output/continuation.js +1 -1
  625. package/dist/sdk/read-output/options.js +1 -1
  626. package/dist/sdk/read-output/provenance.js +1 -1
  627. package/dist/sdk/read-output-budget.js +1 -1
  628. package/dist/sdk/read-output-contracts.js +1 -1
  629. package/dist/sdk/read-output-rows.js +1 -1
  630. package/dist/sdk/read-output-session.js +1 -1
  631. package/dist/sdk/relationship-analytics.js +1 -1
  632. package/dist/sdk/relationship-context.js +1 -1
  633. package/dist/sdk/relationship-history.js +7 -4
  634. package/dist/sdk/relationship-kinds/contract.js +1 -1
  635. package/dist/sdk/relationship-migration.js +1 -1
  636. package/dist/sdk/relationships.js +1 -1
  637. package/dist/sdk/reproducibility/process.js +1 -1
  638. package/dist/sdk/runtime/actions.js +1 -1
  639. package/dist/sdk/runtime/context.js +1 -1
  640. package/dist/sdk/runtime/schema-preview.js +1 -1
  641. package/dist/sdk/runtime/schema.js +1 -1
  642. package/dist/sdk/runtime-action-aliases.js +1 -1
  643. package/dist/sdk/runtime-extended-actions.js +1 -1
  644. package/dist/sdk/runtime-input.js +1 -1
  645. package/dist/sdk/runtime-primitives.js +1 -1
  646. package/dist/sdk/runtime-public-contracts.js +1 -1
  647. package/dist/sdk/runtime-stats-options.js +1 -1
  648. package/dist/sdk/runtime.js +1 -1
  649. package/dist/sdk/scheduling-shortcuts.js +1 -1
  650. package/dist/sdk/schema-migration.js +4 -3
  651. package/dist/sdk/schema.js +7 -1
  652. package/dist/sdk/search-refresh-worker.js +1 -1
  653. package/dist/sdk/similarity-scoring.js +1 -1
  654. package/dist/sdk/similarity.js +1 -1
  655. package/dist/sdk/start-task-status.js +1 -1
  656. package/dist/sdk/stats.js +1 -1
  657. package/dist/sdk/structured-mutations.js +1 -1
  658. package/dist/sdk/telemetry-flush.js +1 -1
  659. package/dist/sdk/telemetry.js +4 -3
  660. package/dist/sdk/templates.js +26 -2
  661. package/dist/sdk/test/batch.js +2 -2
  662. package/dist/sdk/test/entry.js +1 -1
  663. package/dist/sdk/test/execution.js +6 -5
  664. package/dist/sdk/test/json-path.js +1 -1
  665. package/dist/sdk/test/linked-command-detection.js +1 -1
  666. package/dist/sdk/test/measurements.js +1 -1
  667. package/dist/sdk/test/parsers.js +1 -1
  668. package/dist/sdk/test/runs.js +1 -1
  669. package/dist/sdk/test/trust.js +2 -2
  670. package/dist/sdk/test/workspace-snapshot.js +1 -1
  671. package/dist/sdk/testing.js +7 -4
  672. package/dist/sdk/traceability/runtime-files-lookup.js +1 -1
  673. package/dist/sdk/traceability/source-traceability.js +2 -1
  674. package/dist/sdk/tracker-root-discovery.js +1 -1
  675. package/dist/sdk/workspace-contracts-cache.js +1 -1
  676. package/dist/sdk/workspace-contracts.js +1 -1
  677. package/dist/sdk/workspace-memory.js +2 -2
  678. package/dist/sdk/workspace-recipe.js +1 -1
  679. package/dist/sdk/workspace-snapshot.js +5 -4
  680. package/dist/sdk/workspace-transaction-gc.js +1 -1
  681. package/dist/sdk/workspace-transaction.js +2 -2
  682. package/dist/sdk/workspace.js +3 -2
  683. package/dist/types/index.js +1 -1
  684. package/dist/types.js +1 -1
  685. package/docs/AGENT_EVIDENCE_CONSISTENCY.md +88 -0
  686. package/docs/DIAGNOSTIC_OUTPUT_CONTRACTS.md +25 -0
  687. package/docs/GET_READ_EVIDENCE.md +68 -0
  688. package/docs/OUTPUT_PROJECTION_CONTRACTS.md +23 -0
  689. package/docs/README.md +2 -0
  690. package/docs/SDK_AUDITED_MUTATIONS.md +35 -0
  691. package/docs/TESTING.md +8 -0
  692. package/docs/ecosystem-review-2026-09-28.json +2864 -3157
  693. package/marketplace.json +2 -2
  694. package/package.json +1 -1
  695. package/packages/pm-beads/package.json +1 -1
  696. package/packages/pm-calendar/package.json +1 -1
  697. package/packages/pm-command-kit/package.json +1 -1
  698. package/packages/pm-digital-twin/package.json +1 -1
  699. package/packages/pm-governance-audit/package.json +1 -1
  700. package/packages/pm-guide-shell/package.json +1 -1
  701. package/packages/pm-kanban/package.json +1 -1
  702. package/packages/pm-lifecycle-hooks/package.json +1 -1
  703. package/packages/pm-linked-test-adapters/package.json +1 -1
  704. package/packages/pm-search-advanced/package.json +1 -1
  705. package/packages/pm-templates/package.json +1 -1
  706. package/packages/pm-todos/package.json +1 -1
  707. package/packages/pm-vcs/extensions/vcs/index.ts +4 -2
  708. package/packages/pm-vcs/package.json +1 -1
  709. package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
  710. package/plugins/pm-claude/package.json +2 -2
  711. package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
  712. package/plugins/pm-codex/package.json +2 -2
  713. package/plugins/pm-codex/plugin.json +1 -1
  714. package/scripts/finalize-build.mjs +3 -2
  715. package/dist/cli-bundle/chunks/chunk-3AF2R3Y6.js +0 -6
  716. package/dist/cli-bundle/chunks/chunk-6ST3SCQ6.js +0 -2
  717. package/dist/cli-bundle/chunks/chunk-6Z4IV2MC.js +0 -8
  718. package/dist/cli-bundle/chunks/chunk-DEZPZOQ7.js +0 -2
  719. package/dist/cli-bundle/chunks/chunk-FW5LJXQY.js +0 -31
  720. package/dist/cli-bundle/chunks/chunk-H2DZW6I6.js +0 -3
  721. package/dist/cli-bundle/chunks/chunk-H7CXQBGQ.js +0 -2
  722. package/dist/cli-bundle/chunks/chunk-KP7NBQK3.js +0 -80
  723. package/dist/cli-bundle/chunks/chunk-MKXBCBAN.js +0 -20
  724. package/dist/cli-bundle/chunks/chunk-QPKQKSQU.js +0 -238
  725. package/dist/cli-bundle/chunks/chunk-SGFQQXFD.js +0 -2
  726. package/dist/cli-bundle/chunks/chunk-YCBGZF3T.js +0 -2
  727. package/dist/cli-bundle/chunks/chunk-YDWKGUQU.js +0 -3
  728. package/dist/cli-bundle/chunks/register-mutation-5PT3NW3A.js +0 -20
  729. package/dist/cli-bundle/chunks/register-operations-QDDQOAAV.js +0 -2
  730. package/dist/cli-bundle/chunks/register-setup-BBX67YMA.js +0 -2
  731. package/dist/cli-bundle/focused-chunks/chunk-4FFPGNCJ.js +0 -6
  732. package/dist/cli-bundle/focused-chunks/chunk-73DA7ISY.js +0 -75
  733. package/dist/cli-bundle/focused-chunks/chunk-E754JDLY.js +0 -2
  734. package/dist/cli-bundle/focused-chunks/chunk-FKK2HI3S.js +0 -2
  735. package/dist/cli-bundle/focused-chunks/chunk-GMYUNHST.js +0 -3
  736. package/dist/cli-bundle/focused-chunks/chunk-HIA2ZF64.js +0 -12
  737. package/dist/cli-bundle/focused-chunks/chunk-UTRSM3ZK.js +0 -8
  738. package/dist/cli-bundle/focused-chunks/chunk-VVWYI2X7.js +0 -2
  739. package/dist/cli-bundle/focused-chunks/chunk-WAJNX4RN.js +0 -20
  740. package/dist/cli-bundle/focused-chunks/chunk-WCY6HRZO.js +0 -30
  741. package/dist/cli-bundle/focused-chunks/chunk-YC32ZSLS.js +0 -165
  742. package/dist/cli-bundle/focused-chunks/chunk-ZIXFMIUL.js +0 -3
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="874a21db-ed3b-5b4f-a913-bf87103172e7")}catch(e2){}})();import{collectOrderingStorageContradictions,normalizeDependencyGraphTarget,resolveWorkspaceRelationshipKindRegistry}from"./assembly.js";import{collectOrderingCycles,formatOrderingStorageContradiction}from"./governance.js";function cycleKey(component){return[...component].sort().join("\0")}function addOrderingEdge(digraph,predecessor,successor){const forward=digraph.successors.get(predecessor);if(forward)forward.push(successor);else digraph.successors.set(predecessor,[successor]);const backward=digraph.predecessors.get(successor);if(backward)backward.push(predecessor);else digraph.predecessors.set(successor,[predecessor])}function orientOrderingEdge(digraph,registry,source,target,kind){const definition=registry.resolve(kind);if(definition?.ordering!==true)return;const normalized=normalizeDependencyGraphTarget(target);const canonicalTarget=normalized===void 0?void 0:digraph.canonicalIds.get(normalized.toLowerCase());if(canonicalTarget===void 0)return;const sourceFirst=(definition.precedence??"source_before_target")==="source_before_target";addOrderingEdge(digraph,sourceFirst?source:canonicalTarget,sourceFirst?canonicalTarget:source)}function buildOrderingDigraph(items,registry){const digraph={successors:new Map,predecessors:new Map,canonicalIds:new Map};const safeItems=items.filter(item=>typeof item?.id==="string"&&item.id.trim().length>0);for(const item of safeItems){const id=item.id.trim();digraph.canonicalIds.set(id.toLowerCase(),id)}for(const item of safeItems){const id=item.id.trim();orientOrderingEdge(digraph,registry,id,item.blocked_by,"blocked_by");for(const dependency of item.dependencies??[]){if(typeof dependency!=="object"||dependency===null)continue;orientOrderingEdge(digraph,registry,id,dependency.id,typeof dependency.kind==="string"?dependency.kind:"related")}}for(const adjacency of[digraph.successors,digraph.predecessors])for(const neighbors of adjacency.values())neighbors.sort();return digraph}function collectWeakComponent(digraph,start){const members=new Set([start]);const queue=[start];while(queue.length>0){const node=queue.pop();for(const adjacency of[digraph.successors,digraph.predecessors]){for(const neighbor of adjacency.get(node)??[]){if(members.has(neighbor))continue;members.add(neighbor);queue.push(neighbor)}}}return members}function induceSuccessors(digraph,members){const induced=new Map;for(const member of members){const neighbors=(digraph.successors.get(member)??[]).filter(node=>members.has(node));if(neighbors.length>0)induced.set(member,neighbors)}return induced}function collectScopedCycles(items,registry,changedItemId){const digraph=buildOrderingDigraph(items,registry);const canonical=digraph.canonicalIds.get(changedItemId.trim().toLowerCase());if(canonical===void 0)return{cycles:[],successors:new Map,canonical:changedItemId};const successors=induceSuccessors(digraph,collectWeakComponent(digraph,canonical));return{cycles:collectOrderingCycles(successors).filter(component=>component.includes(canonical)),successors,canonical}}function findCyclePath(adjacency,component,changedItemId){const members=new Set(component);const start=members.has(changedItemId)?changedItemId:component[0];if(adjacency.get(start)?.includes(start))return[start,start];for(const first of adjacency.get(start)??[]){if(!members.has(first))continue;const path=findPathBackToStart(adjacency,members,start,first);if(path)return path}return[...component,component[0]]}function findPathBackToStart(adjacency,members,start,first){const queue=[[first]];const visited=new Set([start,first]);while(queue.length>0){const path=queue.shift();const tail=path.at(-1);for(const next of adjacency.get(tail)??[]){if(next===start)return[start,...path,start];if(!members.has(next)||visited.has(next))continue;visited.add(next);queue.push([...path,next])}}return void 0}function collectNewOrderingCycleWarnings(beforeItems,afterItems,changedItemId){const registry=resolveWorkspaceRelationshipKindRegistry();const before=collectScopedCycles(beforeItems,registry,changedItemId);const after=collectScopedCycles(afterItems,registry,changedItemId);const beforeCycles=new Set(before.cycles.map(cycleKey));const beforeContradictions=new Set(collectOrderingStorageContradictions(beforeItems,void 0,registry).map(row=>`${row.holder_id.toLowerCase()}\0${row.target_id.toLowerCase()}\0${row.dependency_kind}`));const contradictionWarnings=collectOrderingStorageContradictions(afterItems,void 0,registry).filter(row=>row.holder_id.toLowerCase()===changedItemId.trim().toLowerCase()&&!beforeContradictions.has(`${row.holder_id.toLowerCase()}\0${row.target_id.toLowerCase()}\0${row.dependency_kind}`)).map(row=>`ordering_storage_contradiction_created:${formatOrderingStorageContradiction(row)}:remove_contradicting_dependency_row:run_pm_graph_audit`);return[...contradictionWarnings,...after.cycles.filter(component=>!beforeCycles.has(cycleKey(component))).map(component=>`ordering_cycle_created:${findCyclePath(after.successors,component,after.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}const mutationAdvisoryTestOnly={buildOrderingDigraph,collectWeakComponent,induceSuccessors,findCyclePath,findPathBackToStart};export{collectNewOrderingCycleWarnings,mutationAdvisoryTestOnly};
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]="73852fdf-f072-51ab-9449-d7922712eeb4")}catch{}})();import{collectOrderingStorageContradictions,normalizeDependencyGraphTarget,resolveWorkspaceRelationshipKindRegistry}from"./assembly.js";import{collectOrderingCycles,formatOrderingStorageContradiction}from"./governance.js";function cycleKey(component){return[...component].sort().join("\0")}function addOrderingEdge(digraph,predecessor,successor){const forward=digraph.successors.get(predecessor);forward?forward.push(successor):digraph.successors.set(predecessor,[successor]);const backward=digraph.predecessors.get(successor);backward?backward.push(predecessor):digraph.predecessors.set(successor,[predecessor])}function orientOrderingEdge(digraph,registry,source,target,kind){const definition=registry.resolve(kind);if(definition?.ordering!==!0)return;const normalized=normalizeDependencyGraphTarget(target),canonicalTarget=normalized===void 0?void 0:digraph.canonicalIds.get(normalized.toLowerCase());if(canonicalTarget===void 0)return;const sourceFirst=(definition.precedence??"source_before_target")==="source_before_target";addOrderingEdge(digraph,sourceFirst?source:canonicalTarget,sourceFirst?canonicalTarget:source)}function buildOrderingDigraph(items,registry){const digraph={successors:new Map,predecessors:new Map,canonicalIds:new Map},safeItems=items.filter(item=>typeof item?.id=="string"&&item.id.trim().length>0);for(const item of safeItems){const id=item.id.trim();digraph.canonicalIds.set(id.toLowerCase(),id)}for(const item of safeItems){const id=item.id.trim();orientOrderingEdge(digraph,registry,id,item.blocked_by,"blocked_by");for(const dependency of item.dependencies??[])typeof dependency!="object"||dependency===null||orientOrderingEdge(digraph,registry,id,dependency.id,typeof dependency.kind=="string"?dependency.kind:"related")}for(const adjacency of[digraph.successors,digraph.predecessors])for(const neighbors of adjacency.values())neighbors.sort();return digraph}function collectWeakComponent(digraph,start){const members=new Set([start]),queue=[start];for(;queue.length>0;){const node=queue.pop();for(const adjacency of[digraph.successors,digraph.predecessors])for(const neighbor of adjacency.get(node)??[])members.has(neighbor)||(members.add(neighbor),queue.push(neighbor))}return members}function induceSuccessors(digraph,members){const induced=new Map;for(const member of members){const neighbors=(digraph.successors.get(member)??[]).filter(node=>members.has(node));neighbors.length>0&&induced.set(member,neighbors)}return induced}function collectScopedCycles(items,registry,changedItemId){const digraph=buildOrderingDigraph(items,registry),canonical=digraph.canonicalIds.get(changedItemId.trim().toLowerCase());if(canonical===void 0)return{cycles:[],successors:new Map,canonical:changedItemId};const successors=induceSuccessors(digraph,collectWeakComponent(digraph,canonical));return{cycles:collectOrderingCycles(successors).filter(component=>component.includes(canonical)),successors,canonical}}function findCyclePath(adjacency,component,changedItemId){const members=new Set(component),start=members.has(changedItemId)?changedItemId:component[0];if(adjacency.get(start)?.includes(start))return[start,start];for(const first of adjacency.get(start)??[]){if(!members.has(first))continue;const path=findPathBackToStart(adjacency,members,start,first);if(path)return path}return[...component,component[0]]}function findPathBackToStart(adjacency,members,start,first){const queue=[[first]],visited=new Set([start,first]);for(;queue.length>0;){const path=queue.shift(),tail=path.at(-1);for(const next of adjacency.get(tail)??[]){if(next===start)return[start,...path,start];!members.has(next)||visited.has(next)||(visited.add(next),queue.push([...path,next]))}}}function collectNewOrderingCycleWarnings(beforeItems,afterItems,changedItemId){const registry=resolveWorkspaceRelationshipKindRegistry(),before=collectScopedCycles(beforeItems,registry,changedItemId),after=collectScopedCycles(afterItems,registry,changedItemId),beforeCycles=new Set(before.cycles.map(cycleKey)),beforeContradictions=new Set(collectOrderingStorageContradictions(beforeItems,void 0,registry).map(row=>`${row.holder_id.toLowerCase()}\0${row.target_id.toLowerCase()}\0${row.dependency_kind}`));return[...collectOrderingStorageContradictions(afterItems,void 0,registry).filter(row=>row.holder_id.toLowerCase()===changedItemId.trim().toLowerCase()&&!beforeContradictions.has(`${row.holder_id.toLowerCase()}\0${row.target_id.toLowerCase()}\0${row.dependency_kind}`)).map(row=>`ordering_storage_contradiction_created:${formatOrderingStorageContradiction(row)}:remove_contradicting_dependency_row:run_pm_graph_audit`),...after.cycles.filter(component=>!beforeCycles.has(cycleKey(component))).map(component=>`ordering_cycle_created:${findCyclePath(after.successors,component,after.canonical).join(" -> ")}:items_will_not_be_ready:run_pm_graph_audit`)]}const mutationAdvisoryTestOnly={buildOrderingDigraph,collectWeakComponent,induceSuccessors,findCyclePath,findPathBackToStart};export{collectNewOrderingCycleWarnings,mutationAdvisoryTestOnly};
2
2
  //# sourceMappingURL=mutation-advisory.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="bfaa3455-3237-5c98-8ef4-b353ce9530fe")}catch(e2){}})();const GRAPH_QUERY_DEFAULTS=Object.freeze({rows:10,paths:5,samples:10,path_depth:8,visited_paths:1e4});export{GRAPH_QUERY_DEFAULTS};
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]="bfaa3455-3237-5c98-8ef4-b353ce9530fe")}catch{}})();const GRAPH_QUERY_DEFAULTS=Object.freeze({rows:10,paths:5,samples:10,path_depth:8,visited_paths:1e4});export{GRAPH_QUERY_DEFAULTS};
2
2
  //# sourceMappingURL=query-contracts.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="236ccc7d-6efd-57b1-8cce-6758d537f779")}catch(e2){}})();import{findRedundantRelationshipEdges}from"./analytics.js";import{auditWorkspaceRelationshipGraph,collectDuplicateRelationshipEdgeGroups,formatDuplicateEdgeGroup}from"./governance.js";const FINDING_STEP_TEMPLATES={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function formatStoredEdge(edge){return`${edge.source} -${edge.kind}-> ${edge.target}`}function stepsFromDuplicateGroup(group){const[keeper,...extras]=group.edges;return extras.map(edge=>({op:"remove",code:"duplicate_edge",subject:formatStoredEdge(edge),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${formatStoredEdge(keeper)}`,`group: ${formatDuplicateEdgeGroup(group)}`],confidence:"high"}))}function stepsFromFinding(finding,duplicateGroups){if(finding.code==="duplicate_edge"){return finding.sample.flatMap(subject=>stepsFromDuplicateGroup(duplicateGroups.get(subject)))}const template=FINDING_STEP_TEMPLATES[finding.code];return finding.sample.map(subject=>({op:template.op,code:finding.code,subject,rationale:template.rationale,evidence:[finding.policy],confidence:template.confidence}))}function planRelationshipRemediation(assembly,options={}){const{redundancyLimit,...auditOptions}=options;const report=auditWorkspaceRelationshipGraph(assembly,auditOptions);const duplicateGroups=new Map(collectDuplicateRelationshipEdgeGroups(assembly).map(group=>[formatDuplicateEdgeGroup(group),group]));const steps=report.findings.flatMap(finding=>stepsFromFinding(finding,duplicateGroups));let truncated=report.findings.some(finding=>finding.sample_truncated);options.signal?.throwIfAborted();const redundancy=findRedundantRelationshipEdges(assembly.graph,{limit:redundancyLimit??options.maxSampleSize??25,...options.signal===void 0?{}:{signal:options.signal}});for(const row of redundancy.value){steps.push({op:"remove",code:"redundant_edge",subject:`${row.edge.source} -> ${row.edge.target} (${row.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${row.witness.join(" -> ")}`],confidence:"medium"})}truncated=truncated||redundancy.meta.truncated;return{steps,report,truncated,cost:{visitedNodes:redundancy.meta.visitedNodes,inspectedEdges:redundancy.meta.inspectedEdges}}}export{planRelationshipRemediation};
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]="253f392d-4e91-57ec-b656-6134583d57e5")}catch{}})();import{findRedundantRelationshipEdges}from"./analytics.js";import{auditWorkspaceRelationshipGraph,collectDuplicateRelationshipEdgeGroups,formatDuplicateEdgeGroup}from"./governance.js";const FINDING_STEP_TEMPLATES={missing_reference_active:{op:"investigate",confidence:"medium",rationale:"Restore or re-create the referenced item, or remove/retype the reference on the active holder; the correct fix depends on why the target is absent."},missing_reference_terminal:{op:"waive",confidence:"high",rationale:"Terminal-holder reference to an absent item is historical debt; waive it or clean it up only in a dedicated changelog-safe closed-item batch."},legacy_no_blocker_sentinel:{op:"remove",confidence:"high",rationale:"The pre-structured-dependency no-active-blocker sentinel is retired and carries no information; blocker state derives from blocked_by edges."},ordering_cycle:{op:"investigate",confidence:"low",rationale:"Every cycle member is unschedulable until one ordering edge is removed or retyped; the planner never chooses which edge to cut."},legacy_ordering_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only ordering cycles have no scheduling effect; repairing them would mutate closed history (changelog drag)."},ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The structured ordering row asserts the opposite precedence from the same-target scalar blocker; remove that exact dependency row or replace both representations with one unambiguous edge."},legacy_ordering_storage_contradiction:{op:"remove",confidence:"high",rationale:"The terminal holder contains a proven contradictory structured ordering row; remove it in a dedicated changelog-safe batch while preserving the scalar blocker as history."},hierarchy_cycle:{op:"investigate",confidence:"low",rationale:"Cut or retype one exact structural relation in the cycle; the planner preserves every evidence row because intent determines the correct parent."},legacy_hierarchy_cycle:{op:"waive",confidence:"high",rationale:"Terminal-only hierarchy cycles are historical debt; waive them unless an explicit closed-history repair is approved."},hierarchy_cardinality_violation:{op:"investigate",confidence:"medium",rationale:"Choose the canonical parent and remove or retype the exact surplus hierarchy rows; the planner cannot infer ownership intent."},legacy_hierarchy_cardinality_violation:{op:"waive",confidence:"high",rationale:"Multiple parents confined to terminal items are historical debt; waive them unless a dedicated history repair is approved."},hierarchy_direction_violation:{op:"investigate",confidence:"medium",rationale:"Align the scalar parent and dependency-backed hierarchy rows to the intended canonical parent."},legacy_hierarchy_direction_violation:{op:"waive",confidence:"high",rationale:"Divergent hierarchy storage confined to terminal items is historical debt; waive it unless a dedicated history repair is approved."},duplicate_edge:{op:"remove",confidence:"high",rationale:"Parallel same-family spellings state one relationship twice; remove all but one stored spelling, keeping the holder's canonical direction."},legacy_duplicate_edge:{op:"waive",confidence:"high",rationale:"Duplicated spellings between terminal items are historical noise; waive or batch changelog-safe cleanup."},duplicate_dependency_row:{op:"remove",confidence:"high",rationale:"The identical dependency row is stored more than once on the holder; drop the repeats so the row exists exactly once \u2014 graph semantics are unchanged."},legacy_duplicate_dependency_row:{op:"waive",confidence:"high",rationale:"Repeated identical rows on terminal holders are storage noise; waive or clean up only in a changelog-safe closed-item batch."},stale_lifecycle_block:{op:"investigate",confidence:"medium",rationale:`Add a local ordering edge, declare an external blocker with --dep "id=<external-ref>,kind=blocked_by,source_kind=external", or move the item back to an active status; only the holder's owner knows which is true.`},isolated_active_node:{op:"investigate",confidence:"medium",rationale:"Link the item to its parent, prerequisite, or origin \u2014 or register it as an explicitly exempt isolate; the audit never fabricates an edge."},sparse_active_node:{op:"investigate",confidence:"low",rationale:"Investigate for an honest second edge (story-to-task, defect family, cross-epic complement); sparse is not automatically defective."}};function formatStoredEdge(edge){return`${edge.source} -${edge.kind}-> ${edge.target}`}function stepsFromDuplicateGroup(group){const[keeper,...extras]=group.edges;return extras.map(edge=>({op:"remove",code:"duplicate_edge",subject:formatStoredEdge(edge),rationale:"This stored spelling restates the kept canonical edge of the same semantic family; removing it leaves the relationship stated exactly once.",evidence:[`keep: ${formatStoredEdge(keeper)}`,`group: ${formatDuplicateEdgeGroup(group)}`],confidence:"high"}))}function stepsFromFinding(finding,duplicateGroups){if(finding.code==="duplicate_edge")return finding.sample.flatMap(subject=>stepsFromDuplicateGroup(duplicateGroups.get(subject)));const template=FINDING_STEP_TEMPLATES[finding.code];return finding.sample.map(subject=>({op:template.op,code:finding.code,subject,rationale:template.rationale,evidence:[finding.policy],confidence:template.confidence}))}function planRelationshipRemediation(assembly,options={}){const{redundancyLimit,...auditOptions}=options,report=auditWorkspaceRelationshipGraph(assembly,auditOptions),duplicateGroups=new Map(collectDuplicateRelationshipEdgeGroups(assembly).map(group=>[formatDuplicateEdgeGroup(group),group])),steps=report.findings.flatMap(finding=>stepsFromFinding(finding,duplicateGroups));let truncated=report.findings.some(finding=>finding.sample_truncated);options.signal?.throwIfAborted();const redundancy=findRedundantRelationshipEdges(assembly.graph,{limit:redundancyLimit??options.maxSampleSize??25,...options.signal===void 0?{}:{signal:options.signal}});for(const row of redundancy.value)steps.push({op:"remove",code:"redundant_edge",subject:`${row.edge.source} -> ${row.edge.target} (${row.edge.kind})`,rationale:"The stored edge is implied by a longer same-family witness path; shortcut edges are sometimes deliberate emphasis, so confirm intent before removing.",evidence:[`witness: ${row.witness.join(" -> ")}`],confidence:"medium"});return truncated=truncated||redundancy.meta.truncated,{steps,report,truncated,cost:{visitedNodes:redundancy.meta.visitedNodes,inspectedEdges:redundancy.meta.inspectedEdges}}}export{planRelationshipRemediation};
2
2
  //# sourceMappingURL=remediation.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="123fbdac-0fc7-5f02-85d9-9a7ca55e1df1")}catch(e2){}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{isTerminalStatus}from"../../core/item/status.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.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{nowIso}from"../../core/shared/time.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";import{listAllItemMetadataLight}from"../../core/store/item-store.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger}from"../dependencies.js";import{analyzeGraphImpact,analyzeKnowledgeGraph,analyzeRelationshipExecution}from"../relationship-analytics.js";import{RelationshipGraph}from"../relationships.js";import{computeRelationshipDominators,detectRelationshipCommunities,findRedundantRelationshipEdges}from"./analytics.js";import{computeRelationshipCentrality,findRelationshipCutStructure}from"./centrality.js";import{analyzeRelationshipSchedule}from"./scheduling.js";import{deriveRelationshipDeadlines}from"./deadline-scheduling.js";import{assembleWorkspaceRelationshipGraph,getWorkspaceHierarchyIntegrity,resolveWorkspaceRelationshipKindRegistry}from"./assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./cache.js";import{clearDurableGraphCache,durableGraphCacheStatus,loadGraphAuditBaseline,openDurableGraphCache,persistDurableGraphResult,saveGraphAuditBaseline,shouldPersistDurableGraphCache,GRAPH_DURABLE_CACHE_MIN_ITEMS}from"./durable-cache.js";import{auditWorkspaceRelationshipGraph,diffRelationshipAuditSnapshots}from"./governance.js";import{RELATIONSHIP_AUDIT_FINDING_CODES}from"./governance-contracts.js";import{planRelationshipRemediation}from"./remediation.js";import{enumerateRelationshipPaths,hierarchyAncestors,hierarchyDescendants,orderingPredecessors,orderingSuccessors}from"./traversal.js";import{GRAPH_SUBCOMMAND_VALUES}from"../cli-contracts/enum-contracts.js";import{assertProjectionModeChoice}from"../output-projection.js";import{GRAPH_QUERY_DEFAULTS}from"./query-contracts.js";const ROOTED_SUBCOMMANDS=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function attachGraphProjection(result,summary,rowGroup){let projected=result;if(summary&&result.subcommand==="audit"){const{nodes,recorded_nodes,edges,active_nodes,terminal_nodes,missing_nodes,ordering_acyclic,active_ordering_acyclic,coverage_by_lifecycle}=result.profile;const populations=Object.fromEntries(Object.entries(coverage_by_lifecycle).map(([key,population])=>{const{degree_histogram:_histogram,...counts}=population;return[key,counts]}));projected={...result,profile:{nodes,recorded_nodes,edges,active_nodes,terminal_nodes,missing_nodes,ordering_acyclic,active_ordering_acyclic,coverage_by_lifecycle:populations}}}return{...projected,projection:{mode:summary?"summary":"full",declared_field_groups:rowGroup===void 0?[]:[{name:rowGroup,restore_with:"--full"}],included_field_groups:rowGroup===void 0||summary?[]:[rowGroup]}}}function parseGraphInvocation(subcommand,assembly,kinds,options){return{assembly,...kinds===void 0?{}:{kinds},maxDepth:parseMaxDepth(options.maxDepth),limit:subcommand==="impact"&&Number(options.limit)===0?0:parsePositiveInteger(options.limit,"limit")??(options.full===true?Number.MAX_SAFE_INTEGER:GRAPH_QUERY_DEFAULTS.rows),after:options.after?.trim()||void 0,direction:parseDirection(options.direction),maxPaths:parsePositiveInteger(options.maxPaths,"max-paths"),sample:parsePositiveInteger(options.sample,"sample")??GRAPH_QUERY_DEFAULTS.samples,exemptIsolates:normalizeIdList(options.exemptIsolate),exemptIsolateTypes:normalizeIdList(options.exemptIsolateType),saveBaseline:options.saveBaseline===true,summary:options.summary===true,unbounded:options.full===true}}function normalizeIdList(raw){if(raw===void 0)return[];return(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0)}function parseGraphSubcommand(raw,id,target){const candidate=raw.trim().toLowerCase();if(!GRAPH_SUBCOMMAND_VALUES.includes(candidate)){throw createUnknownSubcommandError({command_path:"graph",token:candidate||"<empty>",allowed:GRAPH_SUBCOMMAND_VALUES})}const subcommand=candidate;if(ROOTED_SUBCOMMANDS.has(subcommand)&&!id?.trim()){throw new PmCliError(`graph ${subcommand} requires an item id.`,EXIT_CODE.USAGE)}if(subcommand==="paths"&&!target?.trim()){throw new PmCliError("graph paths requires a source and a target item id.",EXIT_CODE.USAGE)}return subcommand}function rethrowGraphUsage(error){if(error instanceof TypeError)throw new PmCliError(error.message,EXIT_CODE.USAGE);throw error}function projectQueryMeta(meta){return{truncated:meta.truncated,cost:{visited_nodes:meta.visitedNodes,inspected_edges:meta.inspectedEdges}}}function canonicalizeGraphId(assembly,raw){const wanted=raw.trim().toLowerCase();for(const detail of assembly.details){if(detail.id.trim().toLowerCase()===wanted&&!assembly.missingIdSet.has(detail.id.toLowerCase())){return detail.id}}throw new PmCliError(`Item ${raw} not found`,EXIT_CODE.NOT_FOUND)}function runGraphTraversal(subcommand,root,invocation){const walk={ancestors:hierarchyAncestors,descendants:hierarchyDescendants,predecessors:orderingPredecessors,successors:orderingSuccessors}[subcommand];let result;try{result=walk(invocation.assembly.graph,root,{...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},limit:invocation.limit,...invocation.after===void 0?{}:{after:invocation.after}})}catch(error){rethrowGraphUsage(error)}const meta=projectQueryMeta(result.meta);return{subcommand,root,count:result.value.length,...meta,...result.meta.nextCursor===void 0?{}:{next_cursor:result.meta.nextCursor},...invocation.summary?{}:{ids:result.value}}}function runGraphPaths(root,target,invocation){const result=enumerateRelationshipPaths(invocation.assembly.graph,root,target,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},...invocation.maxPaths===void 0?{}:{maxPaths:invocation.maxPaths}});return{subcommand:"paths",root,target,direction:invocation.direction,count:result.value.length,...projectQueryMeta(result.meta),...invocation.summary?{}:{paths:result.value.map(path=>({nodes:path.nodes,kinds:path.edges.map(edge=>edge.kind),length:path.length}))}}}function runGraphImpact(root,invocation){let analysis;try{analysis=analyzeGraphImpact(invocation.assembly.graph,root,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},...invocation.unbounded?{}:{limit:invocation.limit},...invocation.after===void 0?{}:{after:invocation.after}})}catch(error){rethrowGraphUsage(error)}return{subcommand:"impact",root,direction:invocation.direction,count:analysis.affected.length,truncated:analysis.truncated,...analysis.nextCursor===void 0?{}:{next_cursor:analysis.nextCursor},cost:{visited_nodes:analysis.cost.visitedNodes,inspected_edges:analysis.cost.inspectedEdges},...invocation.summary?{}:{affected:analysis.affected}}}function buildGraphExecutionSummary(execution,summary,sampleLimit){return{acyclic:execution.acyclic,ordered_node_count:execution.order.length,layer_count:execution.layers.length,frontier_count:execution.frontier.length,critical_path_length:execution.criticalPathLength,cycle_count:execution.cycles.length,...summary?{}:{frontier:execution.frontier.slice(0,sampleLimit),critical_path:execution.criticalPath.slice(0,sampleLimit),cycles:execution.cycles.slice(0,sampleLimit)}}}function buildGraphKnowledgeSummary(knowledge,summary,sampleLimit){return{component_count:knowledge.components.length,largest_component_size:knowledge.components[0]?.length??0,orphan_count:knowledge.orphans.length,...summary?{}:{orphans:knowledge.orphans.slice(0,sampleLimit),hubs:knowledge.hubs.slice(0,sampleLimit)}}}function buildGraphHierarchySummary(hierarchy,summary,sampleLimit){let legacyCycleCount=0;let legacyCardinalityCount=0;let legacyDivergenceCount=0;for(const finding of hierarchy.cycles){legacyCycleCount+=Number(finding.legacy_terminal)}for(const finding of hierarchy.cardinality_violations){legacyCardinalityCount+=Number(finding.legacy_terminal)}for(const finding of hierarchy.divergences){legacyDivergenceCount+=Number(finding.legacy_terminal)}return{acyclic:hierarchy.cycles.length===0,relation_count:hierarchy.relations.length,cycle_count:hierarchy.cycles.length,active_cycle_count:hierarchy.cycles.length-legacyCycleCount,legacy_cycle_count:legacyCycleCount,cardinality_violation_count:hierarchy.cardinality_violations.length,active_cardinality_violation_count:hierarchy.cardinality_violations.length-legacyCardinalityCount,legacy_cardinality_violation_count:legacyCardinalityCount,parent_divergence_count:hierarchy.divergences.length,active_parent_divergence_count:hierarchy.divergences.length-legacyDivergenceCount,legacy_parent_divergence_count:legacyDivergenceCount,...summary?{}:{cycles:hierarchy.cycles.slice(0,sampleLimit).map(cycle=>cycle.item_ids)}}}function runGraphAnalyze(invocation){const graph=invocation.assembly.graph;const sampleLimit=invocation.limit;const execution=analyzeRelationshipExecution(graph,{registry:graph.registry()});const knowledge=analyzeKnowledgeGraph(graph);return{subcommand:"analyze",node_count:graph.nodes().length,edge_count:graph.edges().length,edge_basis:"deduplicated_directed",sample_limit:sampleLimit,execution:buildGraphExecutionSummary(execution,invocation.summary,sampleLimit),knowledge:buildGraphKnowledgeSummary(knowledge,invocation.summary,sampleLimit),hierarchy:buildGraphHierarchySummary(getWorkspaceHierarchyIntegrity(invocation.assembly),invocation.summary,sampleLimit)}}function runGraphAudit(invocation,isTerminal){const report=auditWorkspaceRelationshipGraph(invocation.assembly,{isTerminal,maxSampleSize:invocation.sample,...invocation.exemptIsolates.length===0?{}:{exemptIsolates:invocation.exemptIsolates},...invocation.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:invocation.exemptIsolateTypes}});const bySeverity={};const byCode={};const affectedBySeverity={};const affectedByCode={};for(const finding of report.findings){bySeverity[finding.severity]=(bySeverity[finding.severity]??0)+1;byCode[finding.code]=(byCode[finding.code]??0)+1;affectedBySeverity[finding.severity]=(affectedBySeverity[finding.severity]??0)+finding.count;affectedByCode[finding.code]=(affectedByCode[finding.code]??0)+finding.count}const{finding_subjects_by_code:_findingSubjects,...compactProfile}=report.profile;return{subcommand:"audit",truncated:report.findings.length>invocation.limit,finding_count:report.findings.length,findings_by_severity:bySeverity,findings_by_code:byCode,affected_subjects_by_severity:affectedBySeverity,affected_subjects_by_code:affectedByCode,profile:invocation.summary?compactProfile:report.profile,legacy_alias_counts:invocation.assembly.legacyAliasCounts,...invocation.summary?{}:{findings:report.findings.slice(0,invocation.limit)}}}function runGraphCommunities(invocation){const sampleLimit=invocation.limit;const options={};if(invocation.kinds!==void 0)options.kinds=invocation.kinds;const result=detectRelationshipCommunities(invocation.assembly.graph,options);const analysis=result.value;return{subcommand:"communities",community_count:analysis.communities.length,largest_community_size:analysis.communities[0]?.size??0,iterations:analysis.iterations,converged:analysis.converged,truncated:!analysis.converged||analysis.communities.length>sampleLimit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{communities:analysis.communities.slice(0,sampleLimit).map(community=>({representative:community.representative,size:community.size,members:community.members.slice(0,sampleLimit)}))}}}function runGraphRedundancy(invocation){let result;try{result=findRedundantRelationshipEdges(invocation.assembly.graph,{...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},limit:invocation.limit})}catch(error){rethrowGraphUsage(error)}return{subcommand:"redundancy",redundant_count:result.value.length,...projectQueryMeta(result.meta),...invocation.summary?{}:{redundant:result.value.map(row=>({source:row.edge.source,target:row.edge.target,kind:row.edge.kind,witness:row.witness}))}}}function runGraphDominators(root,invocation){const limit=invocation.limit;const result=computeRelationshipDominators(invocation.assembly.graph,root,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth}});const bottlenecks=result.value.rows.filter(row=>row.dominatedCount>0);return{subcommand:"dominators",root,direction:invocation.direction,reachable_count:result.value.reachableCount,bottleneck_count:bottlenecks.length,truncated:result.meta.truncated||bottlenecks.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{bottlenecks:bottlenecks.slice(0,limit).map(row=>({id:row.id,idom:row.idom,dominated_count:row.dominatedCount}))}}}function runGraphSlack(invocation){const limit=invocation.limit;const analysis=analyzeRelationshipSchedule(invocation.assembly.graph);const criticalCount=analysis.rows.filter(row=>row.critical).length;return{subcommand:"slack",acyclic:analysis.acyclic,makespan:analysis.makespan,scheduled_count:analysis.scheduledCount,critical_count:criticalCount,critical_path_length:analysis.criticalPathLength,cycle_count:analysis.cycles.length,truncated:analysis.rows.length>limit,...invocation.summary?{}:{critical_path:analysis.criticalPath.slice(0,limit),rows:analysis.rows.slice(0,limit).map(row=>({id:row.id,earliest_start:row.earliestStart,latest_start:row.latestStart,slack:row.slack,critical:row.critical}))}}}function runGraphCentrality(invocation){const limit=invocation.limit;const result=computeRelationshipCentrality(invocation.assembly.graph,invocation.kinds===void 0?{}:{kinds:invocation.kinds});const analysis=result.value;return{subcommand:"centrality",node_count:analysis.nodeCount,edge_count:analysis.edgeCount,edge_basis:"simple_undirected",truncated:analysis.rows.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{rows:analysis.rows.slice(0,limit).map(row=>({id:row.id,degree:row.degree,in_degree:row.inDegree,out_degree:row.outDegree,betweenness:row.betweenness,closeness:row.closeness}))}}}function runGraphArticulation(invocation){const limit=invocation.limit;const result=findRelationshipCutStructure(invocation.assembly.graph,invocation.kinds===void 0?{}:{kinds:invocation.kinds});const{articulationPoints,bridges}=result.value;return{subcommand:"articulation",articulation_count:articulationPoints.length,bridge_count:bridges.length,truncated:articulationPoints.length>limit||bridges.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{articulation_points:articulationPoints.slice(0,limit),bridges:bridges.slice(0,limit)}}}function runGraphPlan(invocation,isTerminal){const limit=invocation.limit;const plan=planRelationshipRemediation(invocation.assembly,{isTerminal,redundancyLimit:limit,maxSampleSize:invocation.sample,...invocation.exemptIsolates.length===0?{}:{exemptIsolates:invocation.exemptIsolates},...invocation.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:invocation.exemptIsolateTypes}});const byOp={};const byCode={};for(const step of plan.steps){byOp[step.op]=(byOp[step.op]??0)+1;byCode[step.code]=(byCode[step.code]??0)+1}return{subcommand:"plan",step_count:plan.steps.length,steps_by_op:byOp,steps_by_code:byCode,finding_count:plan.report.findings.length,truncated:plan.truncated||plan.steps.length>limit,cost:{visited_nodes:plan.cost.visitedNodes,inspected_edges:plan.cost.inspectedEdges},...invocation.summary?{}:{steps:plan.steps.slice(0,limit)}}}function buildGraphQueryKey(subcommand,root,pathsTarget,invocation){return JSON.stringify({projection_version:2,subcommand,root:root??null,target:pathsTarget??null,kinds:invocation.kinds??null,maxDepth:invocation.maxDepth??null,limit:invocation.limit,after:invocation.after??null,direction:invocation.direction,maxPaths:invocation.maxPaths??null,sample:invocation.sample,exemptIsolates:[...new Set(invocation.exemptIsolates.map(id=>id.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(invocation.exemptIsolateTypes.map(type=>type.toLowerCase()))].sort(),summary:invocation.summary,unbounded:invocation.unbounded})}function executeGraphSubcommand(subcommand,root,pathsTarget,invocation,isTerminal){if(subcommand==="analyze")return runGraphAnalyze(invocation);if(subcommand==="audit")return runGraphAudit(invocation,isTerminal);if(subcommand==="plan")return runGraphPlan(invocation,isTerminal);if(subcommand==="communities")return runGraphCommunities(invocation);if(subcommand==="redundancy")return runGraphRedundancy(invocation);if(subcommand==="dominators")return runGraphDominators(root,invocation);if(subcommand==="slack")return runGraphSlack(invocation);if(subcommand==="centrality")return runGraphCentrality(invocation);if(subcommand==="articulation")return runGraphArticulation(invocation);if(subcommand==="paths")return runGraphPaths(root,pathsTarget,invocation);if(subcommand==="impact")return runGraphImpact(root,invocation);return runGraphTraversal(subcommand,root,invocation)}function assertGraphFlagScope(subcommand,options){if(subcommand!=="index"&&(options.rebuild===true||options.clear===true))throw new PmCliError("--rebuild and --clear apply only to graph index.",EXIT_CODE.USAGE);if(subcommand!=="audit"&&options.saveBaseline===true)throw new PmCliError("--save-baseline applies only to graph audit.",EXIT_CODE.USAGE);if(subcommand==="slack"&&options.kind!==void 0)throw new PmCliError("graph slack analyzes every ordering kind; --kind is not supported.",EXIT_CODE.USAGE);if(options.rebuild===true&&options.clear===true)throw new PmCliError("graph index accepts either --rebuild or --clear, not both.",EXIT_CODE.USAGE);if(options.full===true&&options.limit!==void 0)throw new PmCliError(`graph ${subcommand} accepts either --full or --limit, not both.`,EXIT_CODE.USAGE)}async function runGraphIndex(pmRoot,fingerprint,invocation,itemCount,isTerminal,options){let action="status";if(options.clear===true){await clearDurableGraphCache(pmRoot);action="cleared"}if(options.rebuild===true){await clearDurableGraphCache(pmRoot);const view=await openDurableGraphCache(pmRoot,fingerprint);const warmInvocation={assembly:invocation.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:false,summary:true,limit:GRAPH_QUERY_DEFAULTS.rows,sample:GRAPH_QUERY_DEFAULTS.samples,unbounded:false};for(const warm of["analyze","audit"]){await persistDurableGraphResult(pmRoot,fingerprint,view,buildGraphQueryKey(warm,void 0,void 0,warmInvocation),executeGraphSubcommand(warm,void 0,void 0,warmInvocation,isTerminal))}action="rebuilt"}const status=await durableGraphCacheStatus(pmRoot,fingerprint);return{subcommand:"index",action,state:status.exists?status.fresh?"fresh":"stale":"absent",entry_count:status.entry_count,item_count:itemCount,min_items_threshold:GRAPH_DURABLE_CACHE_MIN_ITEMS,persist_enabled:shouldPersistDurableGraphCache(itemCount,status.exists),current_fingerprint:fingerprint.slice(0,12),...status.saved_at===void 0?{}:{saved_at:status.saved_at},...status.bytes===void 0?{}:{bytes:status.bytes}}}async function applyAuditBaseline(pmRoot,fingerprint,audit,saveBaseline){const current={saved_at:new Date().toISOString(),fingerprint,affected_subjects_by_code:audit.affected_subjects_by_code,profile:{...audit.profile,finding_subjects_by_code:Object.fromEntries(RELATIONSHIP_AUDIT_FINDING_CODES.map(code=>[code,audit.affected_subjects_by_code[code]??0]))}};const stored=await loadGraphAuditBaseline(pmRoot);if(saveBaseline)await saveGraphAuditBaseline(pmRoot,current);return stored===void 0?audit:{...audit,baseline:diffRelationshipAuditSnapshots(stored,current)}}async function persistDurableGraphResultBestEffort(pmRoot,fingerprint,view,queryKey,result){try{await persistDurableGraphResult(pmRoot,fingerprint,view,queryKey,result)}catch{}}function attachDeadlineSchedule(value,invocation,items,isTerminal){if(value.subcommand!=="slack")return;const terminal=new Set(invocation.assembly.details.filter(detail=>isTerminal(detail.status)).map(detail=>detail.id));const graph=invocation.assembly.graph;const activeGraph=new RelationshipGraph(graph.nodes().filter(id=>!terminal.has(id)),graph.edges().filter(edge=>!terminal.has(edge.source)&&!terminal.has(edge.target)),graph.registry());const analysis=deriveRelationshipDeadlines(activeGraph,items.filter(item=>!terminal.has(item.id)),{now:nowIso(),limit:invocation.limit});const{rows,residuals,overcommitted,...counts}=analysis;value.deadline_schedule={population:"active",...counts,...invocation.summary?{}:{rows,residuals,overcommitted}}}async function runGraph(subcommandRaw,id,target,options,global2){const subcommand=parseGraphSubcommand(subcommandRaw,id,target);assertProjectionModeChoice(options.summary===true,options.full===true,"--summary");const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot);const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations());const items=await listAllItemMetadataLight(pmRoot,settings.item_format,typeRegistry.type_to_folder,void 0,settings.schema);const statusRegistry=resolveRuntimeStatusRegistry(settings.schema);const isTerminal=status=>isTerminalStatus(status,statusRegistry);assertGraphFlagScope(subcommand,options);const relationshipRegistry=resolveWorkspaceRelationshipKindRegistry();const kinds=parseKinds(options.kind,relationshipRegistry);const lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry));const invocation=parseGraphInvocation(subcommand,lookup.assembly,kinds,options);if(subcommand==="index"){return attachGraphProjection(await runGraphIndex(pmRoot,lookup.fingerprint,invocation,items.length,isTerminal,options),false)}const root=ROOTED_SUBCOMMANDS.has(subcommand)?canonicalizeGraphId(invocation.assembly,id):void 0;const pathsTarget=subcommand==="paths"?canonicalizeGraphId(invocation.assembly,target):void 0;const queryKey=buildGraphQueryKey(subcommand,root,pathsTarget,invocation);const durableView=await openDurableGraphCache(pmRoot,lookup.fingerprint);const durableValue=durableView.results[queryKey];const memo=lookup.memoize(queryKey,()=>durableValue!==void 0?structuredClone(durableValue):executeGraphSubcommand(subcommand,root,pathsTarget,invocation,isTerminal));const persistEnabled=shouldPersistDurableGraphCache(items.length,durableView.exists);if(!memo.reused&&durableValue===void 0&&persistEnabled){await persistDurableGraphResultBestEffort(pmRoot,lookup.fingerprint,durableView,queryKey,memo.value)}const value=memo.value.subcommand==="audit"?await applyAuditBaseline(pmRoot,lookup.fingerprint,memo.value,invocation.saveBaseline):memo.value;value.cache={fingerprint:lookup.fingerprint.slice(0,12),assembly:lookup.assemblyReused?"hit":"miss",result:memo.reused?"hit":"miss",durable:durableValue!==void 0?"hit":persistEnabled?"miss":"off"};attachDeadlineSchedule(value,invocation,items,isTerminal);return attachGraphProjection(value,invocation.summary,"result_rows")}export{GRAPH_SUBCOMMAND_VALUES,parseGraphSubcommand,runGraph};
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]="66df3949-0caf-5f01-8cec-3bba3d1e6111")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{isTerminalStatus}from"../../core/item/status.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.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{nowIso}from"../../core/shared/time.js";import{createUnknownSubcommandError}from"../agent/subcommand-recovery.js";import{listAllItemMetadataLight}from"../../core/store/item-store.js";import{resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{parseDirection,parseKinds,parseMaxDepth,parsePositiveInteger}from"../dependencies.js";import{analyzeGraphImpact,analyzeKnowledgeGraph,analyzeRelationshipExecution}from"../relationship-analytics.js";import{RelationshipGraph}from"../relationships.js";import{computeRelationshipDominators,detectRelationshipCommunities,findRedundantRelationshipEdges}from"./analytics.js";import{computeRelationshipCentrality,findRelationshipCutStructure}from"./centrality.js";import{analyzeRelationshipSchedule}from"./scheduling.js";import{deriveRelationshipDeadlines}from"./deadline-scheduling.js";import{assembleWorkspaceRelationshipGraph,getWorkspaceHierarchyIntegrity,resolveWorkspaceRelationshipKindRegistry}from"./assembly.js";import{computeWorkspaceGraphFingerprint,workspaceGraphCache}from"./cache.js";import{clearDurableGraphCache,durableGraphCacheStatus,loadGraphAuditBaseline,openDurableGraphCache,persistDurableGraphResult,saveGraphAuditBaseline,shouldPersistDurableGraphCache,GRAPH_DURABLE_CACHE_MIN_ITEMS}from"./durable-cache.js";import{auditWorkspaceRelationshipGraph,diffRelationshipAuditSnapshots}from"./governance.js";import{RELATIONSHIP_AUDIT_FINDING_CODES}from"./governance-contracts.js";import{planRelationshipRemediation}from"./remediation.js";import{enumerateRelationshipPaths,hierarchyAncestors,hierarchyDescendants,orderingPredecessors,orderingSuccessors}from"./traversal.js";import{GRAPH_SUBCOMMAND_VALUES}from"../cli-contracts/enum-contracts.js";import{assertProjectionModeChoice}from"../output-projection.js";import{GRAPH_QUERY_DEFAULTS}from"./query-contracts.js";const ROOTED_SUBCOMMANDS=new Set(["ancestors","descendants","predecessors","successors","paths","impact","dominators"]);function attachGraphProjection(result,summary,rowGroup){let projected=result;if(summary&&result.subcommand==="audit"){const{nodes,recorded_nodes,edges,active_nodes,terminal_nodes,missing_nodes,ordering_acyclic,active_ordering_acyclic,coverage_by_lifecycle}=result.profile,populations=Object.fromEntries(Object.entries(coverage_by_lifecycle).map(([key,population])=>{const{degree_histogram:_histogram,...counts}=population;return[key,counts]}));projected={...result,profile:{nodes,recorded_nodes,edges,active_nodes,terminal_nodes,missing_nodes,ordering_acyclic,active_ordering_acyclic,coverage_by_lifecycle:populations}}}return{...projected,projection:{mode:summary?"summary":"full",declared_field_groups:rowGroup===void 0?[]:[{name:rowGroup,restore_with:"--full"}],included_field_groups:rowGroup===void 0||summary?[]:[rowGroup]}}}function parseGraphInvocation(subcommand,assembly,kinds,options){return{assembly,...kinds===void 0?{}:{kinds},maxDepth:parseMaxDepth(options.maxDepth),limit:subcommand==="impact"&&Number(options.limit)===0?0:parsePositiveInteger(options.limit,"limit")??(options.full===!0?Number.MAX_SAFE_INTEGER:GRAPH_QUERY_DEFAULTS.rows),after:options.after?.trim()||void 0,direction:parseDirection(options.direction),maxPaths:parsePositiveInteger(options.maxPaths,"max-paths"),sample:parsePositiveInteger(options.sample,"sample")??GRAPH_QUERY_DEFAULTS.samples,exemptIsolates:normalizeIdList(options.exemptIsolate),exemptIsolateTypes:normalizeIdList(options.exemptIsolateType),saveBaseline:options.saveBaseline===!0,summary:options.summary===!0,unbounded:options.full===!0}}function normalizeIdList(raw){return raw===void 0?[]:(Array.isArray(raw)?raw:[raw]).flatMap(value=>value.split(",")).map(value=>value.trim()).filter(value=>value.length>0)}function parseGraphSubcommand(raw,id,target){const candidate=raw.trim().toLowerCase();if(!GRAPH_SUBCOMMAND_VALUES.includes(candidate))throw createUnknownSubcommandError({command_path:"graph",token:candidate||"<empty>",allowed:GRAPH_SUBCOMMAND_VALUES});const subcommand=candidate;if(ROOTED_SUBCOMMANDS.has(subcommand)&&!id?.trim())throw new PmCliError(`graph ${subcommand} requires an item id.`,EXIT_CODE.USAGE);if(subcommand==="paths"&&!target?.trim())throw new PmCliError("graph paths requires a source and a target item id.",EXIT_CODE.USAGE);return subcommand}function rethrowGraphUsage(error){throw error instanceof TypeError?new PmCliError(error.message,EXIT_CODE.USAGE):error}function projectQueryMeta(meta){return{truncated:meta.truncated,cost:{visited_nodes:meta.visitedNodes,inspected_edges:meta.inspectedEdges}}}function canonicalizeGraphId(assembly,raw){const wanted=raw.trim().toLowerCase();for(const detail of assembly.details)if(detail.id.trim().toLowerCase()===wanted&&!assembly.missingIdSet.has(detail.id.toLowerCase()))return detail.id;throw new PmCliError(`Item ${raw} not found`,EXIT_CODE.NOT_FOUND)}function runGraphTraversal(subcommand,root,invocation){const walk={ancestors:hierarchyAncestors,descendants:hierarchyDescendants,predecessors:orderingPredecessors,successors:orderingSuccessors}[subcommand];let result;try{result=walk(invocation.assembly.graph,root,{...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},limit:invocation.limit,...invocation.after===void 0?{}:{after:invocation.after}})}catch(error){rethrowGraphUsage(error)}const meta=projectQueryMeta(result.meta);return{subcommand,root,count:result.value.length,...meta,...result.meta.nextCursor===void 0?{}:{next_cursor:result.meta.nextCursor},...invocation.summary?{}:{ids:result.value}}}function runGraphPaths(root,target,invocation){const result=enumerateRelationshipPaths(invocation.assembly.graph,root,target,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},...invocation.maxPaths===void 0?{}:{maxPaths:invocation.maxPaths}});return{subcommand:"paths",root,target,direction:invocation.direction,count:result.value.length,...projectQueryMeta(result.meta),...invocation.summary?{}:{paths:result.value.map(path=>({nodes:path.nodes,kinds:path.edges.map(edge=>edge.kind),length:path.length}))}}}function runGraphImpact(root,invocation){let analysis;try{analysis=analyzeGraphImpact(invocation.assembly.graph,root,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},...invocation.unbounded?{}:{limit:invocation.limit},...invocation.after===void 0?{}:{after:invocation.after}})}catch(error){rethrowGraphUsage(error)}return{subcommand:"impact",root,direction:invocation.direction,count:analysis.affected.length,truncated:analysis.truncated,...analysis.nextCursor===void 0?{}:{next_cursor:analysis.nextCursor},cost:{visited_nodes:analysis.cost.visitedNodes,inspected_edges:analysis.cost.inspectedEdges},...invocation.summary?{}:{affected:analysis.affected}}}function buildGraphExecutionSummary(execution,summary,sampleLimit){return{acyclic:execution.acyclic,ordered_node_count:execution.order.length,layer_count:execution.layers.length,frontier_count:execution.frontier.length,critical_path_length:execution.criticalPathLength,cycle_count:execution.cycles.length,...summary?{}:{frontier:execution.frontier.slice(0,sampleLimit),critical_path:execution.criticalPath.slice(0,sampleLimit),cycles:execution.cycles.slice(0,sampleLimit)}}}function buildGraphKnowledgeSummary(knowledge,summary,sampleLimit){return{component_count:knowledge.components.length,largest_component_size:knowledge.components[0]?.length??0,orphan_count:knowledge.orphans.length,...summary?{}:{orphans:knowledge.orphans.slice(0,sampleLimit),hubs:knowledge.hubs.slice(0,sampleLimit)}}}function buildGraphHierarchySummary(hierarchy,summary,sampleLimit){let legacyCycleCount=0,legacyCardinalityCount=0,legacyDivergenceCount=0;for(const finding of hierarchy.cycles)legacyCycleCount+=Number(finding.legacy_terminal);for(const finding of hierarchy.cardinality_violations)legacyCardinalityCount+=Number(finding.legacy_terminal);for(const finding of hierarchy.divergences)legacyDivergenceCount+=Number(finding.legacy_terminal);return{acyclic:hierarchy.cycles.length===0,relation_count:hierarchy.relations.length,cycle_count:hierarchy.cycles.length,active_cycle_count:hierarchy.cycles.length-legacyCycleCount,legacy_cycle_count:legacyCycleCount,cardinality_violation_count:hierarchy.cardinality_violations.length,active_cardinality_violation_count:hierarchy.cardinality_violations.length-legacyCardinalityCount,legacy_cardinality_violation_count:legacyCardinalityCount,parent_divergence_count:hierarchy.divergences.length,active_parent_divergence_count:hierarchy.divergences.length-legacyDivergenceCount,legacy_parent_divergence_count:legacyDivergenceCount,...summary?{}:{cycles:hierarchy.cycles.slice(0,sampleLimit).map(cycle=>cycle.item_ids)}}}function runGraphAnalyze(invocation){const graph=invocation.assembly.graph,sampleLimit=invocation.limit,execution=analyzeRelationshipExecution(graph,{registry:graph.registry()}),knowledge=analyzeKnowledgeGraph(graph);return{subcommand:"analyze",node_count:graph.nodes().length,edge_count:graph.edges().length,edge_basis:"deduplicated_directed",sample_limit:sampleLimit,execution:buildGraphExecutionSummary(execution,invocation.summary,sampleLimit),knowledge:buildGraphKnowledgeSummary(knowledge,invocation.summary,sampleLimit),hierarchy:buildGraphHierarchySummary(getWorkspaceHierarchyIntegrity(invocation.assembly),invocation.summary,sampleLimit)}}function runGraphAudit(invocation,isTerminal){const report=auditWorkspaceRelationshipGraph(invocation.assembly,{isTerminal,maxSampleSize:invocation.sample,...invocation.exemptIsolates.length===0?{}:{exemptIsolates:invocation.exemptIsolates},...invocation.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:invocation.exemptIsolateTypes}}),bySeverity={},byCode={},affectedBySeverity={},affectedByCode={};for(const finding of report.findings)bySeverity[finding.severity]=(bySeverity[finding.severity]??0)+1,byCode[finding.code]=(byCode[finding.code]??0)+1,affectedBySeverity[finding.severity]=(affectedBySeverity[finding.severity]??0)+finding.count,affectedByCode[finding.code]=(affectedByCode[finding.code]??0)+finding.count;const{finding_subjects_by_code:_findingSubjects,...compactProfile}=report.profile;return{subcommand:"audit",truncated:report.findings.length>invocation.limit,finding_count:report.findings.length,findings_by_severity:bySeverity,findings_by_code:byCode,affected_subjects_by_severity:affectedBySeverity,affected_subjects_by_code:affectedByCode,profile:invocation.summary?compactProfile:report.profile,legacy_alias_counts:invocation.assembly.legacyAliasCounts,...invocation.summary?{}:{findings:report.findings.slice(0,invocation.limit)}}}function runGraphCommunities(invocation){const sampleLimit=invocation.limit,options={};invocation.kinds!==void 0&&(options.kinds=invocation.kinds);const result=detectRelationshipCommunities(invocation.assembly.graph,options),analysis=result.value;return{subcommand:"communities",community_count:analysis.communities.length,largest_community_size:analysis.communities[0]?.size??0,iterations:analysis.iterations,converged:analysis.converged,truncated:!analysis.converged||analysis.communities.length>sampleLimit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{communities:analysis.communities.slice(0,sampleLimit).map(community=>({representative:community.representative,size:community.size,members:community.members.slice(0,sampleLimit)}))}}}function runGraphRedundancy(invocation){let result;try{result=findRedundantRelationshipEdges(invocation.assembly.graph,{...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth},limit:invocation.limit})}catch(error){rethrowGraphUsage(error)}return{subcommand:"redundancy",redundant_count:result.value.length,...projectQueryMeta(result.meta),...invocation.summary?{}:{redundant:result.value.map(row=>({source:row.edge.source,target:row.edge.target,kind:row.edge.kind,witness:row.witness}))}}}function runGraphDominators(root,invocation){const limit=invocation.limit,result=computeRelationshipDominators(invocation.assembly.graph,root,{direction:invocation.direction,...invocation.kinds===void 0?{}:{kinds:invocation.kinds},...invocation.maxDepth===void 0?{}:{maxDepth:invocation.maxDepth}}),bottlenecks=result.value.rows.filter(row=>row.dominatedCount>0);return{subcommand:"dominators",root,direction:invocation.direction,reachable_count:result.value.reachableCount,bottleneck_count:bottlenecks.length,truncated:result.meta.truncated||bottlenecks.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{bottlenecks:bottlenecks.slice(0,limit).map(row=>({id:row.id,idom:row.idom,dominated_count:row.dominatedCount}))}}}function runGraphSlack(invocation){const limit=invocation.limit,analysis=analyzeRelationshipSchedule(invocation.assembly.graph),criticalCount=analysis.rows.filter(row=>row.critical).length;return{subcommand:"slack",acyclic:analysis.acyclic,makespan:analysis.makespan,scheduled_count:analysis.scheduledCount,critical_count:criticalCount,critical_path_length:analysis.criticalPathLength,cycle_count:analysis.cycles.length,truncated:analysis.rows.length>limit,...invocation.summary?{}:{critical_path:analysis.criticalPath.slice(0,limit),rows:analysis.rows.slice(0,limit).map(row=>({id:row.id,earliest_start:row.earliestStart,latest_start:row.latestStart,slack:row.slack,critical:row.critical}))}}}function runGraphCentrality(invocation){const limit=invocation.limit,result=computeRelationshipCentrality(invocation.assembly.graph,invocation.kinds===void 0?{}:{kinds:invocation.kinds}),analysis=result.value;return{subcommand:"centrality",node_count:analysis.nodeCount,edge_count:analysis.edgeCount,edge_basis:"simple_undirected",truncated:analysis.rows.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{rows:analysis.rows.slice(0,limit).map(row=>({id:row.id,degree:row.degree,in_degree:row.inDegree,out_degree:row.outDegree,betweenness:row.betweenness,closeness:row.closeness}))}}}function runGraphArticulation(invocation){const limit=invocation.limit,result=findRelationshipCutStructure(invocation.assembly.graph,invocation.kinds===void 0?{}:{kinds:invocation.kinds}),{articulationPoints,bridges}=result.value;return{subcommand:"articulation",articulation_count:articulationPoints.length,bridge_count:bridges.length,truncated:articulationPoints.length>limit||bridges.length>limit,cost:{visited_nodes:result.meta.visitedNodes,inspected_edges:result.meta.inspectedEdges},...invocation.summary?{}:{articulation_points:articulationPoints.slice(0,limit),bridges:bridges.slice(0,limit)}}}function runGraphPlan(invocation,isTerminal){const limit=invocation.limit,plan=planRelationshipRemediation(invocation.assembly,{isTerminal,redundancyLimit:limit,maxSampleSize:invocation.sample,...invocation.exemptIsolates.length===0?{}:{exemptIsolates:invocation.exemptIsolates},...invocation.exemptIsolateTypes.length===0?{}:{isolateExemptTypes:invocation.exemptIsolateTypes}}),byOp={},byCode={};for(const step of plan.steps)byOp[step.op]=(byOp[step.op]??0)+1,byCode[step.code]=(byCode[step.code]??0)+1;return{subcommand:"plan",step_count:plan.steps.length,steps_by_op:byOp,steps_by_code:byCode,finding_count:plan.report.findings.length,truncated:plan.truncated||plan.steps.length>limit,cost:{visited_nodes:plan.cost.visitedNodes,inspected_edges:plan.cost.inspectedEdges},...invocation.summary?{}:{steps:plan.steps.slice(0,limit)}}}function buildGraphQueryKey(subcommand,root,pathsTarget,invocation){return JSON.stringify({projection_version:2,subcommand,root:root??null,target:pathsTarget??null,kinds:invocation.kinds??null,maxDepth:invocation.maxDepth??null,limit:invocation.limit,after:invocation.after??null,direction:invocation.direction,maxPaths:invocation.maxPaths??null,sample:invocation.sample,exemptIsolates:[...new Set(invocation.exemptIsolates.map(id=>id.toLowerCase()))].sort(),exemptIsolateTypes:[...new Set(invocation.exemptIsolateTypes.map(type=>type.toLowerCase()))].sort(),summary:invocation.summary,unbounded:invocation.unbounded})}function executeGraphSubcommand(subcommand,root,pathsTarget,invocation,isTerminal){return subcommand==="analyze"?runGraphAnalyze(invocation):subcommand==="audit"?runGraphAudit(invocation,isTerminal):subcommand==="plan"?runGraphPlan(invocation,isTerminal):subcommand==="communities"?runGraphCommunities(invocation):subcommand==="redundancy"?runGraphRedundancy(invocation):subcommand==="dominators"?runGraphDominators(root,invocation):subcommand==="slack"?runGraphSlack(invocation):subcommand==="centrality"?runGraphCentrality(invocation):subcommand==="articulation"?runGraphArticulation(invocation):subcommand==="paths"?runGraphPaths(root,pathsTarget,invocation):subcommand==="impact"?runGraphImpact(root,invocation):runGraphTraversal(subcommand,root,invocation)}function assertGraphFlagScope(subcommand,options){if(subcommand!=="index"&&(options.rebuild===!0||options.clear===!0))throw new PmCliError("--rebuild and --clear apply only to graph index.",EXIT_CODE.USAGE);if(subcommand!=="audit"&&options.saveBaseline===!0)throw new PmCliError("--save-baseline applies only to graph audit.",EXIT_CODE.USAGE);if(subcommand==="slack"&&options.kind!==void 0)throw new PmCliError("graph slack analyzes every ordering kind; --kind is not supported.",EXIT_CODE.USAGE);if(options.rebuild===!0&&options.clear===!0)throw new PmCliError("graph index accepts either --rebuild or --clear, not both.",EXIT_CODE.USAGE);if(options.full===!0&&options.limit!==void 0)throw new PmCliError(`graph ${subcommand} accepts either --full or --limit, not both.`,EXIT_CODE.USAGE)}async function runGraphIndex(pmRoot,fingerprint,invocation,itemCount,isTerminal,options){let action="status";if(options.clear===!0&&(await clearDurableGraphCache(pmRoot),action="cleared"),options.rebuild===!0){await clearDurableGraphCache(pmRoot);const view=await openDurableGraphCache(pmRoot,fingerprint),warmInvocation={assembly:invocation.assembly,direction:"both",exemptIsolates:[],exemptIsolateTypes:[],saveBaseline:!1,summary:!0,limit:GRAPH_QUERY_DEFAULTS.rows,sample:GRAPH_QUERY_DEFAULTS.samples,unbounded:!1};for(const warm of["analyze","audit"])await persistDurableGraphResult(pmRoot,fingerprint,view,buildGraphQueryKey(warm,void 0,void 0,warmInvocation),executeGraphSubcommand(warm,void 0,void 0,warmInvocation,isTerminal));action="rebuilt"}const status=await durableGraphCacheStatus(pmRoot,fingerprint);return{subcommand:"index",action,state:status.exists?status.fresh?"fresh":"stale":"absent",entry_count:status.entry_count,item_count:itemCount,min_items_threshold:GRAPH_DURABLE_CACHE_MIN_ITEMS,persist_enabled:shouldPersistDurableGraphCache(itemCount,status.exists),current_fingerprint:fingerprint.slice(0,12),...status.saved_at===void 0?{}:{saved_at:status.saved_at},...status.bytes===void 0?{}:{bytes:status.bytes}}}async function applyAuditBaseline(pmRoot,fingerprint,audit,saveBaseline){const current={saved_at:new Date().toISOString(),fingerprint,affected_subjects_by_code:audit.affected_subjects_by_code,profile:{...audit.profile,finding_subjects_by_code:Object.fromEntries(RELATIONSHIP_AUDIT_FINDING_CODES.map(code=>[code,audit.affected_subjects_by_code[code]??0]))}},stored=await loadGraphAuditBaseline(pmRoot);return saveBaseline&&await saveGraphAuditBaseline(pmRoot,current),stored===void 0?audit:{...audit,baseline:diffRelationshipAuditSnapshots(stored,current)}}async function persistDurableGraphResultBestEffort(pmRoot,fingerprint,view,queryKey,result){try{await persistDurableGraphResult(pmRoot,fingerprint,view,queryKey,result)}catch{}}function attachDeadlineSchedule(value,invocation,items,isTerminal){if(value.subcommand!=="slack")return;const terminal=new Set(invocation.assembly.details.filter(detail=>isTerminal(detail.status)).map(detail=>detail.id)),graph=invocation.assembly.graph,activeGraph=new RelationshipGraph(graph.nodes().filter(id=>!terminal.has(id)),graph.edges().filter(edge=>!terminal.has(edge.source)&&!terminal.has(edge.target)),graph.registry()),analysis=deriveRelationshipDeadlines(activeGraph,items.filter(item=>!terminal.has(item.id)),{now:nowIso(),limit:invocation.limit}),{rows,residuals,overcommitted,...counts}=analysis;value.deadline_schedule={population:"active",...counts,...invocation.summary?{}:{rows,residuals,overcommitted}}}async function runGraph(subcommandRaw,id,target,options,global2){const subcommand=parseGraphSubcommand(subcommandRaw,id,target);assertProjectionModeChoice(options.summary===!0,options.full===!0,"--summary");const pmRoot=resolvePmRoot(process.cwd(),global2.path);await assertInitializedTracker(pmRoot);const 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),isTerminal=status=>isTerminalStatus(status,statusRegistry);assertGraphFlagScope(subcommand,options);const relationshipRegistry=resolveWorkspaceRelationshipKindRegistry(),kinds=parseKinds(options.kind,relationshipRegistry),lookup=workspaceGraphCache().lookup(pmRoot,computeWorkspaceGraphFingerprint(items,isTerminal,relationshipRegistry),()=>assembleWorkspaceRelationshipGraph(items,isTerminal,relationshipRegistry)),invocation=parseGraphInvocation(subcommand,lookup.assembly,kinds,options);if(subcommand==="index")return attachGraphProjection(await runGraphIndex(pmRoot,lookup.fingerprint,invocation,items.length,isTerminal,options),!1);const root=ROOTED_SUBCOMMANDS.has(subcommand)?canonicalizeGraphId(invocation.assembly,id):void 0,pathsTarget=subcommand==="paths"?canonicalizeGraphId(invocation.assembly,target):void 0,queryKey=buildGraphQueryKey(subcommand,root,pathsTarget,invocation),durableView=await openDurableGraphCache(pmRoot,lookup.fingerprint),durableValue=durableView.results[queryKey],memo=lookup.memoize(queryKey,()=>durableValue!==void 0?structuredClone(durableValue):executeGraphSubcommand(subcommand,root,pathsTarget,invocation,isTerminal)),persistEnabled=shouldPersistDurableGraphCache(items.length,durableView.exists);!memo.reused&&durableValue===void 0&&persistEnabled&&await persistDurableGraphResultBestEffort(pmRoot,lookup.fingerprint,durableView,queryKey,memo.value);const value=memo.value.subcommand==="audit"?await applyAuditBaseline(pmRoot,lookup.fingerprint,memo.value,invocation.saveBaseline):memo.value;return value.cache={fingerprint:lookup.fingerprint.slice(0,12),assembly:lookup.assemblyReused?"hit":"miss",result:memo.reused?"hit":"miss",durable:durableValue!==void 0?"hit":persistEnabled?"miss":"off"},attachDeadlineSchedule(value,invocation,items,isTerminal),attachGraphProjection(value,invocation.summary,"result_rows")}export{GRAPH_SUBCOMMAND_VALUES,parseGraphSubcommand,runGraph};
2
2
  //# sourceMappingURL=run.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1c9d9d0c-e989-568c-a49a-202f77e94806")}catch(e2){}})();import{analyzeRelationshipExecution}from"../relationship-analytics.js";import{orientOrderingEdge}from"./traversal.js";function collectOrderingParticipation(graph){const registry=graph.registry();const forward=new Map;const participants=new Set;for(const edge of graph.edges()){const definition=registry.require(edge.kind);if(!definition.ordering)continue;const{predecessor,successor}=orientOrderingEdge(edge,definition);participants.add(predecessor);participants.add(successor);if(predecessor===successor)continue;const targets=forward.get(predecessor);if(targets===void 0)forward.set(predecessor,new Set([successor]));else targets.add(successor)}return{forward,participants}}function latestFinishFor(successors,acyclic,latestStart,makespan){if(successors===void 0)return makespan;let bound=makespan;for(const successor of successors){if(!acyclic.has(successor))continue;bound=Math.min(bound,latestStart.get(successor))}return bound}function scheduleRow(id,earliestStart,latestStart){const slack=latestStart-earliestStart;return{id,earliestStart,earliestFinish:earliestStart+1,latestStart,latestFinish:latestStart+1,slack,critical:slack===0}}function computeScheduleRows(topoParticipants,participation,depth,acyclic,makespan){const latestStart=new Map;for(let index=topoParticipants.length-1;index>=0;index-=1){const id=topoParticipants[index];const finish=latestFinishFor(participation.forward.get(id),acyclic,latestStart,makespan);latestStart.set(id,finish-1)}return topoParticipants.map(id=>scheduleRow(id,depth[id],latestStart.get(id))).sort((left,right)=>left.slack-right.slack||left.earliestStart-right.earliestStart||left.id.localeCompare(right.id))}function analyzeRelationshipSchedule(graph,options={}){options.signal?.throwIfAborted();const execution=analyzeRelationshipExecution(graph,{registry:graph.registry()});const participation=collectOrderingParticipation(graph);const acyclic=new Set(execution.order);const topoParticipants=execution.order.filter(id=>participation.participants.has(id));const makespan=topoParticipants.reduce((peak,id)=>Math.max(peak,execution.depth[id]+1),0);const rows=computeScheduleRows(topoParticipants,participation,execution.depth,acyclic,makespan);const scheduled=rows.length>0;return{exact:true,acyclic:execution.acyclic,makespan,scheduledCount:rows.length,criticalPath:scheduled?execution.criticalPath:[],criticalPathLength:scheduled?execution.criticalPathLength:0,cycles:execution.cycles,rows,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}export{analyzeRelationshipSchedule};
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]="32f3ce0d-64ac-5ad4-b27a-2a279718de22")}catch{}})();import{analyzeRelationshipExecution}from"../relationship-analytics.js";import{orientOrderingEdge}from"./traversal.js";function collectOrderingParticipation(graph){const registry=graph.registry(),forward=new Map,participants=new Set;for(const edge of graph.edges()){const definition=registry.require(edge.kind);if(!definition.ordering)continue;const{predecessor,successor}=orientOrderingEdge(edge,definition);if(participants.add(predecessor),participants.add(successor),predecessor===successor)continue;const targets=forward.get(predecessor);targets===void 0?forward.set(predecessor,new Set([successor])):targets.add(successor)}return{forward,participants}}function latestFinishFor(successors,acyclic,latestStart,makespan){if(successors===void 0)return makespan;let bound=makespan;for(const successor of successors)acyclic.has(successor)&&(bound=Math.min(bound,latestStart.get(successor)));return bound}function scheduleRow(id,earliestStart,latestStart){const slack=latestStart-earliestStart;return{id,earliestStart,earliestFinish:earliestStart+1,latestStart,latestFinish:latestStart+1,slack,critical:slack===0}}function computeScheduleRows(topoParticipants,participation,depth,acyclic,makespan){const latestStart=new Map;for(let index=topoParticipants.length-1;index>=0;index-=1){const id=topoParticipants[index],finish=latestFinishFor(participation.forward.get(id),acyclic,latestStart,makespan);latestStart.set(id,finish-1)}return topoParticipants.map(id=>scheduleRow(id,depth[id],latestStart.get(id))).sort((left,right)=>left.slack-right.slack||left.earliestStart-right.earliestStart||left.id.localeCompare(right.id))}function analyzeRelationshipSchedule(graph,options={}){options.signal?.throwIfAborted();const execution=analyzeRelationshipExecution(graph,{registry:graph.registry()}),participation=collectOrderingParticipation(graph),acyclic=new Set(execution.order),topoParticipants=execution.order.filter(id=>participation.participants.has(id)),makespan=topoParticipants.reduce((peak,id)=>Math.max(peak,execution.depth[id]+1),0),rows=computeScheduleRows(topoParticipants,participation,execution.depth,acyclic,makespan),scheduled=rows.length>0;return{exact:!0,acyclic:execution.acyclic,makespan,scheduledCount:rows.length,criticalPath:scheduled?execution.criticalPath:[],criticalPathLength:scheduled?execution.criticalPathLength:0,cycles:execution.cycles,rows,provenance:{algorithm:"critical-path-method",edgeFamily:"ordering",weighting:"unit"}}}export{analyzeRelationshipSchedule};
2
2
  //# sourceMappingURL=scheduling.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="2ca317ff-f6b3-5f36-acc4-cd740b3d65e3")}catch(e2){}})();import{GRAPH_QUERY_DEFAULTS}from"./query-contracts.js";const DEFAULT_MAX_PATHS=GRAPH_QUERY_DEFAULTS.paths;const DEFAULT_MAX_VISITED_PATHS=GRAPH_QUERY_DEFAULTS.visited_paths;const DEFAULT_PATH_MAX_DEPTH=GRAPH_QUERY_DEFAULTS.path_depth;function assertPathBound(name,value){if(!Number.isFinite(value)||!Number.isInteger(value)||value<0)throw new TypeError(`Invalid path ${name} bound: ${String(value)}`)}function hierarchyParentEndpoint(edge,definition){return definition.hierarchyDirection==="target_parent"?edge.target:edge.source}function orderingPredecessorEndpoint(edge,definition){return(definition.precedence??"source_before_target")==="target_before_source"?edge.target:edge.source}function orientOrderingEdge(edge,definition){const predecessor=orderingPredecessorEndpoint(edge,definition);return{predecessor,successor:predecessor===edge.source?edge.target:edge.source}}function resolveFamilyKinds(graph,kinds,family){if(kinds===void 0)return void 0;const registry=graph.registry();const resolved=new Set;for(const kind of kinds){const definition=registry.require(kind);const traversal=definition.traversal;if(traversal==="association")throw new TypeError(`Relationship kind ${definition.kind} uses association traversal; use graph impact --direction both`);if(traversal!==family&&traversal!=="semantic"){const redirect=traversal==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${definition.kind} uses ${traversal} traversal; use ${redirect}`)}resolved.add(definition.kind)}return resolved}function expandSemanticNeighbors(graph,nodeId,familyKinds,family,matches){const registry=graph.registry();const rows=graph.neighborEdges(nodeId,{direction:"both",...familyKinds===void 0?{}:{kinds:[...familyKinds]}});const neighbors=[];const seen=new Set;for(const row of rows.value){const definition=registry.require(row.edge.kind);if(familyKinds===void 0&&!definition[family])continue;if(!matches(row,definition,nodeId))continue;if(seen.has(row.id))continue;seen.add(row.id);neighbors.push(row.id)}return{neighbors,inspectedEdges:rows.meta.inspectedEdges}}function appendSemanticExpansion(expansion,currentDepth,maxDepth,limit,after,state){if(currentDepth>=maxDepth){if(expansion.neighbors.some(neighbor=>!state.seen.has(neighbor)))state.truncated=true;return false}for(const neighbor of expansion.neighbors){if(state.seen.has(neighbor))continue;state.seen.add(neighbor);state.queue.push({id:neighbor,depth:currentDepth+1});if(!state.resumed){if(neighbor===after)state.resumed=true;continue}if(state.value.length>=limit){state.truncated=true;return true}state.value.push(neighbor)}return false}function boundedSemanticWalk(graph,start,options,family,matches){if(!graph.hasNode(start))throw new TypeError(`Relationship node not found: ${start}`);const familyKinds=resolveFamilyKinds(graph,options.kinds,family);const limit=options.limit??Number.POSITIVE_INFINITY;const maxDepth=options.maxDepth??Number.POSITIVE_INFINITY;const after=options.after;const state={seen:new Set([start]),value:[],queue:[{id:start,depth:0}],resumed:after===void 0,truncated:false};let visitedNodes=0;let inspectedEdges=0;for(let index=0;index<state.queue.length;index+=1){options.signal?.throwIfAborted();const current=state.queue[index];visitedNodes+=1;const expansion=expandSemanticNeighbors(graph,current.id,familyKinds,family,matches);inspectedEdges+=expansion.inspectedEdges;if(appendSemanticExpansion(expansion,current.depth,maxDepth,limit,after,state))break}if(!state.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${after}`);return{value:state.value,meta:{visitedNodes,inspectedEdges,truncated:state.truncated,nextCursor:state.value.at(-1)}}}function assertPathEndpoint(graph,id){if(!graph.hasNode(id))throw new TypeError(`Relationship node not found: ${id}`)}function readPathContinuations(graph,partial,options,direction,state){const rows=graph.neighborEdges(partial.nodes.at(-1),{direction,...options.kinds===void 0?{}:{kinds:options.kinds}});state.inspectedEdges+=rows.meta.inspectedEdges;return rows.value.filter(row=>!partial.nodeSet.has(row.id))}function expandPartialPath(graph,partial,target,options,direction,probeLimit,state){for(const row of readPathContinuations(graph,partial,options,direction,state)){const nodes=[...partial.nodes,row.id];const nodeSet=new Set(partial.nodeSet).add(row.id);const edges=[...partial.edges,row.edge];if(row.id===target){state.value.push({nodes,edges,length:edges.length});if(state.value.length>=probeLimit)return true}else{state.queue.push({nodes,nodeSet,edges})}}return false}function hierarchyAncestors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"hierarchy",(row,definition)=>hierarchyParentEndpoint(row.edge,definition)===row.id)}function hierarchyDescendants(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"hierarchy",(row,definition,nodeId)=>hierarchyParentEndpoint(row.edge,definition)===nodeId)}function orderingPredecessors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"ordering",(row,definition)=>orderingPredecessorEndpoint(row.edge,definition)===row.id)}function orderingSuccessors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"ordering",(row,definition,nodeId)=>orderingPredecessorEndpoint(row.edge,definition)===nodeId)}function enumerateNonZeroRelationshipPaths(graph,source,target,options,maxPaths,maxVisitedPaths,maxDepth,direction){const state={value:[],queue:[{nodes:[source],nodeSet:new Set([source]),edges:[]}],inspectedEdges:0};let visitedNodes=0;let truncated=false;const probeLimit=maxPaths+1;for(let index=0;index<state.queue.length;index+=1){options.signal?.throwIfAborted();if(state.value.length>=probeLimit||visitedNodes>=maxVisitedPaths){truncated=true;break}const partial=state.queue[index];visitedNodes+=1;if(partial.edges.length>=maxDepth){if(readPathContinuations(graph,partial,options,direction,state).length>0)truncated=true;continue}if(expandPartialPath(graph,partial,target,options,direction,probeLimit,state)){truncated=true;break}}return{value:state.value.slice(0,maxPaths),meta:{visitedNodes,inspectedEdges:state.inspectedEdges,truncated}}}function enumerateRelationshipPaths(graph,source,target,options={}){assertPathEndpoint(graph,source);assertPathEndpoint(graph,target);const maxPaths=options.maxPaths??DEFAULT_MAX_PATHS;const maxVisitedPaths=options.maxVisitedPaths??DEFAULT_MAX_VISITED_PATHS;const maxDepth=options.maxDepth??DEFAULT_PATH_MAX_DEPTH;assertPathBound("maxPaths",maxPaths);assertPathBound("maxVisitedPaths",maxVisitedPaths);assertPathBound("maxDepth",maxDepth);const direction=options.direction??"outgoing";options.signal?.throwIfAborted();for(const kind of options.kinds??[])graph.registry().require(kind);if(source===target){if(maxPaths===0){return{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:true}}}return{value:[{nodes:[source],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:false}}}return enumerateNonZeroRelationshipPaths(graph,source,target,options,maxPaths,maxVisitedPaths,maxDepth,direction)}export{enumerateRelationshipPaths,hierarchyAncestors,hierarchyDescendants,hierarchyParentEndpoint,orderingPredecessorEndpoint,orderingPredecessors,orderingSuccessors,orientOrderingEdge};
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]="f60c628a-2e42-5770-a001-39cce5f92595")}catch{}})();import{GRAPH_QUERY_DEFAULTS}from"./query-contracts.js";const DEFAULT_MAX_PATHS=GRAPH_QUERY_DEFAULTS.paths,DEFAULT_MAX_VISITED_PATHS=GRAPH_QUERY_DEFAULTS.visited_paths,DEFAULT_PATH_MAX_DEPTH=GRAPH_QUERY_DEFAULTS.path_depth;function assertPathBound(name,value){if(!Number.isFinite(value)||!Number.isInteger(value)||value<0)throw new TypeError(`Invalid path ${name} bound: ${String(value)}`)}function hierarchyParentEndpoint(edge,definition){return definition.hierarchyDirection==="target_parent"?edge.target:edge.source}function orderingPredecessorEndpoint(edge,definition){return(definition.precedence??"source_before_target")==="target_before_source"?edge.target:edge.source}function orientOrderingEdge(edge,definition){const predecessor=orderingPredecessorEndpoint(edge,definition);return{predecessor,successor:predecessor===edge.source?edge.target:edge.source}}function resolveFamilyKinds(graph,kinds,family){if(kinds===void 0)return;const registry=graph.registry(),resolved=new Set;for(const kind of kinds){const definition=registry.require(kind),traversal=definition.traversal;if(traversal==="association")throw new TypeError(`Relationship kind ${definition.kind} uses association traversal; use graph impact --direction both`);if(traversal!==family&&traversal!=="semantic"){const redirect=traversal==="hierarchy"?"graph ancestors or graph descendants":"graph predecessors or graph successors";throw new TypeError(`Relationship kind ${definition.kind} uses ${traversal} traversal; use ${redirect}`)}resolved.add(definition.kind)}return resolved}function expandSemanticNeighbors(graph,nodeId,familyKinds,family,matches){const registry=graph.registry(),rows=graph.neighborEdges(nodeId,{direction:"both",...familyKinds===void 0?{}:{kinds:[...familyKinds]}}),neighbors=[],seen=new Set;for(const row of rows.value){const definition=registry.require(row.edge.kind);familyKinds===void 0&&!definition[family]||matches(row,definition,nodeId)&&(seen.has(row.id)||(seen.add(row.id),neighbors.push(row.id)))}return{neighbors,inspectedEdges:rows.meta.inspectedEdges}}function appendSemanticExpansion(expansion,currentDepth,maxDepth,limit,after,state){if(currentDepth>=maxDepth)return expansion.neighbors.some(neighbor=>!state.seen.has(neighbor))&&(state.truncated=!0),!1;for(const neighbor of expansion.neighbors)if(!state.seen.has(neighbor)){if(state.seen.add(neighbor),state.queue.push({id:neighbor,depth:currentDepth+1}),!state.resumed){neighbor===after&&(state.resumed=!0);continue}if(state.value.length>=limit)return state.truncated=!0,!0;state.value.push(neighbor)}return!1}function boundedSemanticWalk(graph,start,options,family,matches){if(!graph.hasNode(start))throw new TypeError(`Relationship node not found: ${start}`);const familyKinds=resolveFamilyKinds(graph,options.kinds,family),limit=options.limit??Number.POSITIVE_INFINITY,maxDepth=options.maxDepth??Number.POSITIVE_INFINITY,after=options.after,state={seen:new Set([start]),value:[],queue:[{id:start,depth:0}],resumed:after===void 0,truncated:!1};let visitedNodes=0,inspectedEdges=0;for(let index=0;index<state.queue.length;index+=1){options.signal?.throwIfAborted();const current=state.queue[index];visitedNodes+=1;const expansion=expandSemanticNeighbors(graph,current.id,familyKinds,family,matches);if(inspectedEdges+=expansion.inspectedEdges,appendSemanticExpansion(expansion,current.depth,maxDepth,limit,after,state))break}if(!state.resumed)throw new TypeError(`Traversal cursor not found in sequence: ${after}`);return{value:state.value,meta:{visitedNodes,inspectedEdges,truncated:state.truncated,nextCursor:state.value.at(-1)}}}function assertPathEndpoint(graph,id){if(!graph.hasNode(id))throw new TypeError(`Relationship node not found: ${id}`)}function readPathContinuations(graph,partial,options,direction,state){const rows=graph.neighborEdges(partial.nodes.at(-1),{direction,...options.kinds===void 0?{}:{kinds:options.kinds}});return state.inspectedEdges+=rows.meta.inspectedEdges,rows.value.filter(row=>!partial.nodeSet.has(row.id))}function expandPartialPath(graph,partial,target,options,direction,probeLimit,state){for(const row of readPathContinuations(graph,partial,options,direction,state)){const nodes=[...partial.nodes,row.id],nodeSet=new Set(partial.nodeSet).add(row.id),edges=[...partial.edges,row.edge];if(row.id===target){if(state.value.push({nodes,edges,length:edges.length}),state.value.length>=probeLimit)return!0}else state.queue.push({nodes,nodeSet,edges})}return!1}function hierarchyAncestors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"hierarchy",(row,definition)=>hierarchyParentEndpoint(row.edge,definition)===row.id)}function hierarchyDescendants(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"hierarchy",(row,definition,nodeId)=>hierarchyParentEndpoint(row.edge,definition)===nodeId)}function orderingPredecessors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"ordering",(row,definition)=>orderingPredecessorEndpoint(row.edge,definition)===row.id)}function orderingSuccessors(graph,id,options={}){return boundedSemanticWalk(graph,id,options,"ordering",(row,definition,nodeId)=>orderingPredecessorEndpoint(row.edge,definition)===nodeId)}function enumerateNonZeroRelationshipPaths(graph,source,target,options,maxPaths,maxVisitedPaths,maxDepth,direction){const state={value:[],queue:[{nodes:[source],nodeSet:new Set([source]),edges:[]}],inspectedEdges:0};let visitedNodes=0,truncated=!1;const probeLimit=maxPaths+1;for(let index=0;index<state.queue.length;index+=1){if(options.signal?.throwIfAborted(),state.value.length>=probeLimit||visitedNodes>=maxVisitedPaths){truncated=!0;break}const partial=state.queue[index];if(visitedNodes+=1,partial.edges.length>=maxDepth){readPathContinuations(graph,partial,options,direction,state).length>0&&(truncated=!0);continue}if(expandPartialPath(graph,partial,target,options,direction,probeLimit,state)){truncated=!0;break}}return{value:state.value.slice(0,maxPaths),meta:{visitedNodes,inspectedEdges:state.inspectedEdges,truncated}}}function enumerateRelationshipPaths(graph,source,target,options={}){assertPathEndpoint(graph,source),assertPathEndpoint(graph,target);const maxPaths=options.maxPaths??DEFAULT_MAX_PATHS,maxVisitedPaths=options.maxVisitedPaths??DEFAULT_MAX_VISITED_PATHS,maxDepth=options.maxDepth??DEFAULT_PATH_MAX_DEPTH;assertPathBound("maxPaths",maxPaths),assertPathBound("maxVisitedPaths",maxVisitedPaths),assertPathBound("maxDepth",maxDepth);const direction=options.direction??"outgoing";options.signal?.throwIfAborted();for(const kind of options.kinds??[])graph.registry().require(kind);return source===target?maxPaths===0?{value:[],meta:{visitedNodes:1,inspectedEdges:0,truncated:!0}}:{value:[{nodes:[source],edges:[],length:0}],meta:{visitedNodes:1,inspectedEdges:0,truncated:!1}}:enumerateNonZeroRelationshipPaths(graph,source,target,options,maxPaths,maxVisitedPaths,maxDepth,direction)}export{enumerateRelationshipPaths,hierarchyAncestors,hierarchyDescendants,hierarchyParentEndpoint,orderingPredecessorEndpoint,orderingPredecessors,orderingSuccessors,orientOrderingEdge};
2
2
  //# sourceMappingURL=traversal.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0a3dd0c1-2dea-5143-a2eb-65e758a0cc71")}catch(e2){}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{createRelationshipKindRegistry}from"../relationships.js";function resolveWorkspaceRelationshipKindRegistry(){const registry=createRelationshipKindRegistry();for(const registration of getActiveExtensionRegistrations()?.relationship_kinds??[]){for(const definition of registration.definitions){registry.register(definition)}}return registry}export{resolveWorkspaceRelationshipKindRegistry};
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]="283dfa35-9a8e-524c-b6e2-d433d51215ca")}catch{}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{createRelationshipKindRegistry}from"../relationships.js";function resolveWorkspaceRelationshipKindRegistry(){const registry=createRelationshipKindRegistry();for(const registration of getActiveExtensionRegistrations()?.relationship_kinds??[])for(const definition of registration.definitions)registry.register(definition);return registry}export{resolveWorkspaceRelationshipKindRegistry};
2
2
  //# sourceMappingURL=workspace-relationship-kind-registry.js.map
package/dist/sdk/graph.js CHANGED
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3160880c-9d85-52c5-ae1d-ada213f56ce6")}catch(e2){}})();export*from"./graph/index.js";export*from"./actionability.js";export*from"./relationships.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";
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]="3160880c-9d85-52c5-ae1d-ada213f56ce6")}catch{}})();export*from"./graph/index.js";export*from"./actionability.js";export*from"./relationships.js";export*from"./relationship-analytics.js";export*from"./relationship-context.js";export*from"./relationship-history.js";export*from"./relationship-migration.js";
2
2
  //# sourceMappingURL=graph.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="5b106ed0-ef19-58a4-a7d0-bd0988482f58")}catch(e2){}})();import{listPmCommandCapabilityGroups}from"./agent-capability-contracts.js";function normalizeTopicToken(value){return value.trim().toLowerCase().replaceAll("_","-")}const GUIDE_TOPICS=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:listPmCommandCapabilityGroups().flatMap(({commands})=>commands.map(command=>`pm ${command}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}];const TOPIC_BY_TOKEN=new Map;for(const topic of GUIDE_TOPICS){TOPIC_BY_TOKEN.set(topic.id,topic);for(const alias of topic.aliases){TOPIC_BY_TOKEN.set(alias,topic)}}function listGuideTopics(){return GUIDE_TOPICS.map(topic=>({...topic,aliases:[...topic.aliases],commands:[...topic.commands],workflows:topic.workflows.map(workflow=>({...workflow,commands:[...workflow.commands]})),docs:topic.docs.map(doc=>({...doc})),related:[...topic.related]}))}function listGuideTopicIds(){return GUIDE_TOPICS.map(topic=>topic.id)}function resolveGuideTopic(rawTopic){if(!rawTopic){return null}const normalized=normalizeTopicToken(rawTopic);if(!normalized){return null}return TOPIC_BY_TOKEN.get(normalized)??null}export{listGuideTopicIds,listGuideTopics,resolveGuideTopic};
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]="f5ba86ac-336e-5fdb-a8fb-d8d7e7c1a504")}catch{}})();import{listPmCommandCapabilityGroups}from"./agent-capability-contracts.js";function normalizeTopicToken(value){return value.trim().toLowerCase().replaceAll("_","-")}const GUIDE_TOPICS=[{id:"capabilities",aliases:["capability-map","families","routing"],title:"Generated Capability Routing",summary:"Route work through command families generated from the canonical agent capability contract.",intent:"Use this as the drift-free entrypoint when selecting a CLI, MCP, completion, documentation, or extension command surface.",commands:listPmCommandCapabilityGroups().flatMap(({commands})=>commands.map(command=>`pm ${command}`)),workflows:[],docs:[{path:"docs/generated/AGENT_CAPABILITY_ROUTING.md",purpose:"Generated command-to-family routing table."},{path:"docs/generated/AGENT_COMMAND_SURFACE.md",purpose:"Generated visibility-tier and family table."}],related:["commands","workflows","extensions"]},{id:"quickstart",aliases:["start","getting-started","bootstrap"],title:"Quickstart",summary:"Initialize a tracker and run the shortest safe plan -> execute -> close loop.",intent:"Use this when a human or agent needs to start productive work quickly with minimal context load.",commands:["pm workspace init","pm workspace config --help","pm workspace schema --help","pm workspace profile --help","pm context --limit 10","pm list --status open --limit 20",'pm create --create-mode progressive --title "..." --description "..." --type Task',"pm claim <ID>","pm update <ID> --status in_progress",'pm close <ID> "<reason with evidence>" --validate-close warn'],workflows:[{name:"Start Session Safely",goal:"Bootstrap without mutating unrelated state.",prompt:"You are bootstrapping pm work. Use a token-efficient context snapshot first, then select one open item, claim it, and only then mutate.",commands:["pm context --limit 10","pm list --status open --limit 20","pm claim <ID>"]}],docs:[{path:"README.md",purpose:"High-level project and install entrypoint."},{path:"docs/QUICKSTART.md",purpose:"Short setup and first-command walkthrough."},{path:"docs/COMMANDS.md",purpose:"Task-oriented command recipes."}],related:["commands","workflows","release"]},{id:"commands",aliases:["cli","operations","reference"],title:"CLI Command Routing",summary:"Find the right command family quickly and use command-scoped help/contracts output.",intent:"Use this when selecting command paths, flags, and output formats for implementation or automation.",commands:["pm --help","pm <command> --help","pm <command> --help --explain","pm contracts --command <command> --flags-only","pm contracts --command <command> --availability-only --runtime-only","pm completion <bash|zsh|fish>"],workflows:[{name:"Flag Discovery",goal:"Resolve command flags deterministically before mutations.",prompt:"You are preparing to run a command. Use help and contracts surfaces to verify required/optional flags before execution.",commands:["pm <command> --help --explain","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Command grouping and examples."},{path:"docs/CONFIGURATION.md",purpose:"Project/global settings and policy controls."},{path:"docs/TESTING.md",purpose:"Linked-test orchestration and safety guidance."}],related:["quickstart","workflows","sdk","extensions"]},{id:"workflows",aliases:["developer","maintainer","agent"],title:"Developer and Agent Workflows",summary:"Apply canonical claim -> execute -> verify -> close workflows with append-only evidence.",intent:"Use this for day-to-day coding-agent execution loops and handoff-safe updates.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add ...","pm test <ID> --add ...",'pm comments <ID> "..."',"pm validate --check-resolution --check-history-drift","pm release <ID>"],workflows:[{name:"Execution Loop",goal:"Keep code, tests, and tracker evidence synchronized.",prompt:"You are implementing a scoped change. Claim first, link files/tests/docs as you go, append evidence comments, and close only after validation.",commands:["pm claim <ID>","pm update <ID> --status in_progress","pm files <ID> --add path=<file>,scope=project","pm test <ID> --run --progress",'pm close <ID> "<evidence>" --validate-close warn']}],docs:[{path:"AGENTS.md",purpose:"Repository operating rules and required workflow."},{path:"docs/AGENT_GUIDE.md",purpose:"Agent-oriented usage and context strategy."},{path:"docs/TESTING.md",purpose:"Sandbox-safe test execution rules."}],related:["quickstart","commands","skills"]},{id:"sdk",aliases:["api","typescript-sdk"],title:"SDK and Integrations",summary:"Use the published SDK surface for extension authoring and contract-safe integrations.",intent:"Use this when building or reviewing programmatic integrations against @unbrained/pm-cli/sdk.",commands:["pm contracts --schema-only","pm contracts --command extension --flags-only","pm contracts --runtime-only --availability-only"],workflows:[{name:"Integration Contract Check",goal:"Confirm action schemas and runtime availability before coding.",prompt:"You are wiring an integration. Capture schema + runtime availability first, then map your adapter payload fields to contract keys.",commands:["pm contracts --schema-only","pm contracts --availability-only --runtime-only","pm contracts --command <command> --flags-only"]}],docs:[{path:"docs/SDK.md",purpose:"Public SDK exports and extension authoring references."},{path:"docs/ARCHITECTURE.md",purpose:"Core runtime composition and extension load flow."}],related:["extensions","commands"]},{id:"extensions",aliases:["plugins","extension-authoring","packages","package-authoring"],title:"Packages and Extensions",summary:"Install, author, and diagnose packages/extensions with deterministic lifecycle controls.",intent:"Use this for package management, extension capability registration, and runtime diagnostics.",commands:["pm package install <target> --project","pm package upgrade --dry-run","pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package activate <target> --project","pm package deactivate <target> --project"],workflows:[{name:"Lifecycle Triage",goal:"Diagnose extension state before forceful lifecycle actions.",prompt:"You are debugging package behavior. Inspect managed state first, then run doctor diagnostics, then apply install/adopt/activate actions.",commands:["pm package explore --project","pm package manage --detail summary","pm package doctor --detail deep","pm package upgrade --packages-only --dry-run"]}],docs:[{path:"docs/EXTENSIONS.md",purpose:"Capability model and lifecycle command usage."},{path:"docs/examples/starter-extension/README.md",purpose:"Starter extension scaffold and local development path."},{path:"docs/SDK.md",purpose:"SDK contracts used by extension implementations."}],related:["sdk","commands","skills"]},{id:"skills",aliases:["agent-skills","agentskills"],title:"Agent Skills",summary:"Skill bundles for developer, user, extensions, and sdk workflows aligned to the current CLI.",intent:"Use this when an agent needs reproducible prompts/workflows with strict compatibility metadata.",commands:["pm guide skills --depth deep","pm contracts --command guide --flags-only","pm validate --check-command-references"],workflows:[{name:"Skill Selection",goal:"Pick the narrowest compatible skill first to minimize context usage.",prompt:"Select a pm skill based on the task intent, then execute only the workflow section needed for the current change.",commands:["pm guide skills","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent-first usage and context model."},{path:"docs/README.md",purpose:"Documentation routing with progressive disclosure."},{path:".agents/skills/README.md",purpose:"Agent skills index and routing overview."},{path:".agents/skills/pm-developer/SKILL.md",purpose:"Developer-oriented pm skill workflow."},{path:".agents/skills/pm-user/SKILL.md",purpose:"User/operator pm skill workflow."},{path:".agents/skills/pm-extensions/SKILL.md",purpose:"Extension-focused pm skill workflow."},{path:".agents/skills/pm-sdk/SKILL.md",purpose:"SDK integration pm skill workflow."}],related:["workflows","harnesses","commands"]},{id:"harnesses",aliases:["compatibility","agent-compatibility"],title:"Agent Harness Compatibility",summary:"Cross-harness compatibility guidance for docs routing.",intent:"Use this when adapting pm docs and SDK contracts for an external automation harness.",commands:["pm guide skills","pm guide commands","pm contracts --runtime-only --availability-only"],workflows:[{name:"Harness Mapping",goal:"Route each harness to the same canonical skill/docs sources.",prompt:"Map harness-specific entrypoints to the same pm guide topics and .agents/skills workflows without adding runtime harness-specific code.",commands:["pm guide harnesses --depth standard","pm guide skills --depth deep"]}],docs:[{path:"docs/AGENT_GUIDE.md",purpose:"Agent context and output-mode conventions."},{path:"docs/README.md",purpose:"Single-source documentation routing entrypoint."},{path:".agents/skills/HARNESS_COMPATIBILITY.md",purpose:"Harness compatibility matrix and usage notes."}],related:["skills","workflows"]},{id:"release",aliases:["gates","ship","release-readiness"],title:"Release and Staleness Gates",summary:"Run release gates and docs/skills freshness checks before publishing.",intent:"Use this when validating release readiness and preventing docs/skills drift.",commands:["pnpm build","pnpm test:coverage","pnpm quality:static","node scripts/release/run-gates.mjs --telemetry-mode best-effort","pnpm security:scan"],workflows:[{name:"Pre-Release Gate Sweep",goal:"Ensure code, docs, and skills are all green before publish.",prompt:"Run release gates in deterministic order and treat docs/skills freshness failures as release blockers.",commands:["pnpm build","pnpm test:coverage","node scripts/release/run-gates.mjs --telemetry-mode best-effort"]}],docs:[{path:"docs/RELEASING.md",purpose:"Release flow and safety checks."},{path:"CHANGELOG.md",purpose:"Versioned release history and unreleased notes."},{path:"scripts/release/run-gates.mjs",purpose:"Source of truth for release gate ordering."}],related:["commands","skills","workflows"]},{id:"tokens",aliases:["output","budget","context-cost","projections"],title:"Read Output and Token Budgets",summary:"Bound what a read costs before it is emitted, and resume the part a budget withheld.",intent:"Use this when an agent must keep context small: every read declares a token ceiling, degrades deterministically, and reports what it omitted.",commands:["pm contracts --summary --json","pm list --status open --output-limit 20","pm get <ID> --output-include id,title,status,dependencies","pm context --limit 10 --token-accounting","pm notes <ID> --output-cursor <cursor>","pm list --status closed --output-budget unbounded"],workflows:[{name:"Bound A Read Before Emitting It",goal:"Never pay for rows the task does not need.",prompt:"Choose the narrowest projection first, then a row limit, then a token budget. Read the omission receipt before concluding the result is complete.",commands:["pm contracts --command list --flags-only --json","pm list --status open --output-limit 20 --output-format toon","pm list --status open --token-accounting"]},{name:"Recover A Truncated Read",goal:"Continue a bounded read instead of re-running it unbounded.",prompt:"When output_budget_truncation appears, prefer the declared continuation cursor. Only widen the budget when the response declares no cursor.",commands:["pm notes <ID> --output-cursor <cursor>","pm get <ID> --output-budget 20000"]}],docs:[{path:"docs/READ_OUTPUT_CONTRACTS.md",purpose:"Budget, truncation, continuation, and omission receipts."},{path:"docs/OUTPUT_PROJECTION_CONTRACTS.md",purpose:"Field and section projection grammar for every read."},{path:"docs/OUTPUT_TOKEN_ACCOUNTING.md",purpose:"Per-section token cost receipts."},{path:"docs/ITEM_READ_PROJECTIONS.md",purpose:"Item-level projection defaults and restore hints."}],related:["commands","workflows","quickstart"]},{id:"graph",aliases:["relationships","deps","dependencies","analytics"],title:"Relationship Graph and Planning Analytics",summary:"Type the relationships between items, then read the project as a graph rather than as a list.",intent:"Use this when the question is about lineage, ordering, blast radius, bottlenecks, or which work reaches a declared outcome.",commands:["pm deps <ID>",'pm update <ID> --dep "id=<other>,kind=implements"',"pm graph analyze","pm graph impact <ID> --direction downstream","pm graph paths <ID> <ID>","pm graph audit"],workflows:[{name:"Place New Work In The Ladder",goal:"Every item resolves to an outcome through a typed, explainable path.",prompt:"Set parent lineage first, then add typed edges that cite durable evidence. Never add an edge to satisfy a count.",commands:['pm search "<topic>" --limit 10','pm update <ID> --dep "id=<parent-goal>,kind=implements"',"pm graph ancestors <ID>"]},{name:"Assess Blast Radius Before Changing Something",goal:"Know what derives from an item before touching it.",prompt:"Walk the directed graph downstream from the item, then check whether any bottleneck node sits on the path.",commands:["pm graph impact <ID> --direction downstream","pm graph dominators <ID>","pm graph articulation"]}],docs:[{path:"docs/RELATIONSHIP_GRAPH.md",purpose:"Graph model, traversal verbs, and analytics surface."},{path:"docs/DEPENDENCY_KIND_CONTRACT.md",purpose:"Every typed edge kind, its direction, and its semantics."}],related:["commands","workflows","assurance"]},{id:"assurance",aliases:["gates","invariants","measurements","quality"],title:"Declared Invariants and Gates",summary:"Express a project's own quality rules as tracked data the SDK evaluates, instead of as scripts.",intent:"Use this when a rule must hold over the record itself \u2014 a floor, a ceiling, or a monotone property \u2014 and must fail closed in CI.",commands:["pm assurance list","pm assurance run <gate-id> --trigger ci --dry-run","pm validate --check-resolution --check-history-drift","pm health --summary"],workflows:[{name:"Add An Invariant Rather Than A Script",goal:"A new enforcement gap becomes declared data, not a new bespoke gate script.",prompt:"Define the measurement, bind an assertion with an explicit bound and polarity, prove a negative control, then attach it to a trigger.",commands:["pm assurance list --json","pm assurance run <gate-id> --trigger ci --dry-run --json"]},{name:"Read A Verdict Before Believing It",goal:"Know which population a passing assertion speaks for.",prompt:"Read population_size and scope on every assertion. A gate that cannot fail for the reason it exists is not evidence.",commands:["pm assurance run <gate-id> --trigger ci --dry-run --json --output-budget unbounded"]}],docs:[{path:"docs/ASSURANCE.md",purpose:"Measurement, assertion, gate, and trigger vocabulary."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"What every mutation must record to remain provable."}],related:["release","graph","workflows"]},{id:"merge",aliases:["branches","concurrency","multi-agent","fleet"],title:"Branching, Merging, and Concurrent Agents",summary:"Keep tracker data and history conflict-free while many agents work on separate branches.",intent:"Use this when more than one agent or worktree mutates the same tracker and the results must merge without hand resolution.",commands:["pm merge install","pm merge report","pm merge reconcile --dry-run","pm claim <ID>","pm release <ID>","pm validate --check-history-drift","pm health --check-only"],workflows:[{name:"Prepare A Clone For Field-Aware Merges",goal:"The committed merge fence needs clone-local driver configuration once.",prompt:"Run the merge installer in every fresh clone or worktree before the first branch merge of tracker data.",commands:["pm merge install","pm health --check-only"]},{name:"Settle A Merge Before Trusting Health",goal:"A lossless merge still leaves pending receipts that strict health reports until they are reconciled.",prompt:"After any branch merge that touched tracker data, read the merge report, preview the reconciliation, then apply it; only then treat a health verdict as a statement about the data.",commands:["pm merge report","pm merge reconcile --dry-run",'pm merge reconcile --message "Post-merge history reconciliation"',"pm health --check-only"]},{name:"Hand Work Between Agents Safely",goal:"Ownership and evidence survive the handoff.",prompt:"Claim before substantial edits, record evidence as comments, and release the claim when pausing, handing off, closing, or canceling.",commands:["pm claim <ID>",'pm comments <ID> "Handoff: <state and next step>"',"pm release <ID>"]}],docs:[{path:"docs/MERGE_SAFETY.md",purpose:"Merge driver, field-aware resolution, and clone setup."},{path:"docs/SDK_CONTEXT_COORDINATION.md",purpose:"Coordination primitives for concurrent agents."}],related:["workflows","assurance","commands"]},{id:"evidence",aliases:["record","annotations","learnings","history-maintenance"],title:"Evidence, Durable Knowledge, and Record Maintenance",summary:"Append comments, notes, learnings, files, docs, and tests to items, and maintain the immutable history those records live in.",intent:"Use this when work must be explained to the next agent, when a durable lesson should outlive the item, or when a history stream needs verification, repair, redaction, compaction, or author attribution.",commands:['pm comments <ID> "<progress or verification evidence>"','pm notes <ID> --add "<rationale that belongs on the item>"','pm learnings <ID> --add "<lesson that should outlive the item>"',"pm append <ID> --body -","pm files <ID> --add path=<path>,scope=project,note=<why>","pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run","pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run","pm close-many --ids <ID>,<ID> --reason <text> --dry-run","pm test-all --status open --limit 10 --progress"],workflows:[{name:"Record While Working, Not After",goal:"Another agent can rebuild the full situation from the item alone.",prompt:"Add a comment for each verified step, a note for each rationale the item body does not carry, and a learning for each lesson that applies beyond this item. Prefer appending over rewriting.",commands:['pm comments <ID> "Evidence: <what changed and what passed>"','pm notes <ID> --add "Decision log: <why this shape>"','pm learnings <ID> --add "<durable lesson>"',"pm learnings <ID> --limit 5"]},{name:"Verify And Repair A History Stream",goal:"Every mutation stays provable and the chain re-anchors after drift.",prompt:"Verify the chain with a strict exit before trusting a stream, preview any repair, and record why the repair was needed in the audit message.",commands:["pm history <ID> --verify --strict-exit","pm history-repair --all --dry-run",'pm history-repair --all --message "<why the chain drifted>"',"pm validate --check-history-drift"]},{name:"Redact, Compact, Or Attribute Without Losing Proof",goal:"Sensitive text, stream length, and unknown authors are handled through audited rewrites.",prompt:"Preview every history rewrite with --dry-run, read the receipt, then apply. Compaction renumbers ordinal versions, so record the checkpoint it created.",commands:["pm history-redact <ID> --literal <secret> --dry-run","pm history-compact <ID> --dry-run","pm history-author-acknowledge --all-actionable --dry-run"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Annotation, bulk, and history-and-recovery command families."},{path:"docs/MUTATION_INTEGRITY.md",purpose:"Provenance and content-safety policy every mutation shares."},{path:"docs/AGENT_GUIDE.md",purpose:"Evidence expectations in the agent loop and self-repair remediation."}],related:["workflows","assurance","merge","graph"]},{id:"automation",aliases:["calendar","reminders","meetings","events"],title:"Reminders, Events, and Meetings",summary:"Attach time to items so context and agenda views can surface deadlines, meetings, and reminders when they matter.",intent:"Use this when an item needs a due signal, a scheduled event, or a meeting record that later context reads should surface.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm calendar event <title> --start <when> --parent <ID>","pm calendar meet <title> --start <when> --duration 30min --parent <ID>","pm context --limit 10"],workflows:[{name:"Put A Deadline Where Context Will Find It",goal:"Time-bound work surfaces in the agenda section of context reads.",prompt:"Install calendar, then record the reminder or event under its owning item and confirm it in context. Use explicit min or mo for durations; bare m is ambiguous.",commands:["pm package install calendar --project","pm calendar remind <title> --at <when> --parent <ID>","pm context --limit 10"]}],docs:[{path:"docs/COMMANDS.md",purpose:"Calendar and context command family."},{path:"packages/pm-calendar/README.md",purpose:"Package commands, duration units, and compatibility aliases."}],related:["workflows","quickstart","extensions"]}],TOPIC_BY_TOKEN=new Map;for(const topic of GUIDE_TOPICS){TOPIC_BY_TOKEN.set(topic.id,topic);for(const alias of topic.aliases)TOPIC_BY_TOKEN.set(alias,topic)}function listGuideTopics(){return GUIDE_TOPICS.map(topic=>({...topic,aliases:[...topic.aliases],commands:[...topic.commands],workflows:topic.workflows.map(workflow=>({...workflow,commands:[...workflow.commands]})),docs:topic.docs.map(doc=>({...doc})),related:[...topic.related]}))}function listGuideTopicIds(){return GUIDE_TOPICS.map(topic=>topic.id)}function resolveGuideTopic(rawTopic){if(!rawTopic)return null;const normalized=normalizeTopicToken(rawTopic);return normalized?TOPIC_BY_TOKEN.get(normalized)??null:null}export{listGuideTopicIds,listGuideTopics,resolveGuideTopic};
2
2
  //# sourceMappingURL=guide-topics.js.map
package/dist/sdk/guide.js CHANGED
@@ -1,2 +1,9 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3a7cf539-2663-5265-90e8-c2aa9926a62a")}catch(e2){}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import{readFile}from"node:fs/promises";import path from"node:path";import{resolveConfiguredPmPackageRoot,EXIT_CODE,PmCliError}from"./runtime-primitives.js";import{listGuideTopicIds,listGuideTopics,resolveGuideTopic}from"./guide-topics.js";const GUIDE_OUTPUT_VALUES=["markdown","toon","json"];const GUIDE_DEPTH_VALUES=["brief","standard","deep"];function parseGuideOutputFormat(raw){if(!raw){return void 0}const normalized=raw.trim().toLowerCase();if(!GUIDE_OUTPUT_VALUES.includes(normalized)){throw new PmCliError("Guide format must be one of markdown|toon|json",EXIT_CODE.USAGE)}return normalized}function resolveGuideOutputFormat(options,global2){const commandFormat=parseGuideOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json"){throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE)}if(global2.json){return"json"}return commandFormat??"toon"}function parseGuideDepth(raw){if(!raw){return"brief"}const normalized=raw.trim().toLowerCase();if(!GUIDE_DEPTH_VALUES.includes(normalized)){throw new PmCliError("Guide depth must be one of brief|standard|deep",EXIT_CODE.USAGE)}return normalized}function resolvePackageRoot(){return resolveConfiguredPmPackageRoot(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function normalizeLineEndings(value){return value.replaceAll("\r\n","\n")}function toExcerpt(content,maxLines,maxCharacters){const normalized=normalizeLineEndings(content);const lines=normalized.split("\n");const lineSlice=lines.slice(0,maxLines);let excerpt=lineSlice.join("\n");let truncated=lines.length>maxLines;if(excerpt.length>maxCharacters){excerpt=excerpt.slice(0,maxCharacters);truncated=true}return{excerpt:excerpt.trimEnd(),truncated,lineCount:lines.length}}async function renderGuideDocs(topic,depth,packageRoot){const includeContent=depth!=="brief";const contentMode=includeContent?depth==="deep"?"full":"excerpt":"none";const docs=[];for(const doc of topic.docs){const absolutePath=path.resolve(packageRoot,doc.path);if(!includeContent){docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===true,exists:true,line_count:null,content_mode:"none",content:null,truncated:false});continue}try{const rawContent=await readFile(absolutePath,"utf8");if(depth==="deep"){const normalized=normalizeLineEndings(rawContent).trimEnd();docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===true,exists:true,line_count:normalized.length===0?0:normalized.split("\n").length,content_mode:"full",content:normalized,truncated:false})}else{const excerpt=toExcerpt(rawContent,120,12e3);docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===true,exists:true,line_count:excerpt.lineCount,content_mode:contentMode,content:excerpt.excerpt,truncated:excerpt.truncated})}}catch(error){const missing=isFileAbsentError(error);docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===true,exists:false,line_count:null,content_mode:"none",content:null,truncated:false});if(!missing){throw new PmCliError(`Failed to read guide document "${doc.path}".`,EXIT_CODE.GENERIC_FAILURE)}}}return docs}function buildGuideIndex(depth){const topics=listGuideTopics().map(topic=>({id:topic.id,aliases:topic.aliases,title:topic.title,summary:topic.summary,intent:topic.intent,quick_commands:depth==="brief"?topic.commands.slice(0,3):topic.commands.slice(0,6),docs:topic.docs.map(doc=>({path:doc.path,purpose:doc.purpose})),related:topic.related}));return{output_default:"toon",mode:"index",depth,topics,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function ensureGuideTopic(topic){const resolved=resolveGuideTopic(topic);if(resolved){return resolved}const available=listGuideTopicIds().join(", ");throw new PmCliError(`Unknown guide topic "${topic}". Available topics: ${available}. Use "pm guide --list" to browse.`,EXIT_CODE.USAGE)}async function runGuide(options,global2){const depth=parseGuideDepth(typeof options.depth==="string"?options.depth:void 0);const listRequested=options.list===true;const topicRaw=typeof options.topic==="string"?options.topic:void 0;if(listRequested||!topicRaw){return buildGuideIndex(depth)}const topic=ensureGuideTopic(topicRaw);const packageRoot=resolvePackageRoot();const docs=await renderGuideDocs(topic,depth,packageRoot);const warnings=docs.filter(doc=>!doc.exists&&!doc.optional).map(doc=>`Missing required guide document: ${doc.path}`);return{output_default:"toon",mode:"topic",depth,requested_topic:topicRaw,topic,docs,warnings}}const _testOnlyGuide={ensureGuideTopic};function markdownCodeFence(content){return content.replaceAll("```","``\\`")}function renderGuideMarkdown(result){if(result.mode==="index"){const lines2=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(const topic of result.topics){lines2.push(`- \`${topic.id}\` - ${topic.summary}`);if(result.depth!=="brief"){lines2.push(` - intent: ${topic.intent}`);lines2.push(` - docs: ${topic.docs.map(doc=>`\`${doc.path}\``).join(", ")}`)}}lines2.push("","## Next steps");for(const step of result.suggested_next_steps){lines2.push(`- \`${step}\``)}return lines2.join("\n")}const lines=[`# pm guide ${result.topic.id}`,"",result.topic.summary,"","## Intent",result.topic.intent,"","## Key commands",...result.topic.commands.map(command=>`- \`${command}\``),"","## Workflow prompts"];for(const workflow of result.topic.workflows){lines.push(`### ${workflow.name}`);lines.push(`goal: ${workflow.goal}`);lines.push(`prompt: ${workflow.prompt}`);lines.push("commands:");lines.push(...workflow.commands.map(command=>`- \`${command}\``));lines.push("")}lines.push("## Documents");for(const doc of result.docs){const status=doc.exists?"available":doc.optional?"missing (optional)":"missing (required)";lines.push(`- \`${doc.path}\` - ${doc.purpose} (${status})`);if(doc.exists&&doc.content_mode!=="none"&&doc.content){lines.push("");lines.push(`### Excerpt: \`${doc.path}\``);if(doc.truncated){lines.push("_truncated for context efficiency_")}lines.push("```markdown");lines.push(markdownCodeFence(doc.content));lines.push("```")}}if(result.topic.related.length>0){lines.push("","## Related topics");lines.push(...result.topic.related.map(topic=>`- \`${topic}\``))}if(result.warnings.length>0){lines.push("","## Warnings");lines.push(...result.warnings.map(warning=>`- ${warning}`))}return lines.join("\n")}export{GUIDE_DEPTH_VALUES,GUIDE_OUTPUT_VALUES,_testOnlyGuide,renderGuideMarkdown,resolveGuideOutputFormat,runGuide};
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]="b11b0e04-bad1-5090-8df9-d922568db013")}catch{}})();import{isFileAbsentError}from"../core/fs/fs-utils.js";import{readFile}from"node:fs/promises";import path from"node:path";import{resolveConfiguredPmPackageRoot,EXIT_CODE,PmCliError}from"./runtime-primitives.js";import{listGuideTopicIds,listGuideTopics,resolveGuideTopic}from"./guide-topics.js";const GUIDE_OUTPUT_VALUES=["markdown","toon","json"],GUIDE_DEPTH_VALUES=["brief","standard","deep"];function parseGuideOutputFormat(raw){if(!raw)return;const normalized=raw.trim().toLowerCase();if(!GUIDE_OUTPUT_VALUES.includes(normalized))throw new PmCliError("Guide format must be one of markdown|toon|json",EXIT_CODE.USAGE);return normalized}function resolveGuideOutputFormat(options,global2){const commandFormat=parseGuideOutputFormat(options.format);if(global2.json&&commandFormat&&commandFormat!=="json")throw new PmCliError("Cannot combine --json with --format markdown|toon",EXIT_CODE.USAGE);return global2.json?"json":commandFormat??"toon"}function parseGuideDepth(raw){if(!raw)return"brief";const normalized=raw.trim().toLowerCase();if(!GUIDE_DEPTH_VALUES.includes(normalized))throw new PmCliError("Guide depth must be one of brief|standard|deep",EXIT_CODE.USAGE);return normalized}function resolvePackageRoot(){return resolveConfiguredPmPackageRoot(process.env,"PM_CLI_PACKAGE_ROOT",import.meta.url,["..","..",".."])}function normalizeLineEndings(value){return value.replaceAll(`\r
2
+ `,`
3
+ `)}function toExcerpt(content,maxLines,maxCharacters){const lines=normalizeLineEndings(content).split(`
4
+ `);let excerpt=lines.slice(0,maxLines).join(`
5
+ `),truncated=lines.length>maxLines;return excerpt.length>maxCharacters&&(excerpt=excerpt.slice(0,maxCharacters),truncated=!0),{excerpt:excerpt.trimEnd(),truncated,lineCount:lines.length}}async function renderGuideDocs(topic,depth,packageRoot){const includeContent=depth!=="brief",contentMode=includeContent?depth==="deep"?"full":"excerpt":"none",docs=[];for(const doc of topic.docs){const absolutePath=path.resolve(packageRoot,doc.path);if(!includeContent){docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===!0,exists:!0,line_count:null,content_mode:"none",content:null,truncated:!1});continue}try{const rawContent=await readFile(absolutePath,"utf8");if(depth==="deep"){const normalized=normalizeLineEndings(rawContent).trimEnd();docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===!0,exists:!0,line_count:normalized.length===0?0:normalized.split(`
6
+ `).length,content_mode:"full",content:normalized,truncated:!1})}else{const excerpt=toExcerpt(rawContent,120,12e3);docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===!0,exists:!0,line_count:excerpt.lineCount,content_mode:contentMode,content:excerpt.excerpt,truncated:excerpt.truncated})}}catch(error){const missing=isFileAbsentError(error);if(docs.push({path:doc.path,purpose:doc.purpose,optional:doc.optional===!0,exists:!1,line_count:null,content_mode:"none",content:null,truncated:!1}),!missing)throw new PmCliError(`Failed to read guide document "${doc.path}".`,EXIT_CODE.GENERIC_FAILURE)}}return docs}function buildGuideIndex(depth){const topics=listGuideTopics().map(topic=>({id:topic.id,aliases:topic.aliases,title:topic.title,summary:topic.summary,intent:topic.intent,quick_commands:depth==="brief"?topic.commands.slice(0,3):topic.commands.slice(0,6),docs:topic.docs.map(doc=>({path:doc.path,purpose:doc.purpose})),related:topic.related}));return{output_default:"toon",mode:"index",depth,topics,suggested_next_steps:["pm guide <topic>","pm guide <topic> --depth standard","pm guide <topic> --depth deep --format markdown","pm guide <topic> --json"]}}function ensureGuideTopic(topic){const resolved=resolveGuideTopic(topic);if(resolved)return resolved;const available=listGuideTopicIds().join(", ");throw new PmCliError(`Unknown guide topic "${topic}". Available topics: ${available}. Use "pm guide --list" to browse.`,EXIT_CODE.USAGE)}async function runGuide(options,global2){const depth=parseGuideDepth(typeof options.depth=="string"?options.depth:void 0),listRequested=options.list===!0,topicRaw=typeof options.topic=="string"?options.topic:void 0;if(listRequested||!topicRaw)return buildGuideIndex(depth);const topic=ensureGuideTopic(topicRaw),packageRoot=resolvePackageRoot(),docs=await renderGuideDocs(topic,depth,packageRoot),warnings=docs.filter(doc=>!doc.exists&&!doc.optional).map(doc=>`Missing required guide document: ${doc.path}`);return{output_default:"toon",mode:"topic",depth,requested_topic:topicRaw,topic,docs,warnings}}const _testOnlyGuide={ensureGuideTopic};function markdownCodeFence(content){return content.replaceAll("```","``\\`")}function renderGuideMarkdown(result){if(result.mode==="index"){const lines2=["# pm guide","","Token-efficient local documentation index for agent and maintainer workflows.","","## Topics"];for(const topic of result.topics)lines2.push(`- \`${topic.id}\` - ${topic.summary}`),result.depth!=="brief"&&(lines2.push(` - intent: ${topic.intent}`),lines2.push(` - docs: ${topic.docs.map(doc=>`\`${doc.path}\``).join(", ")}`));lines2.push("","## Next steps");for(const step of result.suggested_next_steps)lines2.push(`- \`${step}\``);return lines2.join(`
7
+ `)}const lines=[`# pm guide ${result.topic.id}`,"",result.topic.summary,"","## Intent",result.topic.intent,"","## Key commands",...result.topic.commands.map(command=>`- \`${command}\``),"","## Workflow prompts"];for(const workflow of result.topic.workflows)lines.push(`### ${workflow.name}`),lines.push(`goal: ${workflow.goal}`),lines.push(`prompt: ${workflow.prompt}`),lines.push("commands:"),lines.push(...workflow.commands.map(command=>`- \`${command}\``)),lines.push("");lines.push("## Documents");for(const doc of result.docs){const status=doc.exists?"available":doc.optional?"missing (optional)":"missing (required)";lines.push(`- \`${doc.path}\` - ${doc.purpose} (${status})`),doc.exists&&doc.content_mode!=="none"&&doc.content&&(lines.push(""),lines.push(`### Excerpt: \`${doc.path}\``),doc.truncated&&lines.push("_truncated for context efficiency_"),lines.push("```markdown"),lines.push(markdownCodeFence(doc.content)),lines.push("```"))}return result.topic.related.length>0&&(lines.push("","## Related topics"),lines.push(...result.topic.related.map(topic=>`- \`${topic}\``))),result.warnings.length>0&&(lines.push("","## Warnings"),lines.push(...result.warnings.map(warning=>`- ${warning}`))),lines.join(`
8
+ `)}export{GUIDE_DEPTH_VALUES,GUIDE_OUTPUT_VALUES,_testOnlyGuide,renderGuideMarkdown,resolveGuideOutputFormat,runGuide};
2
9
  //# sourceMappingURL=guide.js.map
@@ -1,3 +1,3 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="825d7132-a49d-584a-b4ac-0801cfe6ad49")}catch(e2){}})();import fs from"node:fs/promises";import{PmCliError}from"../../core/shared/errors.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{exportAttestation,verifyAttestation}from"./attestation.js";async function runHistoryAttest(options,global2){for(const key of["verify","output","hashAlgorithm"]){const value=options[key];if(key==="verify"&&typeof value==="object"&&value!==null)continue;if(value!==void 0&&(typeof value!=="string"||value.trim().length===0)){throw new PmCliError(`history attest ${key} requires a nonempty string.`,EXIT_CODE.USAGE)}}if(options.verify!==void 0){if(options.output!==void 0||options.hashAlgorithm!==void 0)throw new PmCliError("history attest --verify cannot be combined with --output or --hash-algorithm",EXIT_CODE.USAGE);let proof;try{proof=typeof options.verify==="string"?JSON.parse(await fs.readFile(options.verify,"utf8")):options.verify}catch{throw new PmCliError("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",EXIT_CODE.USAGE)}return verifyAttestation(proof,{pmRoot:global2.path})}const bundle=await exportAttestation({pmRoot:global2.path,hashAlgorithm:resolveHistoryHashAlgorithm(options.hashAlgorithm)});if(options.output===void 0)return bundle;try{await fs.writeFile(options.output,`${JSON.stringify(bundle,null,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]="3bca4afb-f1cc-5627-a377-b30e8005a284")}catch{}})();import fs from"node:fs/promises";import{PmCliError}from"../../core/shared/errors.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{exportAttestation,verifyAttestation}from"./attestation.js";async function runHistoryAttest(options,global2){for(const key of["verify","output","hashAlgorithm"]){const value=options[key];if(!(key==="verify"&&typeof value=="object"&&value!==null)&&value!==void 0&&(typeof value!="string"||value.trim().length===0))throw new PmCliError(`history attest ${key} requires a nonempty string.`,EXIT_CODE.USAGE)}if(options.verify!==void 0){if(options.output!==void 0||options.hashAlgorithm!==void 0)throw new PmCliError("history attest --verify cannot be combined with --output or --hash-algorithm",EXIT_CODE.USAGE);let proof;try{proof=typeof options.verify=="string"?JSON.parse(await fs.readFile(options.verify,"utf8")):options.verify}catch{throw new PmCliError("Cannot read history attestation proof. Provide --verify with a readable JSON proof file.",EXIT_CODE.USAGE)}return verifyAttestation(proof,{pmRoot:global2.path})}const bundle=await exportAttestation({pmRoot:global2.path,hashAlgorithm:resolveHistoryHashAlgorithm(options.hashAlgorithm)});if(options.output===void 0)return bundle;try{await fs.writeFile(options.output,`${JSON.stringify(bundle,null,2)}
2
2
  `,{flag:"wx",mode:384})}catch{throw new PmCliError("Cannot create history attestation proof. Choose --output with a new filename in a writable directory; existing files are never overwritten.",EXIT_CODE.USAGE)}return{output:options.output,workspace_digest:bundle.workspace_digest,streams:bundle.streams.length}}export{runHistoryAttest};
3
3
  //# sourceMappingURL=attestation-command.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="63c96190-0df9-5803-aa61-b973493a7277")}catch(e2){}})();const PM_HISTORY_ATTESTATION_CONTRACT={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};export{PM_HISTORY_ATTESTATION_CONTRACT};
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]="63c96190-0df9-5803-aa61-b973493a7277")}catch{}})();const PM_HISTORY_ATTESTATION_CONTRACT={format:"pm-history-attestation",version:1,stream_hash:"exact_file_bytes",rollup_hash:"stable_json_without_workspace_digest",ordering:"stream_id_code_unit_ascending",consistency:"per_stream_snapshot_with_change_detection",trust:"independently_retained_bundle"};export{PM_HISTORY_ATTESTATION_CONTRACT};
2
2
  //# sourceMappingURL=attestation-contract.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="d0001f37-7941-5cad-8950-2c6925056d10")}catch(e2){}})();import{createHash}from"node:crypto";import{isUtf8}from"node:buffer";import fs from"node:fs/promises";import path from"node:path";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{verifyHistoryChain}from"../../core/history/replay.js";import{stableStringify}from"../../core/shared/serialization.js";async function historyNames(directory){try{return(await fs.readdir(directory)).filter(name=>name.endsWith(".jsonl")).sort()}catch(error){if(isFileMissingError(error))return[];throw error}}function summarizeStream(id,entries,bytes,digest){const latest=entries.at(-1);let maintenance;for(let index=entries.length-1;index>=0;index-=1){if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(entries[index].op)){maintenance=entries[index];break}}const checkpoint=entries[0]?.context?.history_compaction;const checkpointDigest=typeof checkpoint==="object"&&checkpoint!==null&&"pruned_stream_digest"in checkpoint&&typeof checkpoint.pruned_stream_digest==="string"?checkpoint.pruned_stream_digest:null;return{id,entries:entries.length,bytes,stream_digest:digest,latest_after_hash:latest?.after_hash??null,latest_record_hash:latest?.record_hash??null,latest_hash_algorithm:latest?resolveHistoryHashAlgorithm(latest.hash_algorithm):null,rewrite_count:entries.reduce((count,entry)=>count+(entry.reanchor_evidence?.length??0),0),checkpoint_digest:checkpointDigest,last_maintenance:maintenance?{op:maintenance.op,ts:maintenance.ts,record_hash:maintenance.record_hash??null}:null}}function decodeAttestedStream(id,bytes,digest){try{if(!/^[A-Za-z0-9_-]+$/u.test(id))return null;if(!isUtf8(bytes))return null;const entries=[];for(const line of bytes.toString("utf8").split(/\r?\n/u)){if(!line.trim())continue;const entry=JSON.parse(line);if(typeof entry!=="object"||entry===null||Array.isArray(entry))return null;const record=entry;if(![record.op,record.author,record.ts,record.before_hash,record.after_hash].every(field=>typeof field==="string")||!Array.isArray(record.patch))return null;entries.push(record)}return verifyHistoryChain(entries).ok?summarizeStream(id,entries,bytes.length,digest):null}catch{return null}}async function scanAttestationStreams(pmRoot,algorithm){if(!(await fs.stat(pmRoot)).isDirectory())throw new TypeError("attestation tracker root must be a directory");const directory=path.join(pmRoot,"history");const names=await historyNames(directory);const observations=new Map;const rows=[];for(const name of names){const id=name.slice(0,-6);const row={id,digest:null,stream:null};rows.push(row);const filename=path.join(directory,name);try{const before=await fs.lstat(filename);observations.set(name,stableStringify([before.ino,before.size,before.mtimeMs,before.ctimeMs]));if(!before.isFile())continue;const bytes=await fs.readFile(filename);row.digest=createHash(algorithm).update(bytes).digest("hex");row.stream=decodeAttestedStream(id,bytes,row.digest)}catch{}}if(stableStringify(names)!==stableStringify(await historyNames(directory)))throw new TypeError("attestation history inventory changed during read; retry");for(const[name,observed]of observations){const after=await fs.lstat(path.join(directory,name));if(observed!==stableStringify([after.ino,after.size,after.mtimeMs,after.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return rows}export{scanAttestationStreams};
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]="a049f799-3807-59b5-96de-51e900798779")}catch{}})();import{createHash}from"node:crypto";import{isUtf8}from"node:buffer";import fs from"node:fs/promises";import path from"node:path";import{isFileMissingError}from"../../core/fs/fs-utils.js";import{resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{verifyHistoryChain}from"../../core/history/replay.js";import{stableStringify}from"../../core/shared/serialization.js";async function historyNames(directory){try{return(await fs.readdir(directory)).filter(name=>name.endsWith(".jsonl")).sort()}catch(error){if(isFileMissingError(error))return[];throw error}}function summarizeStream(id,entries,bytes,digest){const latest=entries.at(-1);let maintenance;for(let index=entries.length-1;index>=0;index-=1)if(["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(entries[index].op)){maintenance=entries[index];break}const checkpoint=entries[0]?.context?.history_compaction,checkpointDigest=typeof checkpoint=="object"&&checkpoint!==null&&"pruned_stream_digest"in checkpoint&&typeof checkpoint.pruned_stream_digest=="string"?checkpoint.pruned_stream_digest:null;return{id,entries:entries.length,bytes,stream_digest:digest,latest_after_hash:latest?.after_hash??null,latest_record_hash:latest?.record_hash??null,latest_hash_algorithm:latest?resolveHistoryHashAlgorithm(latest.hash_algorithm):null,rewrite_count:entries.reduce((count,entry)=>count+(entry.reanchor_evidence?.length??0),0),checkpoint_digest:checkpointDigest,last_maintenance:maintenance?{op:maintenance.op,ts:maintenance.ts,record_hash:maintenance.record_hash??null}:null}}function decodeAttestedStream(id,bytes,digest){try{if(!/^[A-Za-z0-9_-]+$/u.test(id)||!isUtf8(bytes))return null;const entries=[];for(const line of bytes.toString("utf8").split(/\r?\n/u)){if(!line.trim())continue;const entry=JSON.parse(line);if(typeof entry!="object"||entry===null||Array.isArray(entry))return null;const record=entry;if(![record.op,record.author,record.ts,record.before_hash,record.after_hash].every(field=>typeof field=="string")||!Array.isArray(record.patch))return null;entries.push(record)}return verifyHistoryChain(entries).ok?summarizeStream(id,entries,bytes.length,digest):null}catch{return null}}async function scanAttestationStreams(pmRoot,algorithm){if(!(await fs.stat(pmRoot)).isDirectory())throw new TypeError("attestation tracker root must be a directory");const directory=path.join(pmRoot,"history"),names=await historyNames(directory),observations=new Map,rows=[];for(const name of names){const id=name.slice(0,-6),row={id,digest:null,stream:null};rows.push(row);const filename=path.join(directory,name);try{const before=await fs.lstat(filename);if(observations.set(name,stableStringify([before.ino,before.size,before.mtimeMs,before.ctimeMs])),!before.isFile())continue;const bytes=await fs.readFile(filename);row.digest=createHash(algorithm).update(bytes).digest("hex"),row.stream=decodeAttestedStream(id,bytes,row.digest)}catch{}}if(stableStringify(names)!==stableStringify(await historyNames(directory)))throw new TypeError("attestation history inventory changed during read; retry");for(const[name,observed]of observations){const after=await fs.lstat(path.join(directory,name));if(observed!==stableStringify([after.ino,after.size,after.mtimeMs,after.ctimeMs]))throw new TypeError("attestation history stream changed during read; retry")}return rows}export{scanAttestationStreams};
2
2
  //# sourceMappingURL=attestation-scan.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="0a4b3fc5-70bb-5ec0-82b5-a7cdd03c09ea")}catch(e2){}})();import{historyDigest,resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{stableStringify}from"../../core/shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{scanAttestationStreams}from"./attestation-scan.js";import{PM_HISTORY_ATTESTATION_CONTRACT}from"./attestation-contract.js";export*from"./attestation-contract.js";function isObject(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function hasFields(value,fields){return Object.keys(value).length===fields.length&&fields.every(field=>Object.hasOwn(value,field))}function isDigest(value,algorithm){return typeof value==="string"&&(algorithm==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(value)}function validStreamAnchors(value){if(value.entries===0){return[value.latest_hash_algorithm,value.latest_after_hash,value.latest_record_hash,value.checkpoint_digest,value.last_maintenance].every(field=>field===null)&&value.rewrite_count===0}if(value.latest_hash_algorithm!=="sha256"&&value.latest_hash_algorithm!=="sha512")return false;return isDigest(value.latest_after_hash,value.latest_hash_algorithm)&&(value.latest_record_hash===null||isDigest(value.latest_record_hash,value.latest_hash_algorithm))}function validMaintenance(value){if(value===null)return true;if(!isObject(value)||!hasFields(value,["op","ts","record_hash"]))return false;return typeof value.op==="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(value.op)&&typeof value.ts==="string"&&isMillisecondPrecisionRfc3339DateTime(value.ts)&&(value.record_hash===null||isDigest(value.record_hash,"sha256")||isDigest(value.record_hash,"sha512"))}function isStream(value,algorithm){if(!isObject(value)||!hasFields(value,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"]))return false;return typeof value.id==="string"&&/^[A-Za-z0-9_-]+$/u.test(value.id)&&[value.entries,value.bytes,value.rewrite_count].every(count=>typeof count==="number"&&Number.isSafeInteger(count)&&count>=0)&&isDigest(value.stream_digest,algorithm)&&validStreamAnchors(value)&&(value.checkpoint_digest===null||isDigest(value.checkpoint_digest,"sha256"))&&validMaintenance(value.last_maintenance)}function parseHistoryAttestation(value){if(!isObject(value)||!hasFields(value,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(value.format!==PM_HISTORY_ATTESTATION_CONTRACT.format||value.version!==1||typeof value.generated_at!=="string"||!isMillisecondPrecisionRfc3339DateTime(value.generated_at)||!Array.isArray(value.streams)||value.hash_algorithm!=="sha256"&&value.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");const algorithm=value.hash_algorithm;let previous;for(const stream of value.streams){if(!isStream(stream,algorithm))throw new TypeError("Invalid history attestation stream");const id=stream.id;if(previous!==void 0&&id<=previous)throw new TypeError("Invalid history attestation stream order");previous=id}const{workspace_digest:expected,...payload}=value;if(historyDigest(stableStringify(payload),algorithm)!==expected)throw new TypeError("History attestation rollup mismatch");return value}async function exportAttestation(options={}){const algorithm=resolveHistoryHashAlgorithm(options.hashAlgorithm);const generatedAt=options.generatedAt??nowIso();if(!isMillisecondPrecisionRfc3339DateTime(generatedAt))throw new TypeError("Invalid history attestation timestamp");const rows=await scanAttestationStreams(resolvePmRoot(options.cwd??process.cwd(),options.pmRoot),algorithm);const invalid=rows.filter(row=>row.stream===null);if(invalid.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${invalid.map(row=>row.id).join(", ")}`);const payload={format:PM_HISTORY_ATTESTATION_CONTRACT.format,version:1,hash_algorithm:algorithm,generated_at:generatedAt,streams:rows.map(row=>row.stream)};return parseHistoryAttestation({...payload,workspace_digest:historyDigest(stableStringify(payload),algorithm)})}async function verifyAttestation(bundleInput,options={}){const bundle=parseHistoryAttestation(bundleInput);const rows=await scanAttestationStreams(resolvePmRoot(options.cwd??process.cwd(),options.pmRoot),bundle.hash_algorithm);const current=new Map(rows.map(row=>[row.id,row]));const expected=new Map(bundle.streams.map(stream=>[stream.id,stream]));const missing=bundle.streams.filter(stream=>!current.has(stream.id)).map(stream=>stream.id);const added=rows.filter(row=>!expected.has(row.id)).map(row=>row.id);const invalid=rows.filter(row=>row.stream===null).map(row=>row.id);const transitions=[];for(const stream of bundle.streams){const row=current.get(stream.id);if(row&&(row.digest!==stream.stream_digest||stableStringify(row.stream)!==stableStringify(stream)))transitions.push({id:stream.id,before_digest:stream.stream_digest,after_digest:row.digest,last_maintenance:row.stream?.last_maintenance??null})}return{ok:missing.length+added.length+invalid.length+transitions.length===0,workspace_digest:bundle.workspace_digest,streams_checked:rows.length,changed_streams:transitions.map(transition=>transition.id),missing_streams:missing,added_streams:added,invalid_streams:invalid,transitions}}export{exportAttestation,parseHistoryAttestation,verifyAttestation};
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]="54d3c0f4-e663-5e31-aa4e-45ea2f6aaf75")}catch{}})();import{historyDigest,resolveHistoryHashAlgorithm}from"../../core/history/digest.js";import{stableStringify}from"../../core/shared/serialization.js";import{isMillisecondPrecisionRfc3339DateTime,nowIso}from"../../core/shared/time.js";import{resolvePmRoot}from"../../core/store/paths.js";import{scanAttestationStreams}from"./attestation-scan.js";import{PM_HISTORY_ATTESTATION_CONTRACT}from"./attestation-contract.js";export*from"./attestation-contract.js";function isObject(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}function hasFields(value,fields){return Object.keys(value).length===fields.length&&fields.every(field=>Object.hasOwn(value,field))}function isDigest(value,algorithm){return typeof value=="string"&&(algorithm==="sha256"?/^[a-f0-9]{64}$/u:/^[a-f0-9]{128}$/u).test(value)}function validStreamAnchors(value){return value.entries===0?[value.latest_hash_algorithm,value.latest_after_hash,value.latest_record_hash,value.checkpoint_digest,value.last_maintenance].every(field=>field===null)&&value.rewrite_count===0:value.latest_hash_algorithm!=="sha256"&&value.latest_hash_algorithm!=="sha512"?!1:isDigest(value.latest_after_hash,value.latest_hash_algorithm)&&(value.latest_record_hash===null||isDigest(value.latest_record_hash,value.latest_hash_algorithm))}function validMaintenance(value){return value===null?!0:!isObject(value)||!hasFields(value,["op","ts","record_hash"])?!1:typeof value.op=="string"&&["history_compact","history_compact_baseline","history_redact","history_repair","history_salvage","merge_reconcile"].includes(value.op)&&typeof value.ts=="string"&&isMillisecondPrecisionRfc3339DateTime(value.ts)&&(value.record_hash===null||isDigest(value.record_hash,"sha256")||isDigest(value.record_hash,"sha512"))}function isStream(value,algorithm){return!isObject(value)||!hasFields(value,["id","entries","bytes","stream_digest","latest_after_hash","latest_record_hash","latest_hash_algorithm","rewrite_count","checkpoint_digest","last_maintenance"])?!1:typeof value.id=="string"&&/^[A-Za-z0-9_-]+$/u.test(value.id)&&[value.entries,value.bytes,value.rewrite_count].every(count=>typeof count=="number"&&Number.isSafeInteger(count)&&count>=0)&&isDigest(value.stream_digest,algorithm)&&validStreamAnchors(value)&&(value.checkpoint_digest===null||isDigest(value.checkpoint_digest,"sha256"))&&validMaintenance(value.last_maintenance)}function parseHistoryAttestation(value){if(!isObject(value)||!hasFields(value,["format","version","hash_algorithm","generated_at","streams","workspace_digest"]))throw new TypeError("Invalid history attestation bundle");if(value.format!==PM_HISTORY_ATTESTATION_CONTRACT.format||value.version!==1||typeof value.generated_at!="string"||!isMillisecondPrecisionRfc3339DateTime(value.generated_at)||!Array.isArray(value.streams)||value.hash_algorithm!=="sha256"&&value.hash_algorithm!=="sha512")throw new TypeError("Invalid history attestation format");const algorithm=value.hash_algorithm;let previous;for(const stream of value.streams){if(!isStream(stream,algorithm))throw new TypeError("Invalid history attestation stream");const id=stream.id;if(previous!==void 0&&id<=previous)throw new TypeError("Invalid history attestation stream order");previous=id}const{workspace_digest:expected,...payload}=value;if(historyDigest(stableStringify(payload),algorithm)!==expected)throw new TypeError("History attestation rollup mismatch");return value}async function exportAttestation(options={}){const algorithm=resolveHistoryHashAlgorithm(options.hashAlgorithm),generatedAt=options.generatedAt??nowIso();if(!isMillisecondPrecisionRfc3339DateTime(generatedAt))throw new TypeError("Invalid history attestation timestamp");const rows=await scanAttestationStreams(resolvePmRoot(options.cwd??process.cwd(),options.pmRoot),algorithm),invalid=rows.filter(row=>row.stream===null);if(invalid.length>0)throw new TypeError(`Cannot export history attestation: invalid streams ${invalid.map(row=>row.id).join(", ")}`);const payload={format:PM_HISTORY_ATTESTATION_CONTRACT.format,version:1,hash_algorithm:algorithm,generated_at:generatedAt,streams:rows.map(row=>row.stream)};return parseHistoryAttestation({...payload,workspace_digest:historyDigest(stableStringify(payload),algorithm)})}async function verifyAttestation(bundleInput,options={}){const bundle=parseHistoryAttestation(bundleInput),rows=await scanAttestationStreams(resolvePmRoot(options.cwd??process.cwd(),options.pmRoot),bundle.hash_algorithm),current=new Map(rows.map(row=>[row.id,row])),expected=new Map(bundle.streams.map(stream=>[stream.id,stream])),missing=bundle.streams.filter(stream=>!current.has(stream.id)).map(stream=>stream.id),added=rows.filter(row=>!expected.has(row.id)).map(row=>row.id),invalid=rows.filter(row=>row.stream===null).map(row=>row.id),transitions=[];for(const stream of bundle.streams){const row=current.get(stream.id);row&&(row.digest!==stream.stream_digest||stableStringify(row.stream)!==stableStringify(stream))&&transitions.push({id:stream.id,before_digest:stream.stream_digest,after_digest:row.digest,last_maintenance:row.stream?.last_maintenance??null})}return{ok:missing.length+added.length+invalid.length+transitions.length===0,workspace_digest:bundle.workspace_digest,streams_checked:rows.length,changed_streams:transitions.map(transition=>transition.id),missing_streams:missing,added_streams:added,invalid_streams:invalid,transitions}}export{exportAttestation,parseHistoryAttestation,verifyAttestation};
2
2
  //# sourceMappingURL=attestation.js.map
@@ -1,2 +1,2 @@
1
- !(function(){try{var e="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof globalThis?globalThis:"undefined"!=typeof self?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="7bab0f96-b67f-5523-9d1f-7426e1d58fbd")}catch(e2){}})();import{runActiveOnWriteHooks}from"../../core/extensions/index.js";import{readHistorySnapshot}from"../../core/history/read.js";import{executeHistoryRewrite,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{historyEntriesToRaw,verifyHistoryChain}from"../../core/history/replay.js";import{resolveAuthor}from"../../core/shared/author.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{readLocatedItem}from"../../core/store/item-store.js";async function runHistoryMaintenance(params){const{subject,settings,operation,options}=params;const snapshot=await readHistorySnapshot(subject.historyPath,subject.id);if(snapshot.raw===null){throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND)}if(snapshot.entries.length===0){throw new PmCliError(`No history entries exist for ${subject.id}; nothing to ${operation.slice("history-".length)}.`,EXIT_CODE.USAGE)}const loadedItem=subject.located?await readLocatedItem(subject.located,{schema:settings.schema}):null;const author=resolveAuthor(options.author,settings.author_default);const plan=await params.transform({raw:snapshot.raw,entries:snapshot.entries,verification:verifyHistoryChain(snapshot.entries),loadedItem,author});const verification=verifyHistoryChain(plan.rewrittenEntries);if(!verification.ok){throw new PmCliError(`${operation} produced an invalid rewritten chain (${verification.errors.join(", ")}).`,EXIT_CODE.GENERIC_FAILURE)}const warnings=plan.changed&&!options.dryRun?await executeHistoryRewrite({pmRoot:params.pmRoot,subject,settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:snapshot.raw,currentItemRawBeforeLock:loadedItem?.raw??null,operation,author,force:options.force,itemDocument:loadedItem?.document??null,applyRewrite:async verified=>{await plan.beforeWrite?.();if(plan.applyRewrite){await plan.applyRewrite(verified)}else{await writeHistoryRawWithRollback({historyPath:subject.historyPath,nextHistoryRaw:historyEntriesToRaw(plan.rewrittenEntries),historyRawUnderLock:verified.historyRawUnderLock})}},applyPostRewrite:plan.afterWrite??(async()=>runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:`${operation.replace("-","_")}:history`}))}):[];return plan.report({verification,warnings})}export{runHistoryMaintenance};
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]="6283ef18-f75e-5e8c-a65f-0ba05858bc2b")}catch{}})();import{runActiveOnWriteHooks}from"../../core/extensions/index.js";import{readHistorySnapshot}from"../../core/history/read.js";import{executeHistoryRewrite,writeHistoryRawWithRollback}from"../../core/history/history-rewrite.js";import{historyEntriesToRaw,verifyHistoryChain}from"../../core/history/replay.js";import{resolveAuthor}from"../../core/shared/author.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{readLocatedItem}from"../../core/store/item-store.js";async function runHistoryMaintenance(params){const{subject,settings,operation,options}=params,snapshot=await readHistorySnapshot(subject.historyPath,subject.id);if(snapshot.raw===null)throw new PmCliError(`No history stream exists for ${subject.id}.`,EXIT_CODE.NOT_FOUND);if(snapshot.entries.length===0)throw new PmCliError(`No history entries exist for ${subject.id}; nothing to ${operation.slice(8)}.`,EXIT_CODE.USAGE);const loadedItem=subject.located?await readLocatedItem(subject.located,{schema:settings.schema}):null,author=resolveAuthor(options.author,settings.author_default),plan=await params.transform({raw:snapshot.raw,entries:snapshot.entries,verification:verifyHistoryChain(snapshot.entries),loadedItem,author}),verification=verifyHistoryChain(plan.rewrittenEntries);if(!verification.ok)throw new PmCliError(`${operation} produced an invalid rewritten chain (${verification.errors.join(", ")}).`,EXIT_CODE.GENERIC_FAILURE);const warnings=plan.changed&&!options.dryRun?await executeHistoryRewrite({pmRoot:params.pmRoot,subject,settings,typeRegistry:params.typeRegistry,historyRawBeforeLock:snapshot.raw,currentItemRawBeforeLock:loadedItem?.raw??null,operation,author,force:options.force,itemDocument:loadedItem?.document??null,applyRewrite:async verified=>{await plan.beforeWrite?.(),plan.applyRewrite?await plan.applyRewrite(verified):await writeHistoryRawWithRollback({historyPath:subject.historyPath,nextHistoryRaw:historyEntriesToRaw(plan.rewrittenEntries),historyRawUnderLock:verified.historyRawUnderLock})},applyPostRewrite:plan.afterWrite??(async()=>runActiveOnWriteHooks({path:subject.historyPath,scope:"project",op:`${operation.replace("-","_")}:history`}))}):[];return plan.report({verification,warnings})}export{runHistoryMaintenance};
2
2
  //# sourceMappingURL=maintenance.js.map