@unbrained/pm-cli 2026.11.6 → 2026.11.7
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.
- package/.claude-plugin/marketplace.json +1 -1
- package/CHANGELOG.md +13 -0
- package/dist/cli/expected-revisions.js +1 -1
- package/dist/cli/main.js +1 -1
- package/dist/cli/runtime/close-fields-retry.js +2 -0
- package/dist/cli-bundle/bundle-manifest.json +1 -1
- package/dist/cli-bundle/chunks/chunk-3DI6CEF3.js +3 -0
- package/dist/cli-bundle/chunks/{chunk-6VRX2CM7.js → chunk-4PPWVIIT.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-7ZRCYESH.js → chunk-5KHLV7JU.js} +47 -47
- package/dist/cli-bundle/chunks/{chunk-X3URBPMV.js → chunk-BQ5O3CBF.js} +51 -51
- package/dist/cli-bundle/chunks/{chunk-WC4M2H6R.js → chunk-COKKWMSC.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-D53G3NOE.js +6 -0
- package/dist/cli-bundle/chunks/{chunk-LS3GI3H4.js → chunk-ETHAZC3F.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-F3B2ULHB.js +122 -0
- package/dist/cli-bundle/chunks/chunk-JZWFZH2K.js +2 -0
- package/dist/cli-bundle/chunks/{chunk-335BZ75D.js → chunk-KPAVZILX.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-OH6WQ7VT.js → chunk-MQOZNGPS.js} +2 -2
- package/dist/cli-bundle/chunks/chunk-O6TIOKCM.js +9 -0
- package/dist/cli-bundle/chunks/{chunk-PE3ASURT.js → chunk-OIBSKKCO.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-HRFGFIYU.js → chunk-OJZG7Y6S.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-SLC5UWCM.js → chunk-QG6FLDM4.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-D7KYPRK4.js → chunk-RFI4O6NU.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-TSQCUBUX.js → chunk-TGQPCNAD.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-DAX3AOFI.js → chunk-VM6OGNQC.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-S4LPZ4TN.js → chunk-WS2N4TQW.js} +7 -7
- package/dist/cli-bundle/chunks/{chunk-UEGXWXUZ.js → chunk-WXVMPLBY.js} +2 -2
- package/dist/cli-bundle/chunks/{chunk-QNWUIPBO.js → chunk-WYIDX67P.js} +30 -30
- package/dist/cli-bundle/chunks/{chunk-7DEKAXVA.js → chunk-XSEDESNW.js} +2 -2
- package/dist/cli-bundle/chunks/item-revision-SPEKTFBB.js +2 -0
- package/dist/cli-bundle/chunks/item-transaction-BT55TQXE.js +2 -0
- package/dist/cli-bundle/chunks/{mutation-admission-INMM3HHG.js → mutation-admission-LUXUKISJ.js} +2 -2
- package/dist/cli-bundle/chunks/{register-list-query-5Y5JKWU5.js → register-list-query-DU4W7VJU.js} +3 -3
- package/dist/cli-bundle/chunks/{register-mutation-MDSUU3G7.js → register-mutation-IC2C53QK.js} +2 -2
- package/dist/cli-bundle/chunks/{register-operations-WJHZJFK2.js → register-operations-AHDWE2G3.js} +2 -2
- package/dist/cli-bundle/chunks/{register-setup-RRFOS7IT.js → register-setup-7BGG3CI3.js} +2 -2
- package/dist/cli-bundle/chunks/{stage-E3MMV4TV.js → stage-S5BYWLGY.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CPMSL4HS.js → chunk-4EXRRSDS.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-4LDOL6U7.js +26 -0
- package/dist/cli-bundle/focused-chunks/chunk-A46YSPRF.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-RFTJZ5VB.js → chunk-AI2PYNFI.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-AJ2I377F.js +44 -0
- package/dist/cli-bundle/focused-chunks/{chunk-WSOAASCY.js → chunk-BIDF4KO7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-VWWTIX5L.js → chunk-CWFNQQZE.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-D3U7FOZR.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-F62XGAAY.js → chunk-G2VIY6XA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MG7C3JUY.js → chunk-GFF6BITP.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-LW64TINU.js → chunk-IIBWXNW3.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-AHWJPZSJ.js → chunk-IYJRFJHT.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-D2TBEBNW.js → chunk-J5N42SKC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-MC7IE7D7.js → chunk-JRJOFMI7.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-CZM75DE3.js → chunk-KL33JMPC.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-E56OXRYH.js → chunk-LH4C7BLB.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-YMGB2O4E.js → chunk-LTQEYE2L.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-LTTMERPN.js +12 -0
- package/dist/cli-bundle/focused-chunks/{chunk-7KK66ISG.js → chunk-LW4TN5ZM.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-XHOBYCVE.js → chunk-MESFDQ3H.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-G4QP365K.js → chunk-MWTBAI3V.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-TWULNB3N.js +2 -0
- package/dist/cli-bundle/focused-chunks/{chunk-C6P6HPCX.js → chunk-XAC6NP7U.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{chunk-GS3JC5UU.js → chunk-XG3TBYQK.js} +2 -2
- package/dist/cli-bundle/focused-chunks/chunk-XMZAFKVP.js +91 -0
- package/dist/cli-bundle/focused-chunks/item-revision-ELI6NGMY.js +2 -0
- package/dist/cli-bundle/focused-chunks/{item-transaction-H2XACBOP.js → item-transaction-GUGAUY77.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{mutation-admission-4WM7TNHZ.js → mutation-admission-54FI37AA.js} +2 -2
- package/dist/cli-bundle/focused-chunks/{stage-WV7QXR4C.js → stage-OHDJ43T2.js} +2 -2
- package/dist/cli-bundle/main.js +31 -31
- package/dist/cli-bundle/sdk-authoring.js +1 -1
- package/dist/cli-bundle/sdk-contracts.js +1 -1
- package/dist/cli-bundle/sdk-core.js +1 -1
- package/dist/cli-bundle/sdk-governance.js +1 -1
- package/dist/cli-bundle/sdk-graph.js +1 -1
- package/dist/cli-bundle/sdk-merge.js +57 -57
- package/dist/cli-bundle/sdk-query.js +1 -1
- package/dist/cli-bundle/sdk-runtime.js +1 -1
- package/dist/cli-bundle/sdk-testing.js +1 -1
- package/dist/cli-bundle/sdk.js +2 -2
- package/dist/core/store/item-mutation-precondition.d.ts +58 -0
- package/dist/core/store/item-mutation-precondition.js +1 -1
- package/dist/sdk/command-line.d.ts +5 -1
- package/dist/sdk/command-line.js +1 -1
- package/dist/sdk/lifecycle/close.js +1 -1
- package/dist/sdk/lifecycle/item-revision.d.ts +15 -4
- package/dist/sdk/lifecycle/item-revision.js +1 -1
- package/dist/sdk/output/list-envelope.d.ts +18 -7
- package/dist/sdk/output/list-envelope.js +1 -1
- package/dist/sdk/output-projection.js +1 -1
- package/dist/sdk/public-surface.json +1 -1
- package/dist/sdk/query/get.d.ts +16 -6
- package/dist/sdk/query/get.js +1 -1
- package/dist/sdk/query/search/response.js +1 -1
- package/dist/sdk/runtime.js +1 -1
- package/docs/CLOSE_EVIDENCE_RECOVERY.md +36 -2
- package/docs/COMMANDS.md +10 -1
- package/docs/GET_READ_EVIDENCE.md +24 -3
- package/docs/RELEASING.md +17 -0
- package/docs/SDK.md +24 -7
- package/marketplace.json +1 -1
- package/package.json +1 -1
- package/packages/pm-beads/package.json +1 -1
- package/packages/pm-calendar/package.json +1 -1
- package/packages/pm-command-kit/package.json +1 -1
- package/packages/pm-digital-twin/package.json +1 -1
- package/packages/pm-governance-audit/package.json +1 -1
- package/packages/pm-guide-shell/package.json +1 -1
- package/packages/pm-kanban/package.json +1 -1
- package/packages/pm-lifecycle-hooks/package.json +1 -1
- package/packages/pm-linked-test-adapters/package.json +1 -1
- package/packages/pm-search-advanced/package.json +1 -1
- package/packages/pm-templates/package.json +1 -1
- package/packages/pm-todos/package.json +1 -1
- package/packages/pm-vcs/package.json +1 -1
- package/plugins/pm-claude/.claude-plugin/plugin.json +1 -1
- package/plugins/pm-claude/package.json +1 -1
- package/plugins/pm-codex/.codex-plugin/plugin.json +1 -1
- package/plugins/pm-codex/package.json +1 -1
- package/plugins/pm-codex/plugin.json +1 -1
- package/runtime-dependencies.json +1 -1
- package/dist/cli/after-command-context-usage.d.ts +0 -21
- package/dist/cli/argv-utils.d.ts +0 -12
- package/dist/cli/bootstrap-args.d.ts +0 -6
- package/dist/cli/bundle-integrity.d.ts +0 -49
- package/dist/cli/command-namespaces.d.ts +0 -9
- package/dist/cli/commander-usage.d.ts +0 -73
- package/dist/cli/commands/annotations/comments.d.ts +0 -2
- package/dist/cli/commands/annotations/docs.d.ts +0 -6
- package/dist/cli/commands/annotations/files.d.ts +0 -6
- package/dist/cli/commands/annotations/learnings.d.ts +0 -2
- package/dist/cli/commands/annotations/notes.d.ts +0 -2
- package/dist/cli/commands/extension/describe.d.ts +0 -2
- package/dist/cli/commands/extension/extension.d.ts +0 -6
- package/dist/cli/commands/extension/scaffold.d.ts +0 -2
- package/dist/cli/commands/extension/shared.d.ts +0 -2
- package/dist/cli/commands/governance/gc.d.ts +0 -6
- package/dist/cli/commands/governance/health.d.ts +0 -6
- package/dist/cli/commands/governance/telemetry.d.ts +0 -6
- package/dist/cli/commands/governance/validate.d.ts +0 -9
- package/dist/cli/commands/history/activity.d.ts +0 -6
- package/dist/cli/commands/history/history-compact.d.ts +0 -7
- package/dist/cli/commands/history/history-redact.d.ts +0 -8
- package/dist/cli/commands/history/history-repair.d.ts +0 -7
- package/dist/cli/commands/history/history.d.ts +0 -2
- package/dist/cli/commands/history/restore.d.ts +0 -6
- package/dist/cli/commands/lifecycle/append.d.ts +0 -6
- package/dist/cli/commands/lifecycle/claim.d.ts +0 -2
- package/dist/cli/commands/lifecycle/close-many.d.ts +0 -2
- package/dist/cli/commands/lifecycle/close.d.ts +0 -6
- package/dist/cli/commands/lifecycle/copy.d.ts +0 -6
- package/dist/cli/commands/lifecycle/create.d.ts +0 -10
- package/dist/cli/commands/lifecycle/delete.d.ts +0 -6
- package/dist/cli/commands/lifecycle/focus.d.ts +0 -6
- package/dist/cli/commands/lifecycle/plan.d.ts +0 -9
- package/dist/cli/commands/lifecycle/update-many.d.ts +0 -6
- package/dist/cli/commands/lifecycle/update.d.ts +0 -10
- package/dist/cli/commands/query/aggregate.d.ts +0 -2
- package/dist/cli/commands/query/context.d.ts +0 -6
- package/dist/cli/commands/query/deps.d.ts +0 -6
- package/dist/cli/commands/query/duplicates.d.ts +0 -6
- package/dist/cli/commands/query/eval.d.ts +0 -6
- package/dist/cli/commands/query/get.d.ts +0 -6
- package/dist/cli/commands/query/graph.d.ts +0 -7
- package/dist/cli/commands/query/list.d.ts +0 -6
- package/dist/cli/commands/query/next.d.ts +0 -6
- package/dist/cli/commands/query/search.d.ts +0 -6
- package/dist/cli/commands/query/stats.d.ts +0 -6
- package/dist/cli/commands/test/test-all.d.ts +0 -6
- package/dist/cli/commands/test/test-runs.d.ts +0 -6
- package/dist/cli/commands/test/test.d.ts +0 -6
- package/dist/cli/commands/workspace/config.d.ts +0 -6
- package/dist/cli/commands/workspace/contracts.d.ts +0 -2
- package/dist/cli/commands/workspace/init.d.ts +0 -6
- package/dist/cli/commands/workspace/merge.d.ts +0 -8
- package/dist/cli/commands/workspace/profile.d.ts +0 -6
- package/dist/cli/commands/workspace/schema.d.ts +0 -7
- package/dist/cli/commands/workspace/upgrade.d.ts +0 -2
- package/dist/cli/context-intent-invocation.d.ts +0 -2
- package/dist/cli/description-stdin.d.ts +0 -2
- package/dist/cli/error-guidance.d.ts +0 -276
- package/dist/cli/expected-revisions.d.ts +0 -55
- package/dist/cli/extension-command-help.d.ts +0 -137
- package/dist/cli/extension-command-options.d.ts +0 -37
- package/dist/cli/extension-recovery.d.ts +0 -31
- package/dist/cli/help-content.d.ts +0 -57
- package/dist/cli/help-json-payload.d.ts +0 -83
- package/dist/cli/invocation-profile.d.ts +0 -26
- package/dist/cli/main.d.ts +0 -263
- package/dist/cli/migration-gates.d.ts +0 -55
- package/dist/cli/option-values.d.ts +0 -3
- package/dist/cli/preflight-warnings.d.ts +0 -11
- package/dist/cli/register-annotations.d.ts +0 -11
- package/dist/cli/register-assurance.d.ts +0 -8
- package/dist/cli/register-files-lookup.d.ts +0 -9
- package/dist/cli/register-history-activity.d.ts +0 -8
- package/dist/cli/register-history-author.d.ts +0 -8
- package/dist/cli/register-history-maintenance.d.ts +0 -9
- package/dist/cli/register-list-query.d.ts +0 -27
- package/dist/cli/register-mutation-options.d.ts +0 -10
- package/dist/cli/register-mutation.d.ts +0 -16
- package/dist/cli/register-operations.d.ts +0 -85
- package/dist/cli/register-setup.d.ts +0 -16
- package/dist/cli/register-structured-mutation.d.ts +0 -15
- package/dist/cli/registration-helpers.d.ts +0 -2
- package/dist/cli/runtime/activation.d.ts +0 -51
- package/dist/cli/runtime/field-route-retry.d.ts +0 -15
- package/dist/cli/runtime/invocation-options.d.ts +0 -43
- package/dist/cli/runtime/projection-retry.d.ts +0 -9
- package/dist/cli/runtime/selection.d.ts +0 -35
- package/dist/cli/runtime/telemetry-outcome.d.ts +0 -20
- package/dist/cli/runtime-compatibility-boundary.d.ts +0 -17
- package/dist/cli/schema/registration.d.ts +0 -4
- package/dist/cli/schema-registration-helpers.d.ts +0 -24
- package/dist/cli/search-refresh.d.ts +0 -2
- package/dist/cli/stats-analytics-json.d.ts +0 -9
- package/dist/cli/telemetry-flush.d.ts +0 -2
- package/dist/cli-bundle/chunks/chunk-5GWEY4P6.js +0 -122
- package/dist/cli-bundle/chunks/chunk-AUEKTX7V.js +0 -6
- package/dist/cli-bundle/chunks/chunk-FRNMQM45.js +0 -2
- package/dist/cli-bundle/chunks/chunk-HNGLDMSZ.js +0 -9
- package/dist/cli-bundle/chunks/chunk-YKXATU2G.js +0 -3
- package/dist/cli-bundle/chunks/item-revision-OJJVPQY7.js +0 -2
- package/dist/cli-bundle/chunks/item-transaction-TBKEATN6.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-2KTJY7BV.js +0 -44
- package/dist/cli-bundle/focused-chunks/chunk-G5PJCR7R.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-M6V7UMWL.js +0 -26
- package/dist/cli-bundle/focused-chunks/chunk-MK4HV4JO.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-O7EI33NP.js +0 -91
- package/dist/cli-bundle/focused-chunks/chunk-SNOXXRSJ.js +0 -2
- package/dist/cli-bundle/focused-chunks/chunk-UPJUTP2V.js +0 -12
- package/dist/cli-bundle/focused-chunks/item-revision-CTDO4H3I.js +0 -2
- package/dist/cli.d.ts +0 -13
- package/dist/core/checkpoint/checkpoint-gc.d.ts +0 -61
- package/dist/core/checkpoint/mutation-context.d.ts +0 -10
- package/dist/core/diagnostics/remediation.d.ts +0 -52
- package/dist/core/extensions/activation-transaction.d.ts +0 -22
- package/dist/core/extensions/command-visibility-tier.d.ts +0 -8
- package/dist/core/extensions/exporter-output-contract.d.ts +0 -12
- package/dist/core/extensions/extension-candidate.d.ts +0 -26
- package/dist/core/extensions/extension-runtime-helpers.d.ts +0 -16
- package/dist/core/extensions/module-graph-snapshot.d.ts +0 -19
- package/dist/core/extensions/preflight-ownership.d.ts +0 -5
- package/dist/core/extensions/read-output-contract.d.ts +0 -5
- package/dist/core/extensions/reserved-host-flags.d.ts +0 -18
- package/dist/core/extensions/service-ownership.d.ts +0 -8
- package/dist/core/extensions/version-diagnostics.d.ts +0 -2
- package/dist/core/fs/atomic-create.d.ts +0 -7
- package/dist/core/fs/index.d.ts +0 -6
- package/dist/core/fs/path-utils.d.ts +0 -2
- package/dist/core/history/drift-cache.d.ts +0 -4
- package/dist/core/history/drift-scan.d.ts +0 -51
- package/dist/core/history/index.d.ts +0 -6
- package/dist/core/history/tombstone.d.ts +0 -3
- package/dist/core/history/version-address.d.ts +0 -13
- package/dist/core/item/index.d.ts +0 -9
- package/dist/core/item/item-type-definition.d.ts +0 -51
- package/dist/core/item/toon-decode.d.ts +0 -25
- package/dist/core/lock/index.d.ts +0 -6
- package/dist/core/lock/lock-confinement.d.ts +0 -55
- package/dist/core/lock/lock-gc.d.ts +0 -93
- package/dist/core/output/mutation-projection.d.ts +0 -13
- package/dist/core/output/query-summary.d.ts +0 -30
- package/dist/core/search/staleness.d.ts +0 -23
- package/dist/core/sentry/sensitive-assignments.d.ts +0 -9
- package/dist/core/shared/conflict-markers.d.ts +0 -18
- package/dist/core/shared/index.d.ts +0 -9
- package/dist/core/shared/memo.d.ts +0 -7
- package/dist/core/store/index.d.ts +0 -9
- package/dist/core/store/settings-concurrency.d.ts +0 -7
- package/dist/core/telemetry/read-sampling.d.ts +0 -8
- package/dist/core/test/item-test-run-tracking.d.ts +0 -12
- package/dist/core/validate/estimate-defaults.d.ts +0 -21
- package/dist/core/validate/linked-artifact-reference.d.ts +0 -20
- package/dist/mcp/http-server.d.ts +0 -60
- package/dist/mcp/legacy-adapter.d.ts +0 -59
- package/dist/mcp/runtime-capabilities.d.ts +0 -57
- package/dist/mcp/server.d.ts +0 -101
- package/dist/sdk/cli-contracts/bootstrap-command-scanner.d.ts +0 -23
- package/dist/sdk/cli-contracts/registration-helpers.d.ts +0 -123
- package/dist/sdk/cli-contracts/schemas/assurance-definition.d.ts +0 -796
- package/dist/sdk/cli-contracts/string-lists.d.ts +0 -9
- package/dist/sdk/cli-contracts/tool-parameter-tables.d.ts +0 -35
- package/dist/sdk/context/usage-egress.d.ts +0 -9
- package/dist/sdk/dependencies/context-budget-recovery.d.ts +0 -21
- package/dist/sdk/dependency-flag-validation.d.ts +0 -32
- package/dist/sdk/extension/author-manifest.d.ts +0 -22
- package/dist/sdk/extension/bundled-catalog.d.ts +0 -35
- package/dist/sdk/extension/concurrency.d.ts +0 -7
- package/dist/sdk/extension/copy-scope.d.ts +0 -2
- package/dist/sdk/extension/custom-field-collisions.d.ts +0 -6
- package/dist/sdk/extension/install-receipts.d.ts +0 -7
- package/dist/sdk/extension/install-snapshot.d.ts +0 -34
- package/dist/sdk/extension/managed-update-status.d.ts +0 -3
- package/dist/sdk/extension/runtime-summary.d.ts +0 -9
- package/dist/sdk/extension/scaffold.d.ts +0 -38
- package/dist/sdk/generated/error-code-catalog-rows.d.ts +0 -39
- package/dist/sdk/generated/generated-error-code-catalog-part-1.d.ts +0 -8
- package/dist/sdk/generated/generated-error-code-catalog-part-2.d.ts +0 -8
- package/dist/sdk/governance/assurance-limits.d.ts +0 -7
- package/dist/sdk/governance/defect-recurrence-signals.d.ts +0 -10
- package/dist/sdk/governance/health-merge-evidence.d.ts +0 -23
- package/dist/sdk/governance/tracked-runtime-cache.d.ts +0 -24
- package/dist/sdk/governance/validate-history-drift.d.ts +0 -7
- package/dist/sdk/history/attestation-scan.d.ts +0 -16
- package/dist/sdk/history-mcp.d.ts +0 -17
- package/dist/sdk/lifecycle/checkpoint-rollback.d.ts +0 -15
- package/dist/sdk/lifecycle/core-field-recovery.d.ts +0 -33
- package/dist/sdk/lifecycle/core-item-fields.d.ts +0 -6
- package/dist/sdk/lifecycle/event-validation-messages.d.ts +0 -6
- package/dist/sdk/lifecycle/hierarchy-mutation-lock.d.ts +0 -15
- package/dist/sdk/lifecycle/legacy-none-tokens.d.ts +0 -71
- package/dist/sdk/lifecycle/mcp-actions.d.ts +0 -24
- package/dist/sdk/lifecycle/metadata-normalizers.d.ts +0 -8
- package/dist/sdk/lifecycle/mutation-facet-contracts.d.ts +0 -6
- package/dist/sdk/lifecycle/mutation-option-validation.d.ts +0 -2
- package/dist/sdk/lifecycle/recurrence-parsers.d.ts +0 -34
- package/dist/sdk/lifecycle/release-handoff.d.ts +0 -12
- package/dist/sdk/lifecycle/repeatable-metadata-parsers.d.ts +0 -18
- package/dist/sdk/lifecycle/repeated-terminal-state.d.ts +0 -45
- package/dist/sdk/merge/abandoned-receipts.d.ts +0 -15
- package/dist/sdk/merge/history-scalar-rebase.d.ts +0 -9
- package/dist/sdk/merge/ignored-artifacts.d.ts +0 -13
- package/dist/sdk/merge/indexed-receipt-blobs.d.ts +0 -4
- package/dist/sdk/merge/receipt-file-boundary.d.ts +0 -23
- package/dist/sdk/merge/settlement-hook.d.ts +0 -12
- package/dist/sdk/merge/stage.d.ts +0 -13
- package/dist/sdk/merge/worktree-config.d.ts +0 -11
- package/dist/sdk/query/light-metadata.d.ts +0 -3
- package/dist/sdk/query/window-pagination.d.ts +0 -20
- package/dist/sdk/read-output/extension.d.ts +0 -7
- package/dist/sdk/read-output/provenance.d.ts +0 -20
- package/dist/sdk/read-output/surfaces.d.ts +0 -27
- package/dist/sdk/runtime/actions.d.ts +0 -4
- package/dist/sdk/runtime/mutation-admission.d.ts +0 -2
- package/dist/sdk/runtime/mutation-value-validation.d.ts +0 -16
- package/dist/sdk/runtime/schema.d.ts +0 -4
- package/dist/sdk/runtime-action-aliases.d.ts +0 -7
- package/dist/sdk/runtime-extended-actions.d.ts +0 -27
- package/dist/sdk/runtime-stats-options.d.ts +0 -9
- package/dist/sdk/test/command-args.d.ts +0 -4
- package/dist/sdk/test/command-resolution.d.ts +0 -5
- package/dist/sdk/test/entry.d.ts +0 -18
- package/dist/sdk/test/execution-receipts.d.ts +0 -34
- package/dist/sdk/test/receipt-index-snapshot.d.ts +0 -2
- package/dist/sdk/test/workspace-snapshot.d.ts +0 -11
- package/dist/sdk/traceability/runtime-files-lookup.d.ts +0 -8
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { PmCliError,type PmCliErrorContext } from "../shared/errors.js";
|
|
1
2
|
import type { ItemDocument } from "../../types/index.js";
|
|
2
3
|
interface ItemMutationPrecondition {
|
|
3
4
|
pmRoot:string;
|
|
@@ -53,6 +54,17 @@ export declare function itemRevisionScopeReceipt(scope:ItemRevisionScope):{
|
|
|
53
54
|
checked:string[];
|
|
54
55
|
unchecked:string[];
|
|
55
56
|
};
|
|
57
|
+
/**
|
|
58
|
+
* Every revision the active scopes currently expect on this tracker, as
|
|
59
|
+
* `<id>=<hash>` guard values, so a refusal that prescribes a retry carries the
|
|
60
|
+
* same guards (`--expect-hash <id>=<hash>`) the refused operation ran under,
|
|
61
|
+
* including those on items it would write as a side effect (auto-unblocked
|
|
62
|
+
* dependents). Undefined when no single invocation can declare them: nested
|
|
63
|
+
* scopes expect different revisions of the same item, or a write inside the
|
|
64
|
+
* refused operation (a beforeCommand hook) advanced a guard past the revision
|
|
65
|
+
* its caller declared, so replaying the caller's own guard would conflict.
|
|
66
|
+
*/
|
|
67
|
+
export declare function activeItemRevisionExpectations(pmRoot:string):string[] | undefined;
|
|
56
68
|
/**
|
|
57
69
|
* Whether any active scope declared a revision on this tracker, so writers that
|
|
58
70
|
* must read a document to learn its embedded id can skip that read otherwise.
|
|
@@ -65,6 +77,52 @@ export declare function hasActiveItemRevisionScope(pmRoot:string):boolean;
|
|
|
65
77
|
* would write from. `current_revision` is the SHA-256 of the unreadable text.
|
|
66
78
|
*/
|
|
67
79
|
export declare function assertItemRevisionExpectationsOnUnreadable(pmRoot:string,targetId:string,raw:string):void;
|
|
80
|
+
/** `reason` of a revision refusal over a document that could be read and changed since the caller's read. */
|
|
81
|
+
export declare const ITEM_REVISION_CONFLICT_CHANGED_REASON = "revision_changed";
|
|
82
|
+
/** `reason` of a revision refusal over a live document that cannot be read at all. */
|
|
83
|
+
export declare const ITEM_REVISION_CONFLICT_UNREADABLE_REASON = "document_unreadable";
|
|
84
|
+
/**
|
|
85
|
+
* The invocation a revision refusal's read-only recovery commands must replay
|
|
86
|
+
* (pm-gh1677): the store layer never sees global options, so hosts that do
|
|
87
|
+
* re-render the commands with the caller's tracker scope and output mode.
|
|
88
|
+
*/
|
|
89
|
+
export interface ItemRevisionRecoveryInvocation {
|
|
90
|
+
/** Tracker and extension scope tokens, such as `--pm-path <root>` and `--no-extensions`. */
|
|
91
|
+
scopeArgs?:readonly string[];
|
|
92
|
+
/**
|
|
93
|
+
* Output-encoding tokens the recovery reads carry, such as `--json` or
|
|
94
|
+
* `--output-format toon`; empty for the tracker's default encoding.
|
|
95
|
+
* Defaults to `--json`, the machine-readable form.
|
|
96
|
+
*/
|
|
97
|
+
outputArgs?:readonly string[];
|
|
98
|
+
}
|
|
99
|
+
/** Recovery guidance fields of a revision refusal. */
|
|
100
|
+
export type ItemRevisionConflictGuidance = Required<Pick<PmCliErrorContext,"required" | "examples" | "nextSteps">>;
|
|
101
|
+
/**
|
|
102
|
+
* Render the read-only recovery of a revision refusal for one invocation. The
|
|
103
|
+
* commands only re-read the item; deciding again and retrying with a fresh
|
|
104
|
+
* `--expect-hash` stays with the caller, so the guard never writes on its own.
|
|
105
|
+
*/
|
|
106
|
+
export declare function itemRevisionConflictGuidance(targetId:string,unreadable:boolean,invocation?:ItemRevisionRecoveryInvocation):ItemRevisionConflictGuidance;
|
|
107
|
+
/**
|
|
108
|
+
* The canonical tracker whose locked write raised this revision refusal, or
|
|
109
|
+
* undefined for a refusal the guard did not raise itself. A wrapper that kept
|
|
110
|
+
* the refusal as its `cause` reports the refusal's tracker. Nested scopes use
|
|
111
|
+
* it so only the scope bound to that tracker re-renders the recovery.
|
|
112
|
+
*/
|
|
113
|
+
export declare function itemRevisionRefusalTracker(error:unknown):string | undefined;
|
|
114
|
+
/**
|
|
115
|
+
* Whether a revision refusal was raised by this tracker's guard. A refusal
|
|
116
|
+
* with no recorded tracker (one another producer built) is attributed to the
|
|
117
|
+
* caller's tracker, as before nested scopes were distinguished.
|
|
118
|
+
*/
|
|
119
|
+
export declare function isItemRevisionRefusalFrom(error:unknown,pmRoot:string):boolean;
|
|
120
|
+
/** Whether this refusal (or a refusal it wraps as `cause`) already carries invocation-scoped recovery. */
|
|
121
|
+
export declare function isItemRevisionRefusalScoped(error:unknown):boolean;
|
|
122
|
+
/** Record that a refusal's recovery was rendered for its own invocation. */
|
|
123
|
+
export declare function markItemRevisionRefusalScoped(error:PmCliError):PmCliError;
|
|
124
|
+
/** Keep a refusal's originating tracker, and whether it was scoped, on an error re-created from it. */
|
|
125
|
+
export declare function retainItemRevisionRefusalTracker(source:unknown,target:PmCliError):PmCliError;
|
|
68
126
|
/**
|
|
69
127
|
* Evaluate matching preconditions only after the item lock has been acquired
|
|
70
128
|
* and its document read. `targetId` names the locked item explicitly, so a
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="0d72cf82-14ea-573b-a36e-0077c82c0c1d")}catch{}})();import{AsyncLocalStorage}from"node:async_hooks";import{realpathSync}from"node:fs";import path from"node:path";import{hashDocument}from"../history/history.js";import{sha256Hex}from"../shared/serialization.js";import{renderPmCommand}from"../shared/command-line.js";import{EXIT_CODE}from"../shared/constants.js";import{PmCliError}from"../shared/errors.js";const preconditions=new AsyncLocalStorage;function runWithItemMutationPrecondition(condition,operation){return preconditions.run([...preconditions.getStore()??[],{...condition,pmRoot:path.resolve(condition.pmRoot)}],operation)}const REVISION_SCOPES_KEY=Symbol.for("@unbrained/pm-cli/item-revision-scopes"),revisionScopeRegistry=globalThis,revisionScopes=revisionScopeRegistry[REVISION_SCOPES_KEY]??=new AsyncLocalStorage;function canonicalTrackerRoot(pmRoot){const resolved=path.resolve(pmRoot);try{return realpathSync.native(resolved)}catch{return resolved}}function createItemRevisionScope(){return{entries:new Map}}function runWithItemRevisionScope(scope,operation){return revisionScopes.run([...revisionScopes.getStore()??[],scope],operation)}function bindItemRevisionScope(scope,pmRoot,expectations){const resolvedRoot=canonicalTrackerRoot(pmRoot);if(scope.pmRoot!==void 0&&scope.pmRoot!==resolvedRoot)throw new PmCliError("An expected-revision scope is already bound to another tracker.",EXIT_CODE.USAGE,{code:"expected_revision_scope_conflict",required:"Bind expected item revisions for one tracker per scope."});scope.pmRoot=resolvedRoot;for(const{id,itemHash}of expectations){const existing=scope.entries.get(id);if(existing!==void 0&&existing.declared!==itemHash)throw new PmCliError(`Item ${id} has two different expected revisions.`,EXIT_CODE.USAGE,{code:"expected_revision_duplicate",item_id:id,required:"Declare at most one expected revision per item."});scope.entries.set(id,existing??{declared:itemHash,expected:itemHash,checked:!1,committed:!1})}}function itemRevisionScopeReceipt(scope){const entries=[...scope.entries.entries()];return{checked:entries.filter(([,entry])=>entry.checked).map(([id])=>id),unchecked:entries.filter(([,entry])=>!entry.checked).map(([id])=>id)}}function matchingRevisionEntries(pmRoot,ids){const scopes=revisionScopes.getStore()??[];if(scopes.length===0)return[];const resolvedRoot=canonicalTrackerRoot(pmRoot),keys=new Set(ids.filter(id=>typeof id=="string"));return[...new Set(scopes.flatMap(scope=>scope.pmRoot===resolvedRoot?[...keys].flatMap(key=>scope.entries.get(key)??[]):[]))]}function activeItemRevisionExpectations(pmRoot){const scopes=revisionScopes.getStore()??[];if(scopes.length===0)return[];const resolvedRoot=canonicalTrackerRoot(pmRoot),expected=new Map;for(const scope of scopes)if(scope.pmRoot===resolvedRoot)for(const[id,entry]of scope.entries){if(entry.expected!==entry.declared)return;expected.set(id,(expected.get(id)??new Set).add(entry.expected))}if(![...expected.values()].some(hashes=>hashes.size>1))return[...expected].map(([id,hashes])=>`${id}=${[...hashes][0]}`)}function hasActiveItemRevisionScope(pmRoot){const resolvedRoot=canonicalTrackerRoot(pmRoot);return(revisionScopes.getStore()??[]).some(scope=>scope.pmRoot===resolvedRoot&&scope.entries.size>0)}function assertItemRevisionExpectations(pmRoot,document,targetId){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id]);entries.length>0&&assertRevisionEntries(entries,targetId,hashDocument(document),!1,pmRoot)}function assertItemRevisionExpectationsOnUnreadable(pmRoot,targetId,raw){const entries=matchingRevisionEntries(pmRoot,[targetId]);entries.length>0&&assertRevisionEntries(entries,targetId,sha256Hex(raw),!0,pmRoot)}const ITEM_REVISION_CONFLICT_CHANGED_REASON="revision_changed",ITEM_REVISION_CONFLICT_UNREADABLE_REASON="document_unreadable";function itemRevisionConflictGuidance(targetId,unreadable,invocation={}){const scope=[...invocation.scopeArgs??[]],output=[...invocation.outputArgs??["--json"]],read=renderPmCommand([...scope,"get",targetId,...output]),history=renderPmCommand([...scope,"history",targetId,"--limit","5",...output]);return{required:unreadable?`Recover ${targetId} without --expect-hash (${renderPmCommand([...scope,"restore",targetId,"<version>"])}), since no declared revision describes an unreadable document.`:`Re-read ${targetId} (${read} reports item_hash), decide again against the current revision, then retry with --expect-hash <item_hash>.`,examples:[renderPmCommand([...scope,"get",targetId,"--fields","item_hash",...output]),history],nextSteps:[read,history]}}const REFUSAL_TRACKERS_KEY=Symbol.for("@unbrained/pm-cli/item-revision-refusal-trackers"),refusalTrackerRegistry=globalThis,refusalTrackers=refusalTrackerRegistry[REFUSAL_TRACKERS_KEY]??=new WeakMap,REFUSAL_CAUSE_DEPTH=8;function itemRevisionRefusalTracker(error){for(const link of refusalCauseChain(error)){const tracker=refusalTrackers.get(link);if(tracker!==void 0)return tracker}}function*refusalCauseChain(error){let current=error;for(let depth=0;depth<REFUSAL_CAUSE_DEPTH&&typeof current=="object"&¤t!==null;depth+=1){yield current;try{current=current.cause}catch{return}}}function assertRevisionEntries(entries,targetId,current,unreadable,pmRoot){for(const entry of entries)if(entry.checked=!0,!(!unreadable&&entry.expected===current))throw trackRefusal(pmRoot,new PmCliError(`Item ${targetId} is no longer at the expected revision ${entry.expected.slice(0,12)}${unreadable?" (its live document cannot be read)":""}; refusing to write over a revision this decision did not see.${entry.committed?" Earlier writes by this same invocation already committed.":" Nothing was written to this item."}`,EXIT_CODE.CONFLICT,{code:"item_revision_conflict",item_id:targetId,expected_revision:entry.expected,current_revision:current,reason:unreadable?ITEM_REVISION_CONFLICT_UNREADABLE_REASON:ITEM_REVISION_CONFLICT_CHANGED_REASON,why:"The caller declared the revision its decision was based on, and another write changed the item before this locked write.",...itemRevisionConflictGuidance(targetId,unreadable)}))}function isItemRevisionRefusalFrom(error,pmRoot){const tracker=itemRevisionRefusalTracker(error);return tracker===void 0||tracker===canonicalTrackerRoot(pmRoot)}const SCOPED_REFUSALS_KEY=Symbol.for("@unbrained/pm-cli/item-revision-scoped-refusals"),scopedRefusalRegistry=globalThis,scopedRefusals=scopedRefusalRegistry[SCOPED_REFUSALS_KEY]??=new WeakSet;function isItemRevisionRefusalScoped(error){for(const link of refusalCauseChain(error))if(scopedRefusals.has(link))return!0;return!1}function markItemRevisionRefusalScoped(error){return scopedRefusals.add(error),error}function retainItemRevisionRefusalTracker(source,target){const tracker=itemRevisionRefusalTracker(source);return tracker!==void 0&&refusalTrackers.set(target,tracker),isItemRevisionRefusalScoped(source)&&scopedRefusals.add(target),target}function trackRefusal(pmRoot,error){return refusalTrackers.set(error,canonicalTrackerRoot(pmRoot)),error}function assertItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id){assertItemRevisionExpectations(pmRoot,document,targetId);for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id]))condition.validate(document)}function conditionsFor(pmRoot,ids){const resolvedRoot=path.resolve(pmRoot);return(preconditions.getStore()??[]).filter(condition=>condition.pmRoot===resolvedRoot&&ids.includes(condition.id))}function advanceItemMutationPreconditions(pmRoot,document,targetId=document.metadata.id,aliasIds=[],revision){const entries=matchingRevisionEntries(pmRoot,[targetId,document.metadata.id,...aliasIds]);if(entries.length>0){const committed=revision??hashDocument(document);for(const entry of entries)entry.expected=committed,entry.committed=!0}for(const condition of conditionsFor(pmRoot,[targetId,document.metadata.id,...aliasIds]))condition.committed?.(document)}function itemMutationPreconditionHistoryContext(pmRoot,ids){return Object.assign({},...conditionsFor(pmRoot,ids).map(condition=>condition.historyContext))}export{ITEM_REVISION_CONFLICT_CHANGED_REASON,ITEM_REVISION_CONFLICT_UNREADABLE_REASON,activeItemRevisionExpectations,advanceItemMutationPreconditions,assertItemMutationPreconditions,assertItemRevisionExpectationsOnUnreadable,bindItemRevisionScope,createItemRevisionScope,hasActiveItemRevisionScope,isItemRevisionRefusalFrom,isItemRevisionRefusalScoped,itemMutationPreconditionHistoryContext,itemRevisionConflictGuidance,itemRevisionRefusalTracker,itemRevisionScopeReceipt,markItemRevisionRefusalScoped,retainItemRevisionRefusalTracker,runWithItemMutationPrecondition,runWithItemRevisionScope};
|
|
2
2
|
//# sourceMappingURL=item-mutation-precondition.js.map
|
|
@@ -3,7 +3,11 @@ export { quoteWindowsCommandArg,quoteCommandArg,renderPmCommand } from "../core/
|
|
|
3
3
|
type CommandScope = Pick<GlobalOptions,"path" | "noExtensions">;
|
|
4
4
|
/** Retain caller scope before runtime dispatch resolves its working storage path. */
|
|
5
5
|
export declare function capturePmCommandScope(options:CommandScope):void;
|
|
6
|
-
/**
|
|
6
|
+
/**
|
|
7
|
+
* Build copy-safe tracker and extension arguments, preserving explicit spelling and omitting the implicit cwd tracker.
|
|
8
|
+
* A blank typed tracker (empty or whitespace-only) is not an explicit selection: tracker resolution trims it and
|
|
9
|
+
* defers to PM_PATH, so the arguments name the environment's tracker the invocation actually used (pm-gh1677).
|
|
10
|
+
*/
|
|
7
11
|
export declare function resolvePmCommandScopeArgs(options:CommandScope,cwd?:string):string[];
|
|
8
12
|
/** Recognize the leading redaction command after global options, even before flag validation succeeds. */
|
|
9
13
|
export declare function isHistoryRedactInvocation(argv:readonly string[]):boolean;
|
package/dist/sdk/command-line.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="7710bf5a-cea2-5fc5-8017-20e8845238e4")}catch{}})();import{findBootstrapCommandTokenIndex}from"./cli-contracts/bootstrap-command-scanner.js";import path from"node:path";import{resolveImplicitPmRoot,resolvePmRoot,resolveWorkspaceRoot}from"../core/store/paths.js";import{isPathWithinDirectory}from"../core/fs/path-utils.js";import{quoteWindowsCommandArg,quoteCommandArg,renderPmCommand}from"../core/shared/command-line.js";const requestedPaths=new WeakMap;function capturePmCommandScope(options){requestedPaths.set(options,options.path)}function environmentCommandScope(cwd){if(!process.env.PM_PATH?.trim())return;const resolved=resolvePmRoot(cwd);return isPathWithinDirectory(resolveWorkspaceRoot(resolved),cwd)&&resolved===resolveImplicitPmRoot(cwd)?void 0:path.relative(cwd,resolved)||"."}function resolvePmCommandScopeArgs(options,cwd=process.cwd()){const requested=requestedPaths.has(options)?requestedPaths.get(options):options.path,selected=requested?.trim()?requested:environmentCommandScope(cwd),args=selected?["--pm-path",selected]:[];return options.noExtensions&&args.push("--no-extensions"),args}const HISTORY_REDACT_SENSITIVE_FLAGS=new Set(["--literal","--regex","--replacement"]);function isHistoryRedactInvocation(argv){const rootIndex=findBootstrapCommandTokenIndex(argv);if(rootIndex===void 0)return!1;if(argv[rootIndex]==="history-redact")return!0;if(argv[rootIndex]!=="history")return!1;const operationArgs=argv.slice(rootIndex+1),operationIndex=findBootstrapCommandTokenIndex(operationArgs);return operationIndex!==void 0&&operationArgs[operationIndex]==="redact"}function redactSensitiveCommandArgs(argv){if(!isHistoryRedactInvocation(argv))return[...argv];const redacted=[];let redactNext=!1;for(const token of argv){if(redactNext){redacted.push("[redacted]"),redactNext=!1;continue}redactNext=!1;const equalsIndex=token.indexOf("="),flag=equalsIndex>=0?token.slice(0,equalsIndex):token;if(!HISTORY_REDACT_SENSITIVE_FLAGS.has(flag)){redacted.push(token);continue}if(equalsIndex>=0){redacted.push(`${flag}=[redacted]`);continue}redacted.push(flag),redactNext=!0}return redacted}export{capturePmCommandScope,isHistoryRedactInvocation,quoteCommandArg,quoteWindowsCommandArg,redactSensitiveCommandArgs,renderPmCommand,resolvePmCommandScopeArgs};
|
|
2
2
|
//# sourceMappingURL=command-line.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="1ae551f9-53e5-5f63-a6a2-231a40c61c62")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{enrichItemRevisionConflict,isItemRevisionConflict,itemRevisionConflictRowFields}from"./item-revision.js";import{toErrorMessage}from"../runtime-primitives.js";import{toItemRecord,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveIsoOrRelative,shouldCompletePlanOnClose,getActiveExtensionRegistrations}from"../runtime-primitives.js";import{collectBlockedByIds,indexBlockedByIds}from"../actionability.js";import{applyTerminalOrderingPolicy,requireTerminalReason}from"../lifecycle-policy.js";import{nowIso}from"../../core/shared/time.js";import{isPmCliErrorDetails}from"../../core/shared/error-details.js";import{unicodeSafePrefix}from"../../core/shared/text-normalization.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"../command-line.js";import{mutateItemWithHistoryContextResolver}from"../../core/store/item-store.js";const CLOSE_VALIDATION_FIELDS=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function parseValidateCloseMode(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized.length===0||normalized==="warn")return"warn";if(normalized==="off"||normalized==="none"||normalized==="disabled")return"off";if(normalized==="strict")return"strict";throw new PmCliError(`Invalid --validate-close mode "${raw}" (expected "off", "warn", or "strict")`,EXIT_CODE.USAGE)}function findMissingCloseValidationFields(itemMetadata){const missing=[];for(const field of CLOSE_VALIDATION_FIELDS){const rawValue=itemMetadata[field.key];(typeof rawValue!="string"||rawValue.trim().length===0)&&missing.push(field)}return missing}function closeEvidenceRecovery(metadata,commandScope,options={}){const missing=findMissingCloseValidationFields(metadata);if(missing.length===0)return;const values={resolution:options.resolution,expected_result:options.expectedResult,actual_result:options.actualResult},missingFlags=missing.map(field=>`--${field.key.replaceAll("_","-")}`),args=[...commandScope,"update",metadata.id,...missing.flatMap((field,index)=>[missingFlags[index],values[field.key]?.trim()||"<value>"])];return{missing:missingFlags,suggested_retry:renderPmCommand(args),suggested_retry_args:args}}async function duplicateChainReferencesClosingItem(loadItemById,initialDuplicateOf,closingId){const visited=new Set;let current=initialDuplicateOf;for(;typeof current=="string"&¤t.trim().length>0;){const currentId=current.trim();if(currentId===closingId)return!0;if(visited.has(currentId))return!1;visited.add(currentId),current=(await loadItemById(currentId))?.duplicate_of}return!1}function shouldApplyDuplicateFallback(value){return typeof value!="string"||value.trim().length===0}async function assertDuplicateTargetExists(pmRoot,settings,duplicateOf,closingId){const rawTarget=duplicateOf?.trim();if(!rawTarget)return;if(rawTarget===closingId)throw new PmCliError("An item cannot be closed as a duplicate of itself.",EXIT_CODE.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),itemCache=new Map,loadItemById=async id=>{if(itemCache.has(id))return itemCache.get(id)??null;const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)return itemCache.set(id,null),null;const{document}=await readLocatedItem(located,{schema:settings.schema});return itemCache.set(id,document.metadata),document.metadata},target=await loadItemById(rawTarget);if(!target)throw new PmCliError(`Duplicate target "${rawTarget}" was not found. Create or locate the canonical item first.`,EXIT_CODE.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${closingId} "Duplicate of ${rawTarget}" --duplicate-of ${rawTarget}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await duplicateChainReferencesClosingItem(loadItemById,target.duplicate_of,closingId))throw new PmCliError(`Circular duplicate reference detected. Target "${rawTarget}" points back to "${closingId}".`,EXIT_CODE.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof target.duplicate_of=="string"&&target.duplicate_of.trim().length>0)throw new PmCliError(`Duplicate target "${rawTarget}" is already marked as a duplicate of "${target.duplicate_of.trim()}".`,EXIT_CODE.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${closingId} "Duplicate of ${target.duplicate_of.trim()}" --duplicate-of ${target.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return target.id}function findActiveChildIds(items,parentId,statusRegistry){return items.filter(item=>item.parent===parentId&&!isTerminalStatus(item.status,statusRegistry)).map(item=>item.id).sort((left,right)=>left.localeCompare(right))}function findAutoUnblockCandidates(items,closedId,statusRegistry){const itemsById=new Map(items.map(item=>[item.id.trim().toLowerCase(),item])),blockerIdsByItem=indexBlockedByIds(items),normalizedClosedId=closedId.trim().toLowerCase(),blockedStatuses=statusRegistry.blocked_statuses;return items.filter(item=>blockedStatuses.has(item.status)).map(item=>({item,blockerIds:blockerIdsByItem.get(item.id.trim().toLowerCase())})).filter(({blockerIds})=>blockerIds.includes(normalizedClosedId)).filter(({blockerIds})=>blockerIds.every(blockerId=>{if(blockerId===normalizedClosedId)return!0;const blocker=itemsById.get(blockerId);return blocker!==void 0&&isTerminalStatus(blocker.status,statusRegistry)})).map(({item,blockerIds})=>({id:item.id,blocker_ids:blockerIds})).sort((left,right)=>left.id.localeCompare(right.id))}async function autoUnblockResolvedDependents(pmRoot,settings,items,closedId,author,statusRegistry,commandScope){const candidates=findAutoUnblockCandidates(items,closedId,statusRegistry),warnings=[],unblockedIds=[],conflictIds=[],failed=[];let conflict;for(const candidate of candidates)try{const unblocked=await mutateItem({pmRoot,settings,id:candidate.id,op:"update",author,message:`Auto-unblocked after blocker ${closedId} closed`,mutate(document){const dependencies=document.metadata.dependencies??[],remainingDependencies=dependencies.filter(dependency=>{const dependencyId=dependency.id.trim().toLowerCase();return dependency.kind!=="blocked_by"||!candidate.blocker_ids.includes(dependencyId)});document.metadata.status=statusRegistry.open_status,delete document.metadata.blocked_by,delete document.metadata.blocked_reason,document.metadata.unblock_note=`Auto-unblocked after blocker ${closedId} closed; all blockers resolved (${candidate.blocker_ids.join(", ")}).`,remainingDependencies.length>0?document.metadata.dependencies=remainingDependencies:delete document.metadata.dependencies;const changedFields=["status","blocked_by","blocked_reason","unblock_note"];return remainingDependencies.length!==dependencies.length&&changedFields.push("dependencies"),{changedFields}}});warnings.push(`auto_unblocked:${unblocked.item.id}:resolved_blockers=${candidate.blocker_ids.join(",")}`),unblockedIds.push(unblocked.item.id)}catch(error){const reason=error instanceof Error?error.message.replace(/\s+/g," ").trim():"unknown";isItemRevisionConflict(error)?(conflict??=error,conflictIds.push(candidate.id)):failed.push({id:candidate.id,reason}),warnings.push(`auto_unblock_failed:${candidate.id}:${reason}`)}if(conflict!==void 0){const enriched=await enrichItemRevisionConflict(conflict,pmRoot),blockedStatuses=[...statusRegistry.blocked_statuses].sort().join(",");throw postCloseDependentConflict(enriched,{closedId,unblockedIds,conflictIds,failed,openStatus:statusRegistry.open_status,blockedStatuses,commandScope})}return warnings}const POST_CLOSE_REPORT_LIMIT=10,POST_CLOSE_STEP_LIMIT=20,POST_CLOSE_DETAIL_TRIMS=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function fitPostCloseDetails(details){for(const trim of POST_CLOSE_DETAIL_TRIMS){const list=details[trim.list];if(Array.isArray(list))for(;list.length>trim.floor&&!isPmCliErrorDetails(details);)list.pop(),Reflect.set(details,trim.omitted,Number(details[trim.omitted])+1)}return details}function boundedIdList(ids){const omitted=ids.length-POST_CLOSE_REPORT_LIMIT;return`${ids.slice(0,POST_CLOSE_REPORT_LIMIT).join(", ")}${omitted>0?`, and ${omitted} more`:""}`}function postCloseDependentConflict(conflict,fanOut){const{closedId,conflictIds,failed,commandScope}=fanOut,dependent=String(conflict.context.item_id),unblock=id=>renderPmCommand([...commandScope,"update",id,"--status",fanOut.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${id}=<item_hash>`]),reported=failed.slice(0,POST_CLOSE_REPORT_LIMIT).map(entry=>({id:entry.id,reason:unicodeSafePrefix(entry.reason,160)})),otherFailures=failed.length===0?"":` Auto-unblocking also failed for ${boundedIdList(failed.map(entry=>entry.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,discovery=renderPmCommand([...commandScope,"list","--status",fanOut.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),allSteps=[...conflictIds.slice(0,POST_CLOSE_REPORT_LIMIT).flatMap(id=>[renderPmCommand([...commandScope,"get",id,"--json"]),unblock(id)]),...reported.map(entry=>renderPmCommand([...commandScope,"get",entry.id,"--json"]))],truncated=conflictIds.length>POST_CLOSE_REPORT_LIMIT||failed.length>POST_CLOSE_REPORT_LIMIT||allSteps.length>POST_CLOSE_STEP_LIMIT,steps=allSteps.slice(0,truncated?POST_CLOSE_STEP_LIMIT-1:POST_CLOSE_STEP_LIMIT);return new PmCliError(`${closedId} was closed, but auto-unblocking ${dependent} was refused. ${conflict.message}`,conflict.exitCode,{...conflict.context,required:`The close of ${closedId} is complete; do not retry it. Only unblocking ${conflictIds.length===1?dependent:`the guarded dependents it refused (${boundedIdList(conflictIds)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${unblock(dependent)}${conflictIds.length===1?"":" for each id"}.${otherFailures}${truncated?` This refusal does not list a step for every dependent left blocked; list them with ${discovery}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:truncated?[...steps,discovery]:steps,details:fitPostCloseDetails({...structuredClone(conflict.context.details),pending_unblock:conflictIds.slice(0,POST_CLOSE_REPORT_LIMIT),pending_unblock_omitted:Math.max(0,conflictIds.length-POST_CLOSE_REPORT_LIMIT),auto_unblock_failed:reported,auto_unblock_failed_omitted:Math.max(0,failed.length-POST_CLOSE_REPORT_LIMIT)}),side_effects:[{path:`history/${closedId}.jsonl`,op:"close"},...fanOut.unblockedIds.map(id=>({path:`history/${id}.jsonl`,op:"update"}))]})}async function committedCloseDependentConflict(error,id,pmRoot){if(!isItemRevisionConflict(error)||!error.context.side_effects?.some(effect=>`${effect.op}:${effect.path}`==`close:history/${id}.jsonl`))return;const dependent=String(error.context.item_id);return{warnings:[...error.context.side_effects.filter(effect=>effect.op==="update").map(effect=>effect.path.slice(8,-6)).map(unblockedId=>`auto_unblocked:${unblockedId}`),`auto_unblock_refused:${dependent}:item_revision_conflict`],dependent_revision_conflict:{item_id:dependent,error:toErrorMessage(error),...await itemRevisionConflictRowFields(error,pmRoot)}}}function applyInlineCloseFields(metadata,options){const changedFields=[],inlineCloseFields=[{option:options.resolution,key:"resolution"},{option:options.expectedResult,key:"expected_result"},{option:options.actualResult,key:"actual_result"}];for(const{option,key}of inlineCloseFields){if(typeof option!="string")continue;const trimmed=option.trim();trimmed.length!==0&&(metadata[key]=trimmed,changedFields.push(key))}return changedFields}function applyDuplicateCloseMetadata(metadata,duplicateOf){if(duplicateOf===void 0)return[];metadata.duplicate_of=duplicateOf;const duplicateFallbackFields=[],fallbackValues=[{key:"resolution",value:`Duplicate of ${duplicateOf}`},{key:"expected_result",value:`Canonical item ${duplicateOf} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${duplicateOf}.`}];for(const{key,value}of fallbackValues)shouldApplyDuplicateFallback(metadata[key])&&(metadata[key]=value,duplicateFallbackFields.push(key));return duplicateFallbackFields}function collectCloseValidationWarnings(metadata,validateCloseMode,activeChildIds,commandScope){const warnings=[];if(validateCloseMode!=="off"){const missingFields=findMissingCloseValidationFields(metadata);if(missingFields.length>0){const missingLabels=missingFields.map(field=>field.label);if(validateCloseMode==="strict"){const missingFlags=missingFields.map(field=>`--${field.key.replaceAll("_","-")}`),updateTokens=[...commandScope,"update",metadata.id,...missingFlags.flatMap(flag=>[flag,"<value>"])];throw new PmCliError(`Cannot close item ${metadata.id}: missing ${missingLabels.join(", ")}. Populate fields or use --validate-close warn.`,EXIT_CODE.USAGE,{code:"close_validation_missing_fields",recovery:{missing:missingFlags,suggested_retry:renderPmCommand(updateTokens),suggested_retry_args:updateTokens},nextSteps:["Run the suggested pm update, then retry the original pm close invocation.","Use --validate-close warn only when governance permits an evidenced exception."]})}warnings.push(`close_validation_missing_fields:${metadata.id}:${missingLabels.join(",")}`)}if(activeChildIds.length>0){if(validateCloseMode==="strict")throw new PmCliError(`Cannot close item ${metadata.id}: active child items remain open (${activeChildIds.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,EXIT_CODE.USAGE);warnings.push(`close_validation_active_children:${metadata.id}:${activeChildIds.join(",")}`)}return warnings}return activeChildIds.length>0&&warnings.push(`closed_with_active_children:${metadata.id}:${activeChildIds.join(",")}`),warnings}function applyCloseReason(metadata,closeReason){return closeReason!==void 0?(metadata.close_reason=closeReason,["close_reason"]):[]}function clearCloseAssignee(metadata){const cleared=["assignee","claim_principal"].filter(key=>metadata[key]!==void 0);for(const key of cleared)delete metadata[key];return[...cleared]}function mutateCloseMetadata(metadata,context){if(isTerminalStatus(metadata.status,context.statusRegistry)&&!context.force)throw new PmCliError(`Item ${metadata.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,EXIT_CODE.CONFLICT,{recovery:closeEvidenceRecovery(metadata,context.commandScope,context.options)});const inlineChangedFields=applyInlineCloseFields(metadata,context.options),duplicateFallbackFields=applyDuplicateCloseMetadata(metadata,context.duplicateOf),mutationWarnings=collectCloseValidationWarnings(metadata,context.validateCloseMode,context.activeChildIds,context.commandScope);metadata.status=context.statusRegistry.close_status,metadata.closed_at=context.closedAt;const shouldWriteCompletedAt=context.options.completedAt!==void 0||metadata.completed_at===void 0;shouldWriteCompletedAt&&(metadata.completed_at=context.completedAt);const changedFields=["status","closed_at",...shouldWriteCompletedAt?["completed_at"]:[],...applyCloseReason(metadata,context.closeReason),...inlineChangedFields];if(shouldCompletePlanOnClose(metadata)&&(metadata.plan_mode="completed",changedFields.push("plan_mode")),context.duplicateOf!==void 0){changedFields.push("duplicate_of");for(const key of duplicateFallbackFields)changedFields.includes(key)||changedFields.push(key)}changedFields.push(...clearCloseAssignee(metadata));const blockerCleanup=applyTerminalOrderingPolicy(metadata,context.lifecyclePolicy);return changedFields.push(...blockerCleanup.changedFields),mutationWarnings.push(...blockerCleanup.warnings),{changedFields,...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}const _testOnlyCloseCommand={blockedByIds:collectBlockedByIds,fitPostCloseDetails};async function closeItem(id,closeReasonText,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),commandScope=resolvePmCommandScopeArgs(global2);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder);const duplicateOf=await assertDuplicateTargetExists(pmRoot,settings,options.duplicateOf,located.id),lifecyclePolicy={requireCloseReason:options.lifecyclePolicy?.requireCloseReason??settings.governance.require_close_reason,orderingEdges:options.lifecyclePolicy?.orderingEdges??"preserve"},closeReason=requireTerminalReason({explicit:closeReasonText,duplicateOf,resolution:options.resolution,message:options.message},lifecyclePolicy.requireCloseReason).closeReason,validateCloseMode=parseValidateCloseMode(options.validateClose)??settings.governance.close_validation_default,trackerItems=await listAllItemMetadataLight(pmRoot,settings.item_format,typeToFolder,void 0,settings.schema),activeChildIds=findActiveChildIds(trackerItems,located.id,statusRegistry),closedAt=nowIso(),completedAt=options.completedAt===void 0?closedAt:resolveIsoOrRelative(options.completedAt,new Date(closedAt),"completed-at");let completion={timestamp:completedAt,source:options.completedAt===void 0?"close_time":"asserted",...options.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${renderPmCommand([...commandScope,"update",located.id,"--completed-at","<ISO>"])}.`}:{}};const result=await mutateItemWithHistoryContextResolver({pmRoot,settings,id:located.id,op:"close",author,message:options.message,force:options.force,resolveHistoryContext:()=>({completion:{timestamp:completion.timestamp,source:completion.source}}),mutate(document){return options.completedAt===void 0&&document.metadata.completed_at!==void 0&&(completion={timestamp:document.metadata.completed_at,source:"existing"}),mutateCloseMetadata(document.metadata,{pmRoot,commandScope,statusRegistry,force:options.force,options,duplicateOf,validateCloseMode,activeChildIds,closeReason,closedAt,completedAt,lifecyclePolicy})}}),evidence=validateCloseMode==="warn"?closeEvidenceRecovery(result.item,commandScope):void 0;return{item:toItemRecord(result.item),changed_fields:result.changedFields,...evidence?{follow_up:{kind:"complete_close_evidence",missing:evidence.missing,suggested_command:evidence.suggested_retry,suggested_command_args:evidence.suggested_retry_args}}:{},warnings:[...result.warnings,...await autoUnblockResolvedDependents(pmRoot,settings,trackerItems,located.id,author,statusRegistry,commandScope)],completion}}function runClose(id,closeReasonText,options,global2){return closeItem(id,closeReasonText,options,global2)}export{_testOnlyCloseCommand,closeItem,committedCloseDependentConflict,runClose};
|
|
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]="7d2d8230-afd3-5f97-b1f6-110264b520eb")}catch{}})();import{assertInitializedTracker}from"../environment/tracker-preflight.js";import{enrichItemRevisionConflict,isItemRevisionConflict,itemRevisionConflictRowFields}from"./item-revision.js";import{toErrorMessage}from"../runtime-primitives.js";import{toItemRecord,isTerminalStatus,resolveItemTypeRegistry,resolveRuntimeStatusRegistry,EXIT_CODE,PmCliError,buildItemNotFoundError,listAllItemMetadataLight,locateItem,readLocatedItem,mutateItem,resolvePmRoot,readSettings,resolveAuthor,resolveIsoOrRelative,shouldCompletePlanOnClose,getActiveExtensionRegistrations}from"../runtime-primitives.js";import{collectBlockedByIds,indexBlockedByIds}from"../actionability.js";import{applyTerminalOrderingPolicy,requireTerminalReason}from"../lifecycle-policy.js";import{nowIso}from"../../core/shared/time.js";import{isPmCliErrorDetails}from"../../core/shared/error-details.js";import{unicodeSafePrefix}from"../../core/shared/text-normalization.js";import{renderPmCommand,resolvePmCommandScopeArgs}from"../command-line.js";import{mutateItemWithHistoryContextResolver}from"../../core/store/item-store.js";import{activeItemRevisionExpectations,itemRevisionConflictGuidance}from"../../core/store/item-mutation-precondition.js";const CLOSE_VALIDATION_FIELDS=[{key:"resolution",label:"resolution (--resolution)"},{key:"expected_result",label:"expected_result (--expected-result)"},{key:"actual_result",label:"actual_result (--actual-result)"}];function parseValidateCloseMode(raw){if(raw===void 0)return;const normalized=raw.trim().toLowerCase();if(normalized.length===0||normalized==="warn")return"warn";if(normalized==="off"||normalized==="none"||normalized==="disabled")return"off";if(normalized==="strict")return"strict";throw new PmCliError(`Invalid --validate-close mode "${raw}" (expected "off", "warn", or "strict")`,EXIT_CODE.USAGE)}function findMissingCloseValidationFields(itemMetadata){const missing=[];for(const field of CLOSE_VALIDATION_FIELDS){const rawValue=itemMetadata[field.key];(typeof rawValue!="string"||rawValue.trim().length===0)&&missing.push(field)}return missing}function closeEvidenceRecovery(metadata,commandScope,options={}){const missing=findMissingCloseValidationFields(metadata);if(missing.length===0)return;const values={resolution:options.resolution,expected_result:options.expectedResult,actual_result:options.actualResult},missingFlags=missing.map(field=>`--${field.key.replaceAll("_","-")}`),args=[...commandScope,"update",metadata.id,...missing.flatMap((field,index)=>[missingFlags[index],values[field.key]?.trim()||"<value>"])];return{missing:missingFlags,suggested_retry:renderPmCommand(args),suggested_retry_args:args}}async function duplicateChainReferencesClosingItem(loadItemById,initialDuplicateOf,closingId){const visited=new Set;let current=initialDuplicateOf;for(;typeof current=="string"&¤t.trim().length>0;){const currentId=current.trim();if(currentId===closingId)return!0;if(visited.has(currentId))return!1;visited.add(currentId),current=(await loadItemById(currentId))?.duplicate_of}return!1}function shouldApplyDuplicateFallback(value){return typeof value!="string"||value.trim().length===0}async function assertDuplicateTargetExists(pmRoot,settings,duplicateOf,closingId){const rawTarget=duplicateOf?.trim();if(!rawTarget)return;if(rawTarget===closingId)throw new PmCliError("An item cannot be closed as a duplicate of itself.",EXIT_CODE.USAGE,{code:"duplicate_target_self",why:"--duplicate-of must identify the canonical item that should remain open or already represent the work."});const typeRegistry=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()),itemCache=new Map,loadItemById=async id=>{if(itemCache.has(id))return itemCache.get(id)??null;const located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeRegistry.type_to_folder);if(!located)return itemCache.set(id,null),null;const{document}=await readLocatedItem(located,{schema:settings.schema});return itemCache.set(id,document.metadata),document.metadata},target=await loadItemById(rawTarget);if(!target)throw new PmCliError(`Duplicate target "${rawTarget}" was not found. Create or locate the canonical item first.`,EXIT_CODE.USAGE,{code:"duplicate_target_missing",why:"Duplicate closure should point at a real canonical pm item so future dedupe and changelog tooling can trace the relationship.",examples:[`pm close ${closingId} "Duplicate of ${rawTarget}" --duplicate-of ${rawTarget}`],nextSteps:["Run pm search/list to find the canonical item, then retry with --duplicate-of <id>."]});if(await duplicateChainReferencesClosingItem(loadItemById,target.duplicate_of,closingId))throw new PmCliError(`Circular duplicate reference detected. Target "${rawTarget}" points back to "${closingId}".`,EXIT_CODE.USAGE,{code:"duplicate_target_circular",why:"Circular duplicate relationships create loops for dedupe and status propagation tooling.",nextSteps:["Choose the existing canonical item, or clear the target duplicate_of metadata before closing this item as a duplicate."]});if(typeof target.duplicate_of=="string"&&target.duplicate_of.trim().length>0)throw new PmCliError(`Duplicate target "${rawTarget}" is already marked as a duplicate of "${target.duplicate_of.trim()}".`,EXIT_CODE.USAGE,{code:"duplicate_target_is_duplicate",why:"Duplicate closure should point directly at the canonical item, not another duplicate.",examples:[`pm close ${closingId} "Duplicate of ${target.duplicate_of.trim()}" --duplicate-of ${target.duplicate_of.trim()}`],nextSteps:["Use the canonical item referenced by duplicate_of as the --duplicate-of target."]});return target.id}function findActiveChildIds(items,parentId,statusRegistry){return items.filter(item=>item.parent===parentId&&!isTerminalStatus(item.status,statusRegistry)).map(item=>item.id).sort((left,right)=>left.localeCompare(right))}function findAutoUnblockCandidates(items,closedId,statusRegistry){const itemsById=new Map(items.map(item=>[item.id.trim().toLowerCase(),item])),blockerIdsByItem=indexBlockedByIds(items),normalizedClosedId=closedId.trim().toLowerCase(),blockedStatuses=statusRegistry.blocked_statuses;return items.filter(item=>blockedStatuses.has(item.status)).map(item=>({item,blockerIds:blockerIdsByItem.get(item.id.trim().toLowerCase())})).filter(({blockerIds})=>blockerIds.includes(normalizedClosedId)).filter(({blockerIds})=>blockerIds.every(blockerId=>{if(blockerId===normalizedClosedId)return!0;const blocker=itemsById.get(blockerId);return blocker!==void 0&&isTerminalStatus(blocker.status,statusRegistry)})).map(({item,blockerIds})=>({id:item.id,blocker_ids:blockerIds})).sort((left,right)=>left.id.localeCompare(right.id))}async function autoUnblockResolvedDependents(pmRoot,settings,items,closedId,author,statusRegistry,commandScope){const candidates=findAutoUnblockCandidates(items,closedId,statusRegistry),warnings=[],unblockedIds=[],conflictIds=[],failed=[];let conflict;for(const candidate of candidates)try{const unblocked=await mutateItem({pmRoot,settings,id:candidate.id,op:"update",author,message:`Auto-unblocked after blocker ${closedId} closed`,mutate(document){const dependencies=document.metadata.dependencies??[],remainingDependencies=dependencies.filter(dependency=>{const dependencyId=dependency.id.trim().toLowerCase();return dependency.kind!=="blocked_by"||!candidate.blocker_ids.includes(dependencyId)});document.metadata.status=statusRegistry.open_status,delete document.metadata.blocked_by,delete document.metadata.blocked_reason,document.metadata.unblock_note=`Auto-unblocked after blocker ${closedId} closed; all blockers resolved (${candidate.blocker_ids.join(", ")}).`,remainingDependencies.length>0?document.metadata.dependencies=remainingDependencies:delete document.metadata.dependencies;const changedFields=["status","blocked_by","blocked_reason","unblock_note"];return remainingDependencies.length!==dependencies.length&&changedFields.push("dependencies"),{changedFields}}});warnings.push(`auto_unblocked:${unblocked.item.id}:resolved_blockers=${candidate.blocker_ids.join(",")}`),unblockedIds.push(unblocked.item.id)}catch(error){const reason=error instanceof Error?error.message.replace(/\s+/g," ").trim():"unknown";isItemRevisionConflict(error)?(conflict??=error,conflictIds.push(candidate.id)):failed.push({id:candidate.id,reason}),warnings.push(`auto_unblock_failed:${candidate.id}:${reason}`)}if(conflict!==void 0){const enriched=await enrichItemRevisionConflict(conflict,pmRoot),blockedStatuses=[...statusRegistry.blocked_statuses].sort().join(",");throw postCloseDependentConflict(enriched,{closedId,unblockedIds,conflictIds,failed,openStatus:statusRegistry.open_status,blockedStatuses,commandScope})}return warnings}const POST_CLOSE_REPORT_LIMIT=10,POST_CLOSE_STEP_LIMIT=20,POST_CLOSE_DETAIL_TRIMS=[{list:"auto_unblock_failed",omitted:"auto_unblock_failed_omitted",floor:0},{list:"changes_since",omitted:"changes_since_omitted",floor:0},{list:"pending_unblock",omitted:"pending_unblock_omitted",floor:1}];function fitPostCloseDetails(details){for(const trim of POST_CLOSE_DETAIL_TRIMS){const list=details[trim.list];if(Array.isArray(list))for(;list.length>trim.floor&&!isPmCliErrorDetails(details);)list.pop(),Reflect.set(details,trim.omitted,Number(details[trim.omitted])+1)}return details}function boundedIdList(ids){const omitted=ids.length-POST_CLOSE_REPORT_LIMIT;return`${ids.slice(0,POST_CLOSE_REPORT_LIMIT).join(", ")}${omitted>0?`, and ${omitted} more`:""}`}const POST_CLOSE_AUTO_UNBLOCK_REFUSED_REASON="post_close_auto_unblock_refused";function postCloseDependentConflict(conflict,fanOut){const{closedId,conflictIds,failed,commandScope}=fanOut,dependent=String(conflict.context.item_id),unblock=id=>renderPmCommand([...commandScope,"update",id,"--status",fanOut.openStatus,"--unset","blocked_by","--unset","blocked_reason","--expect-hash",`${id}=<item_hash>`]),reported=failed.slice(0,POST_CLOSE_REPORT_LIMIT).map(entry=>({id:entry.id,reason:unicodeSafePrefix(entry.reason,160)})),otherFailures=failed.length===0?"":` Auto-unblocking also failed for ${boundedIdList(failed.map(entry=>entry.id))}; details.auto_unblock_failed gives the reasons it kept (auto_unblock_failed_omitted counts the rest; their get step shows the item). Fix that cause before unblocking it.`,discovery=renderPmCommand([...commandScope,"list","--status",fanOut.blockedStatuses,"--fields","id,title,blocked_by,dependencies","--limit","200"]),allSteps=[...conflictIds.slice(0,POST_CLOSE_REPORT_LIMIT).flatMap(id=>[renderPmCommand([...commandScope,"get",id,"--json"]),unblock(id)]),...reported.map(entry=>renderPmCommand([...commandScope,"get",entry.id,"--json"]))],truncated=conflictIds.length>POST_CLOSE_REPORT_LIMIT||failed.length>POST_CLOSE_REPORT_LIMIT||allSteps.length>POST_CLOSE_STEP_LIMIT,steps=allSteps.slice(0,truncated?POST_CLOSE_STEP_LIMIT-1:POST_CLOSE_STEP_LIMIT);return new PmCliError(`${closedId} was closed, but auto-unblocking ${dependent} was refused. ${conflict.message}`,conflict.exitCode,{...conflict.context,reason:POST_CLOSE_AUTO_UNBLOCK_REFUSED_REASON,examples:itemRevisionConflictGuidance(dependent,!1,{scopeArgs:commandScope}).examples,required:`The close of ${closedId} is complete; do not retry it. Only unblocking ${conflictIds.length===1?dependent:`the guarded dependents it refused (${boundedIdList(conflictIds)})`} remains: re-read each one (pm get <id> --json reports item_hash), check that every blocker it declares is resolved, then unblock it with ${unblock(dependent)}${conflictIds.length===1?"":" for each id"}.${otherFailures}${truncated?` This refusal does not list a step for every dependent left blocked; list them with ${discovery}, and while it reports has_more, continue with --after <next_cursor>.`:""}`,nextSteps:truncated?[...steps,discovery]:steps,details:fitPostCloseDetails({...structuredClone(conflict.context.details),pending_unblock:conflictIds.slice(0,POST_CLOSE_REPORT_LIMIT),pending_unblock_omitted:Math.max(0,conflictIds.length-POST_CLOSE_REPORT_LIMIT),auto_unblock_failed:reported,auto_unblock_failed_omitted:Math.max(0,failed.length-POST_CLOSE_REPORT_LIMIT)}),side_effects:[{path:`history/${closedId}.jsonl`,op:"close"},...fanOut.unblockedIds.map(id=>({path:`history/${id}.jsonl`,op:"update"}))]})}async function committedCloseDependentConflict(error,id,pmRoot){if(!isItemRevisionConflict(error)||!error.context.side_effects?.some(effect=>`${effect.op}:${effect.path}`==`close:history/${id}.jsonl`))return;const dependent=String(error.context.item_id);return{warnings:[...error.context.side_effects.filter(effect=>effect.op==="update").map(effect=>effect.path.slice(8,-6)).map(unblockedId=>`auto_unblocked:${unblockedId}`),`auto_unblock_refused:${dependent}:item_revision_conflict`],dependent_revision_conflict:{item_id:dependent,error:toErrorMessage(error),...await itemRevisionConflictRowFields(error,pmRoot)}}}function applyInlineCloseFields(metadata,options){const changedFields=[],inlineCloseFields=[{option:options.resolution,key:"resolution"},{option:options.expectedResult,key:"expected_result"},{option:options.actualResult,key:"actual_result"}];for(const{option,key}of inlineCloseFields){if(typeof option!="string")continue;const trimmed=option.trim();trimmed.length!==0&&(metadata[key]=trimmed,changedFields.push(key))}return changedFields}function applyDuplicateCloseMetadata(metadata,duplicateOf){if(duplicateOf===void 0)return[];metadata.duplicate_of=duplicateOf;const duplicateFallbackFields=[],fallbackValues=[{key:"resolution",value:`Duplicate of ${duplicateOf}`},{key:"expected_result",value:`Canonical item ${duplicateOf} tracks the work.`},{key:"actual_result",value:`Closed as duplicate of ${duplicateOf}.`}];for(const{key,value}of fallbackValues)shouldApplyDuplicateFallback(metadata[key])&&(metadata[key]=value,duplicateFallbackFields.push(key));return duplicateFallbackFields}function suppliedCloseOptionTokens(options,missingFlags){const tokens=[["--resolution",options.resolution],["--expected-result",options.expectedResult],["--actual-result",options.actualResult],["--validate-close",options.validateClose],["--completed-at",options.completedAt],["--message",options.message],["--author",options.author]].flatMap(([flag,value])=>missingFlags.has(flag)||value===void 0||value.trim().length===0?[]:[`${flag}=${value}`]);return options.force===!0?[...tokens,"--force"]:tokens}function closeValidationMissingFieldsError(metadata,missingFields,context){const missingLabels=missingFields.map(field=>field.label),missingFlags=missingFields.map(field=>`--${field.key.replaceAll("_","-")}`),placeholders=missingFlags.flatMap(flag=>[flag,"<value>"]),updateTokens=[...context.commandScope,"update",metadata.id,...placeholders],message=`Cannot close item ${metadata.id}: missing ${missingLabels.join(", ")}. Populate fields or use --validate-close warn.`,warnStep="Use --validate-close warn only when governance permits an evidenced exception.",overrides=Object.entries(context.options.lifecyclePolicy??{}).filter(([,value])=>value!==void 0).map(([key])=>key),expectations=activeItemRevisionExpectations(context.pmRoot),blankAuthor=typeof context.options.author=="string"&&context.options.author.trim().length===0,unreplayable=overrides.length>0?`its lifecyclePolicy override (${overrides.join(", ")}) has no CLI spelling`:blankAuthor?"its explicitly blank author has no CLI spelling (pm close refuses an empty --author)":expectations===void 0?"its revision guards cannot be replayed as typed (nested revision guards expect different revisions of one item, or a write in the same operation advanced a guarded revision)":void 0;if(unreplayable!==void 0)return new PmCliError(message,EXIT_CODE.USAGE,{code:"close_validation_missing_fields",required:`Pass ${missingFields.map(field=>field.key).join(", ")} on the same SDK close; ${unreplayable}, so no CLI retry reproduces it.`,recovery:{missing:missingFlags,next_best_command:renderPmCommand(updateTokens)},nextSteps:["Retry the same SDK close with the missing evidence supplied, inside the same lifecycle policy and revision guards.",warnStep]});const reason=context.closeReason===void 0?[]:[`--reason=${context.closeReason}`],guards=expectations.map(guard=>`--expect-hash=${guard}`),closeTokens=[...context.commandScope,"close",metadata.id,...reason,...suppliedCloseOptionTokens(context.options,new Set(missingFlags)),...guards,...placeholders];return new PmCliError(message,EXIT_CODE.USAGE,{code:"close_validation_missing_fields",required:`Supply ${missingFlags.join(", ")}: pm close accepts them and records them in the same write as the closure.`,recovery:{missing:missingFlags,suggested_retry:renderPmCommand(closeTokens),suggested_retry_args:closeTokens,next_best_command:renderPmCommand(updateTokens)},nextSteps:["Run recovery.suggested_retry when it is present: the same close with the missing flags added, so one write records the evidence and the closure.","Without it, record the evidence with recovery.next_best_command, then repeat the original close.",warnStep]})}function collectCloseValidationWarnings(metadata,validateCloseMode,activeChildIds,context){const warnings=[];if(validateCloseMode!=="off"){const missingFields=findMissingCloseValidationFields(metadata);if(missingFields.length>0){const missingLabels=missingFields.map(field=>field.label);if(validateCloseMode==="strict")throw closeValidationMissingFieldsError(metadata,missingFields,context);warnings.push(`close_validation_missing_fields:${metadata.id}:${missingLabels.join(",")}`)}if(activeChildIds.length>0){if(validateCloseMode==="strict")throw new PmCliError(`Cannot close item ${metadata.id}: active child items remain open (${activeChildIds.join(", ")}). Close, cancel, or re-parent them first, or use --validate-close warn.`,EXIT_CODE.USAGE);warnings.push(`close_validation_active_children:${metadata.id}:${activeChildIds.join(",")}`)}return warnings}return activeChildIds.length>0&&warnings.push(`closed_with_active_children:${metadata.id}:${activeChildIds.join(",")}`),warnings}function applyCloseReason(metadata,closeReason){return closeReason!==void 0?(metadata.close_reason=closeReason,["close_reason"]):[]}function clearCloseAssignee(metadata){const cleared=["assignee","claim_principal"].filter(key=>metadata[key]!==void 0);for(const key of cleared)delete metadata[key];return[...cleared]}function mutateCloseMetadata(metadata,context){if(isTerminalStatus(metadata.status,context.statusRegistry)&&!context.force)throw new PmCliError(`Item ${metadata.id} is already terminal; use pm update to append acceptance evidence, or --force only for an intentional repeat closure.`,EXIT_CODE.CONFLICT,{recovery:closeEvidenceRecovery(metadata,context.commandScope,context.options)});const inlineChangedFields=applyInlineCloseFields(metadata,context.options),duplicateFallbackFields=applyDuplicateCloseMetadata(metadata,context.duplicateOf),mutationWarnings=collectCloseValidationWarnings(metadata,context.validateCloseMode,context.activeChildIds,context);metadata.status=context.statusRegistry.close_status,metadata.closed_at=context.closedAt;const shouldWriteCompletedAt=context.options.completedAt!==void 0||metadata.completed_at===void 0;shouldWriteCompletedAt&&(metadata.completed_at=context.completedAt);const changedFields=["status","closed_at",...shouldWriteCompletedAt?["completed_at"]:[],...applyCloseReason(metadata,context.closeReason),...inlineChangedFields];if(shouldCompletePlanOnClose(metadata)&&(metadata.plan_mode="completed",changedFields.push("plan_mode")),context.duplicateOf!==void 0){changedFields.push("duplicate_of");for(const key of duplicateFallbackFields)changedFields.includes(key)||changedFields.push(key)}changedFields.push(...clearCloseAssignee(metadata));const blockerCleanup=applyTerminalOrderingPolicy(metadata,context.lifecyclePolicy);return changedFields.push(...blockerCleanup.changedFields),mutationWarnings.push(...blockerCleanup.warnings),{changedFields,...mutationWarnings.length>0?{warnings:mutationWarnings}:{}}}const _testOnlyCloseCommand={blockedByIds:collectBlockedByIds,fitPostCloseDetails};async function closeItem(id,closeReasonText,options,global2){const pmRoot=resolvePmRoot(process.cwd(),global2.path),commandScope=resolvePmCommandScopeArgs(global2);await assertInitializedTracker(pmRoot);const settings=await readSettings(pmRoot),statusRegistry=resolveRuntimeStatusRegistry(settings.schema),author=resolveAuthor(options.author,settings.author_default),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(!located)throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder);const duplicateOf=await assertDuplicateTargetExists(pmRoot,settings,options.duplicateOf,located.id),lifecyclePolicy={requireCloseReason:options.lifecyclePolicy?.requireCloseReason??settings.governance.require_close_reason,orderingEdges:options.lifecyclePolicy?.orderingEdges??"preserve"},closeReason=requireTerminalReason({explicit:closeReasonText,duplicateOf,resolution:options.resolution,message:options.message},lifecyclePolicy.requireCloseReason).closeReason,validateCloseMode=parseValidateCloseMode(options.validateClose)??settings.governance.close_validation_default,trackerItems=await listAllItemMetadataLight(pmRoot,settings.item_format,typeToFolder,void 0,settings.schema),activeChildIds=findActiveChildIds(trackerItems,located.id,statusRegistry),closedAt=nowIso(),completedAt=options.completedAt===void 0?closedAt:resolveIsoOrRelative(options.completedAt,new Date(closedAt),"completed-at");let completion={timestamp:completedAt,source:options.completedAt===void 0?"close_time":"asserted",...options.completedAt===void 0?{hint:`completed_at defaults to the close time. If work finished earlier, correct it with ${renderPmCommand([...commandScope,"update",located.id,"--completed-at","<ISO>"])}.`}:{}};const result=await mutateItemWithHistoryContextResolver({pmRoot,settings,id:located.id,op:"close",author,message:options.message,force:options.force,resolveHistoryContext:()=>({completion:{timestamp:completion.timestamp,source:completion.source}}),mutate(document){return options.completedAt===void 0&&document.metadata.completed_at!==void 0&&(completion={timestamp:document.metadata.completed_at,source:"existing"}),mutateCloseMetadata(document.metadata,{pmRoot,commandScope,statusRegistry,force:options.force,options,duplicateOf,validateCloseMode,activeChildIds,closeReason,closedAt,completedAt,lifecyclePolicy})}}),evidence=validateCloseMode==="warn"?closeEvidenceRecovery(result.item,commandScope):void 0;return{item:toItemRecord(result.item),changed_fields:result.changedFields,...evidence?{follow_up:{kind:"complete_close_evidence",missing:evidence.missing,suggested_command:evidence.suggested_retry,suggested_command_args:evidence.suggested_retry_args}}:{},warnings:[...result.warnings,...await autoUnblockResolvedDependents(pmRoot,settings,trackerItems,located.id,author,statusRegistry,commandScope)],completion}}function runClose(id,closeReasonText,options,global2){return closeItem(id,closeReasonText,options,global2)}export{_testOnlyCloseCommand,closeItem,committedCloseDependentConflict,runClose};
|
|
2
2
|
//# sourceMappingURL=close.js.map
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { bindItemRevisionScope,createItemRevisionScope,itemRevisionScopeReceipt,runWithItemRevisionScope,type ItemRevisionScope } from "../../core/store/item-mutation-precondition.js";
|
|
1
|
+
import { bindItemRevisionScope,createItemRevisionScope,itemRevisionScopeReceipt,runWithItemRevisionScope,type ItemRevisionRecoveryInvocation,type ItemRevisionScope } from "../../core/store/item-mutation-precondition.js";
|
|
2
2
|
import { PmCliError,type PmCliErrorDetails } from "../../core/shared/errors.js";
|
|
3
|
-
export type { ItemRevisionScope } from "../../core/store/item-mutation-precondition.js";
|
|
3
|
+
export type { ItemRevisionRecoveryInvocation,ItemRevisionScope } from "../../core/store/item-mutation-precondition.js";
|
|
4
4
|
/** Refusal code for a locked write that found a revision other than the declared one. */
|
|
5
5
|
export declare const ITEM_REVISION_CONFLICT_CODE = "item_revision_conflict";
|
|
6
6
|
/** Most recent history entries a conflict refusal describes. */
|
|
@@ -106,17 +106,26 @@ export declare function isItemRevisionConflict(error:unknown):error is PmCliErro
|
|
|
106
106
|
export declare function throwFirstItemRevisionConflict(errors:readonly unknown[]):void;
|
|
107
107
|
/** Refusal for a guard on an invocation an extension parser or preflight override rewrote. */
|
|
108
108
|
export declare function expectHashInvocationRewrittenError():PmCliError;
|
|
109
|
+
/**
|
|
110
|
+
* Re-render a revision refusal's read-only recovery (`required`, `examples`,
|
|
111
|
+
* `next_steps`) for the invocation that raised it (pm-gh1677), so replaying
|
|
112
|
+
* them reads the same tracker in the same output mode. Other errors, and an
|
|
113
|
+
* omitted invocation, pass through unchanged.
|
|
114
|
+
*/
|
|
115
|
+
export declare function scopeItemRevisionConflict(error:unknown,invocation:ItemRevisionRecoveryInvocation | undefined):unknown;
|
|
109
116
|
/**
|
|
110
117
|
* Attach bounded change evidence to a revision conflict. The evidence is read
|
|
111
118
|
* after the lock is released, so it describes the record as it was then; the
|
|
112
119
|
* refusal's `current_revision` remains the revision the locked write found.
|
|
120
|
+
* With an `invocation`, the recovery commands are also re-rendered for it. A
|
|
121
|
+
* refusal raised by another tracker's guard is returned unchanged.
|
|
113
122
|
*/
|
|
114
|
-
export declare function enrichItemRevisionConflict(error:unknown,pmRoot:string):Promise<unknown>;
|
|
123
|
+
export declare function enrichItemRevisionConflict(error:unknown,pmRoot:string,invocation?:ItemRevisionRecoveryInvocation):Promise<unknown>;
|
|
115
124
|
/**
|
|
116
125
|
* Run an operation under an already-bound scope and return its receipt,
|
|
117
126
|
* enriching a revision refusal with bounded change evidence.
|
|
118
127
|
*/
|
|
119
|
-
export declare function runWithBoundItemRevisionScope<T>(scope:ItemRevisionScope,operation:() => Promise<T
|
|
128
|
+
export declare function runWithBoundItemRevisionScope<T>(scope:ItemRevisionScope,operation:() => Promise<T>,invocation?:ItemRevisionRecoveryInvocation):Promise<ExpectedItemRevisionsOutcome<T>>;
|
|
120
129
|
/**
|
|
121
130
|
* Run `operation` so every locked write to an expected item first proves the
|
|
122
131
|
* item is still at the declared revision. A mismatch refuses that write with
|
|
@@ -159,4 +168,6 @@ run:() => Promise<T>;
|
|
|
159
168
|
options?:Record<string,unknown>;
|
|
160
169
|
/** Top-level background flag, consulted like `options.background`. */
|
|
161
170
|
background?:unknown;
|
|
171
|
+
/** Invocation whose tracker scope a revision refusal's recovery commands replay. */
|
|
172
|
+
invocation?:ItemRevisionRecoveryInvocation;
|
|
162
173
|
}):Promise<T>;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="aca1dfc0-e0c9-5554-96e3-bb9b2cdeb7f9")}catch{}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{hashDocument}from"../../core/history/history.js";import{readHistoryEntries}from"../../core/history/read.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{bindItemRevisionScope,createItemRevisionScope,itemRevisionScopeReceipt,runWithItemRevisionScope}from"../../core/store/item-mutation-precondition.js";import{buildItemNotFoundError,locateItem,readLocatedItem}from"../../core/store/item-store.js";import{getHistoryPath,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{PM_EXPECT_HASH_ACTIONS,PM_TOOL_ACTIONS}from"../cli-contracts/enum-contracts.js";import{resolveHistorySubject}from"../history/subject.js";import{resolvePhysicalItemId}from"../query/declared-blockers.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{isMutationAction}from"../mutation-guard.js";import{isPmCliExpectedError}from"../errors.js";const ITEM_REVISION_CONFLICT_CODE="item_revision_conflict",ITEM_REVISION_CONFLICT_CHANGE_LIMIT=10,ITEM_HASH_PATTERN=/^[0-9a-f]{64}$/u;function invalidExpectHash(value,reason){return new PmCliError(`Invalid expected revision ${JSON.stringify(value)}: ${reason}.`,EXIT_CODE.USAGE,{code:"expect_hash_invalid",value,required:"Pass the 64-character item_hash from pm get <id> --json, optionally as <id>=<item_hash>.",examples:["--expect-hash <item_hash>","--expect-hash pm-a1b2=<item_hash>"]})}function normalizeExpectedItemHash(value){const normalized=typeof value=="string"?value.trim().toLowerCase():"";if(!ITEM_HASH_PATTERN.test(normalized))throw invalidExpectHash(String(value),"the revision is not a 64-character hexadecimal item_hash");return normalized}function parseExpectHashSpecs(values){return(values===void 0?[]:typeof values=="string"?[values]:values).flatMap(raw=>{if(typeof raw!="string")throw invalidExpectHash(String(raw),"expected a string");const parts=raw.split(",").map(token=>token.trim()).filter(token=>token.length>0);if(parts.length===0)throw invalidExpectHash(raw,"the value is empty");return parts.map(token=>{const separator=token.lastIndexOf("="),id=separator===-1?void 0:token.slice(0,separator).trim();if(id!==void 0&&id.length===0)throw invalidExpectHash(token,"the item id before = is empty");const itemHash=normalizeExpectedItemHash(separator===-1?token:token.slice(separator+1));return id===void 0?{itemHash}:{id,itemHash}})})}async function locateRevisionTarget(pmRoot,id){const settings=await readSettings(pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(located){const{document}=await readLocatedItem(located,{schema:settings.schema});if(document.metadata.id!==await resolvePhysicalItemId(located.itemPath,located.id))throw new PmCliError(`Item file ${located.id} embeds the id ${document.metadata.id}; no revision can be bound to an item whose identity is in conflict.`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:located.id,required:`Repair ${located.id}'s identity first (pm validate reports it; pm restore ${located.id} <version> recovers a recorded state), then read its item_hash again.`});return{id:document.metadata.id,document}}try{return{id:(await resolveHistorySubject(pmRoot,id,settings,typeToFolder)).id,document:EMPTY_CANONICAL_DOCUMENT}}catch{throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder)}}function resolveRevisionRoot(context){return resolvePmRoot(context.cwd??process.cwd(),context.pmRoot)}async function readItemRevision(id,context={}){const target=await locateRevisionTarget(resolveRevisionRoot(context),id);return{id:target.id,item_hash:hashDocument(target.document)}}async function resolveExpectedItemRevisions(pmRoot,specs,defaultId){const resolved=[];for(const spec of specs){const target=spec.id??defaultId;if(target===void 0||target.trim().length===0)throw new PmCliError("A bare expected revision needs an item to bind to.",EXIT_CODE.USAGE,{code:"expect_hash_target_required",required:"This command has no single item argument; name each target as --expect-hash <id>=<item_hash>.",examples:["--expect-hash pm-a1b2=<item_hash>"]});resolved.push({id:(await locateRevisionTarget(pmRoot,target)).id,itemHash:spec.itemHash})}return resolved}function changedTopLevelFields(entry){return[...new Set(entry.patch.map(change=>{const segments=change.path.split("/");return String(segments[1]==="metadata"?segments[2]:segments[1])}))].sort()}async function describeItemRevisionChanges(pmRoot,id,expectedHash){let history;try{history=await readHistoryEntries(getHistoryPath(pmRoot,id),id)}catch{return}let start=-1;for(let index=history.length-1;index>=0;index-=1){const entry=history[index];if(entry.after_hash===expectedHash){start=index+1;break}if(entry.before_hash===expectedHash){start=index;break}}if(start===-1)return{expected_revision_recorded:!1,changes_since:[],changes_since_omitted:0};const later=history.slice(start),shown=later.slice(-ITEM_REVISION_CONFLICT_CHANGE_LIMIT);return{expected_revision_recorded:!0,changes_since:shown.map(entry=>({ts:entry.ts,op:entry.op,author:entry.author,fields:changedTopLevelFields(entry)})),changes_since_omitted:later.length-shown.length}}async function itemRevisionConflictRowFields(error,pmRoot){if(!isItemRevisionConflict(error))return{};const enriched=await enrichItemRevisionConflict(error,pmRoot);return{error_code:ITEM_REVISION_CONFLICT_CODE,expected_revision:String(enriched.context.expected_revision),current_revision:String(enriched.context.current_revision),details:enriched.context.details}}function isItemRevisionConflict(error){return isPmCliExpectedError(error)&&error.context.code===ITEM_REVISION_CONFLICT_CODE}function throwFirstItemRevisionConflict(errors){const conflict=errors.find(error=>isItemRevisionConflict(error));if(conflict!==void 0)throw conflict}function expectHashInvocationRewrittenError(){return new PmCliError("--expect-hash cannot guard an invocation an extension override rewrote: which item it writes is not provable.",EXIT_CODE.USAGE,{code:"expect_hash_invocation_rewritten",required:"Run the command without the rewriting extension (--no-extensions), or drop --expect-hash.",why:"An extension parser or preflight override changed this invocation's tracker or arguments, and final dispatch, the extension SDK client and the guard do not share one rewritten view."})}async function enrichItemRevisionConflict(error,pmRoot){if(!isItemRevisionConflict(error)||error.context.details!==void 0)return error;const id=error.context.item_id,expected=error.context.expected_revision;if(typeof id!="string"||typeof expected!="string")return error;let changes;try{changes=await describeItemRevisionChanges(pmRoot,id,expected)}catch{return error}if(changes===void 0)return error;const details={expected_revision_recorded:changes.expected_revision_recorded,changes_since:changes.changes_since.map(change=>({ts:change.ts,op:change.op,author:change.author,fields:[...change.fields]})),changes_since_omitted:changes.changes_since_omitted},enriched=new PmCliError(error.message,error.exitCode,{...error.context,details});return enriched.stack=error.stack,enriched}async function runWithBoundItemRevisionScope(scope,operation){try{return{result:await runWithItemRevisionScope(scope,operation),...itemRevisionScopeReceipt(scope)}}catch(error){throw scope.pmRoot===void 0?error:await enrichItemRevisionConflict(error,scope.pmRoot)}}async function withExpectedItemRevisions(expectations,operation,context={}){return runWithBoundItemRevisionScope(await bindExpectedItemRevisions(expectations,context),operation)}async function bindExpectedItemRevisions(expectations,context={}){const pmRoot=resolveRevisionRoot(context),specs=expectations.map(({id,itemHash})=>({id,itemHash:normalizeExpectedItemHash(itemHash)})),scope=createItemRevisionScope();return bindItemRevisionScope(scope,pmRoot,await resolveExpectedItemRevisions(pmRoot,specs)),scope}function itemRevisionUncheckedWarning(id){return`expect_hash_unchecked:${id}:no_locked_write_reached_this_item`}const NATIVE_ACTIONS=new Set(PM_TOOL_ACTIONS);function assertExpectHashAdmissible(path,options={}){const hyphenated=path.trim().replace(/\s+/gu,"-"),action=NATIVE_ACTIONS.has(hyphenated)?hyphenated:path;if(NATIVE_ACTIONS.has(action)&&(!isMutationAction(action)||action==="deps")&&!PM_EXPECT_HASH_ACTIONS.has(action))throw expectHashRequiresMutationError(action);if((action==="test"||action==="test-all")&&options.background===!0)throw new PmCliError(`--expect-hash cannot guard ${action} --background: the worker runs in another process.`,EXIT_CODE.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${action} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function expectHashRequiresMutationError(action){return new PmCliError(`--expect-hash guards item writes, and ${action} is not a mutation.`,EXIT_CODE.USAGE,{code:"expect_hash_requires_mutation",required:"Use --expect-hash (MCP/SDK expectHash) only on a command or action that writes items."})}function withUncheckedRevisionWarnings(result,unchecked){if(unchecked.length===0||typeof result!="object"||result===null||Array.isArray(result))return result;const record=result,warnings=Array.isArray(record.warnings)?record.warnings:[];return{...record,warnings:[...warnings,...unchecked.map(itemRevisionUncheckedWarning)]}}async function dispatchWithExpectedItemRevisions(params){const raw=params.expectHash;if(raw!==void 0&&typeof raw!="string"&&!(Array.isArray(raw)&&raw.every(entry=>typeof entry=="string")))throw invalidExpectHash(JSON.stringify(raw)??String(raw),"expected a string or an array of strings");const specs=parseExpectHashSpecs(raw);if(specs.length===0)return params.run();assertExpectHashAdmissible(params.action,{background:params.background===!0||params.options?.background===!0});const scope=createItemRevisionScope();bindItemRevisionScope(scope,params.pmRoot,await resolveExpectedItemRevisions(params.pmRoot,specs,params.defaultId));const outcome=await runWithBoundItemRevisionScope(scope,params.run);return withUncheckedRevisionWarnings(outcome.result,outcome.unchecked)}export{ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,assertExpectHashAdmissible,bindExpectedItemRevisions,bindItemRevisionScope,createItemRevisionScope,describeItemRevisionChanges,dispatchWithExpectedItemRevisions,enrichItemRevisionConflict,expectHashInvocationRewrittenError,expectHashRequiresMutationError,isItemRevisionConflict,itemRevisionConflictRowFields,itemRevisionScopeReceipt,itemRevisionUncheckedWarning,normalizeExpectedItemHash,parseExpectHashSpecs,readItemRevision,resolveExpectedItemRevisions,runWithBoundItemRevisionScope,runWithItemRevisionScope,throwFirstItemRevisionConflict,withExpectedItemRevisions};
|
|
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]="2277d018-a882-57ee-bcd5-52bc61cd8efe")}catch{}})();import{getActiveExtensionRegistrations}from"../../core/extensions/index.js";import{hashDocument}from"../../core/history/history.js";import{readHistoryEntries}from"../../core/history/read.js";import{resolveItemTypeRegistry}from"../../core/item/type-registry.js";import{bindItemRevisionScope,createItemRevisionScope,ITEM_REVISION_CONFLICT_CHANGED_REASON,ITEM_REVISION_CONFLICT_UNREADABLE_REASON,isItemRevisionRefusalFrom,isItemRevisionRefusalScoped,itemRevisionConflictGuidance,markItemRevisionRefusalScoped,retainItemRevisionRefusalTracker,itemRevisionScopeReceipt,runWithItemRevisionScope}from"../../core/store/item-mutation-precondition.js";import{buildItemNotFoundError,locateItem,readLocatedItem}from"../../core/store/item-store.js";import{getHistoryPath,resolvePmRoot}from"../../core/store/paths.js";import{readSettings}from"../../core/store/settings.js";import{EXIT_CODE}from"../../core/shared/constants.js";import{PmCliError}from"../../core/shared/errors.js";import{PM_EXPECT_HASH_ACTIONS,PM_TOOL_ACTIONS}from"../cli-contracts/enum-contracts.js";import{resolveHistorySubject}from"../history/subject.js";import{resolvePhysicalItemId}from"../query/declared-blockers.js";import{EMPTY_CANONICAL_DOCUMENT}from"../../core/shared/constants.js";import{isMutationAction}from"../mutation-guard.js";import{isPmCliExpectedError}from"../errors.js";const ITEM_REVISION_CONFLICT_CODE="item_revision_conflict",ITEM_REVISION_CONFLICT_CHANGE_LIMIT=10,ITEM_HASH_PATTERN=/^[0-9a-f]{64}$/u;function invalidExpectHash(value,reason){return new PmCliError(`Invalid expected revision ${JSON.stringify(value)}: ${reason}.`,EXIT_CODE.USAGE,{code:"expect_hash_invalid",value,required:"Pass the 64-character item_hash from pm get <id> --json, optionally as <id>=<item_hash>.",examples:["--expect-hash <item_hash>","--expect-hash pm-a1b2=<item_hash>"]})}function normalizeExpectedItemHash(value){const normalized=typeof value=="string"?value.trim().toLowerCase():"";if(!ITEM_HASH_PATTERN.test(normalized))throw invalidExpectHash(String(value),"the revision is not a 64-character hexadecimal item_hash");return normalized}function parseExpectHashSpecs(values){return(values===void 0?[]:typeof values=="string"?[values]:values).flatMap(raw=>{if(typeof raw!="string")throw invalidExpectHash(String(raw),"expected a string");const parts=raw.split(",").map(token=>token.trim()).filter(token=>token.length>0);if(parts.length===0)throw invalidExpectHash(raw,"the value is empty");return parts.map(token=>{const separator=token.lastIndexOf("="),id=separator===-1?void 0:token.slice(0,separator).trim();if(id!==void 0&&id.length===0)throw invalidExpectHash(token,"the item id before = is empty");const itemHash=normalizeExpectedItemHash(separator===-1?token:token.slice(separator+1));return id===void 0?{itemHash}:{id,itemHash}})})}async function locateRevisionTarget(pmRoot,id){const settings=await readSettings(pmRoot),typeToFolder=resolveItemTypeRegistry(settings,getActiveExtensionRegistrations()).type_to_folder,located=await locateItem(pmRoot,id,settings.id_prefix,settings.item_format,typeToFolder);if(located){const{document}=await readLocatedItem(located,{schema:settings.schema});if(document.metadata.id!==await resolvePhysicalItemId(located.itemPath,located.id))throw new PmCliError(`Item file ${located.id} embeds the id ${document.metadata.id}; no revision can be bound to an item whose identity is in conflict.`,EXIT_CODE.CONFLICT,{code:"item_identity_conflict",item_id:located.id,required:`Repair ${located.id}'s identity first (pm validate reports it; pm restore ${located.id} <version> recovers a recorded state), then read its item_hash again.`});return{id:document.metadata.id,document}}try{return{id:(await resolveHistorySubject(pmRoot,id,settings,typeToFolder)).id,document:EMPTY_CANONICAL_DOCUMENT}}catch{throw await buildItemNotFoundError(pmRoot,id,settings.id_prefix,typeToFolder)}}function resolveRevisionRoot(context){return resolvePmRoot(context.cwd??process.cwd(),context.pmRoot)}async function readItemRevision(id,context={}){const target=await locateRevisionTarget(resolveRevisionRoot(context),id);return{id:target.id,item_hash:hashDocument(target.document)}}async function resolveExpectedItemRevisions(pmRoot,specs,defaultId){const resolved=[];for(const spec of specs){const target=spec.id??defaultId;if(target===void 0||target.trim().length===0)throw new PmCliError("A bare expected revision needs an item to bind to.",EXIT_CODE.USAGE,{code:"expect_hash_target_required",required:"This command has no single item argument; name each target as --expect-hash <id>=<item_hash>.",examples:["--expect-hash pm-a1b2=<item_hash>"]});resolved.push({id:(await locateRevisionTarget(pmRoot,target)).id,itemHash:spec.itemHash})}return resolved}function changedTopLevelFields(entry){return[...new Set(entry.patch.map(change=>{const segments=change.path.split("/");return String(segments[1]==="metadata"?segments[2]:segments[1])}))].sort()}async function describeItemRevisionChanges(pmRoot,id,expectedHash){let history;try{history=await readHistoryEntries(getHistoryPath(pmRoot,id),id)}catch{return}let start=-1;for(let index=history.length-1;index>=0;index-=1){const entry=history[index];if(entry.after_hash===expectedHash){start=index+1;break}if(entry.before_hash===expectedHash){start=index;break}}if(start===-1)return{expected_revision_recorded:!1,changes_since:[],changes_since_omitted:0};const later=history.slice(start),shown=later.slice(-ITEM_REVISION_CONFLICT_CHANGE_LIMIT);return{expected_revision_recorded:!0,changes_since:shown.map(entry=>({ts:entry.ts,op:entry.op,author:entry.author,fields:changedTopLevelFields(entry)})),changes_since_omitted:later.length-shown.length}}async function itemRevisionConflictRowFields(error,pmRoot){if(!isItemRevisionConflict(error))return{};const enriched=await enrichItemRevisionConflict(error,pmRoot);return{error_code:ITEM_REVISION_CONFLICT_CODE,expected_revision:String(enriched.context.expected_revision),current_revision:String(enriched.context.current_revision),details:enriched.context.details}}function isItemRevisionConflict(error){return isPmCliExpectedError(error)&&error.context.code===ITEM_REVISION_CONFLICT_CODE}function throwFirstItemRevisionConflict(errors){const conflict=errors.find(error=>isItemRevisionConflict(error));if(conflict!==void 0)throw conflict}function expectHashInvocationRewrittenError(){return new PmCliError("--expect-hash cannot guard an invocation an extension override rewrote: which item it writes is not provable.",EXIT_CODE.USAGE,{code:"expect_hash_invocation_rewritten",required:"Run the command without the rewriting extension (--no-extensions), or drop --expect-hash.",why:"An extension parser or preflight override changed this invocation's tracker or arguments, and final dispatch, the extension SDK client and the guard do not share one rewritten view."})}function scopeItemRevisionConflict(error,invocation){if(invocation===void 0||!isItemRevisionConflict(error)||typeof error.context.item_id!="string"||isItemRevisionRefusalScoped(error))return error;const unreadable=error.context.reason===ITEM_REVISION_CONFLICT_UNREADABLE_REASON;if(!unreadable&&error.context.reason!==ITEM_REVISION_CONFLICT_CHANGED_REASON)return error;const scoped=markItemRevisionRefusalScoped(retainItemRevisionRefusalTracker(error,new PmCliError(error.message,error.exitCode,{...error.context,...itemRevisionConflictGuidance(error.context.item_id,unreadable,invocation)})));return scoped.stack=error.stack,scoped}async function enrichItemRevisionConflict(error,pmRoot,invocation){if(!isItemRevisionRefusalFrom(error,pmRoot))return error;const scoped=scopeItemRevisionConflict(error,invocation);if(!isItemRevisionConflict(scoped)||scoped.context.details!==void 0)return scoped;const id=scoped.context.item_id,expected=scoped.context.expected_revision;if(typeof id!="string"||typeof expected!="string")return scoped;let changes;try{changes=await describeItemRevisionChanges(pmRoot,id,expected)}catch{return scoped}if(changes===void 0)return scoped;const details={expected_revision_recorded:changes.expected_revision_recorded,changes_since:changes.changes_since.map(change=>({ts:change.ts,op:change.op,author:change.author,fields:[...change.fields]})),changes_since_omitted:changes.changes_since_omitted},enriched=retainItemRevisionRefusalTracker(scoped,new PmCliError(scoped.message,scoped.exitCode,{...scoped.context,details}));return enriched.stack=scoped.stack,enriched}async function runWithBoundItemRevisionScope(scope,operation,invocation){try{return{result:await runWithItemRevisionScope(scope,operation),...itemRevisionScopeReceipt(scope)}}catch(error){throw scope.pmRoot===void 0?error:await enrichItemRevisionConflict(error,scope.pmRoot,invocation)}}function revisionRecoveryInvocation(context){return context.cwd===void 0&&context.pmRoot===void 0?void 0:{scopeArgs:["--pm-path",resolveRevisionRoot(context)]}}async function withExpectedItemRevisions(expectations,operation,context={}){return runWithBoundItemRevisionScope(await bindExpectedItemRevisions(expectations,context),operation,revisionRecoveryInvocation(context))}async function bindExpectedItemRevisions(expectations,context={}){const pmRoot=resolveRevisionRoot(context),specs=expectations.map(({id,itemHash})=>({id,itemHash:normalizeExpectedItemHash(itemHash)})),scope=createItemRevisionScope();return bindItemRevisionScope(scope,pmRoot,await resolveExpectedItemRevisions(pmRoot,specs)),scope}function itemRevisionUncheckedWarning(id){return`expect_hash_unchecked:${id}:no_locked_write_reached_this_item`}const NATIVE_ACTIONS=new Set(PM_TOOL_ACTIONS);function assertExpectHashAdmissible(path,options={}){const hyphenated=path.trim().replace(/\s+/gu,"-"),action=NATIVE_ACTIONS.has(hyphenated)?hyphenated:path;if(NATIVE_ACTIONS.has(action)&&(!isMutationAction(action)||action==="deps")&&!PM_EXPECT_HASH_ACTIONS.has(action))throw expectHashRequiresMutationError(action);if((action==="test"||action==="test-all")&&options.background===!0)throw new PmCliError(`--expect-hash cannot guard ${action} --background: the worker runs in another process.`,EXIT_CODE.USAGE,{code:"expect_hash_background_unsupported",required:`Run ${action} in the foreground to guard its result recording, or drop --expect-hash for a background run.`})}function expectHashRequiresMutationError(action){return new PmCliError(`--expect-hash guards item writes, and ${action} is not a mutation.`,EXIT_CODE.USAGE,{code:"expect_hash_requires_mutation",required:"Use --expect-hash (MCP/SDK expectHash) only on a command or action that writes items."})}function withUncheckedRevisionWarnings(result,unchecked){if(unchecked.length===0||typeof result!="object"||result===null||Array.isArray(result))return result;const record=result,warnings=Array.isArray(record.warnings)?record.warnings:[];return{...record,warnings:[...warnings,...unchecked.map(itemRevisionUncheckedWarning)]}}async function dispatchWithExpectedItemRevisions(params){const raw=params.expectHash;if(raw!==void 0&&typeof raw!="string"&&!(Array.isArray(raw)&&raw.every(entry=>typeof entry=="string")))throw invalidExpectHash(JSON.stringify(raw)??String(raw),"expected a string or an array of strings");const specs=parseExpectHashSpecs(raw);if(specs.length===0)return params.run();assertExpectHashAdmissible(params.action,{background:params.background===!0||params.options?.background===!0});const scope=createItemRevisionScope();bindItemRevisionScope(scope,params.pmRoot,await resolveExpectedItemRevisions(params.pmRoot,specs,params.defaultId));const outcome=await runWithBoundItemRevisionScope(scope,params.run,params.invocation);return withUncheckedRevisionWarnings(outcome.result,outcome.unchecked)}export{ITEM_REVISION_CONFLICT_CHANGE_LIMIT,ITEM_REVISION_CONFLICT_CODE,assertExpectHashAdmissible,bindExpectedItemRevisions,bindItemRevisionScope,createItemRevisionScope,describeItemRevisionChanges,dispatchWithExpectedItemRevisions,enrichItemRevisionConflict,expectHashInvocationRewrittenError,expectHashRequiresMutationError,isItemRevisionConflict,itemRevisionConflictRowFields,itemRevisionScopeReceipt,itemRevisionUncheckedWarning,normalizeExpectedItemHash,parseExpectHashSpecs,readItemRevision,resolveExpectedItemRevisions,runWithBoundItemRevisionScope,runWithItemRevisionScope,scopeItemRevisionConflict,throwFirstItemRevisionConflict,withExpectedItemRevisions};
|
|
2
2
|
//# sourceMappingURL=item-revision.js.map
|
|
@@ -1,15 +1,26 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
*
|
|
2
|
+
* @module sdk/output/list-envelope
|
|
3
|
+
*
|
|
4
|
+
* Projects standard list and search read receipts for agent presentation while
|
|
5
|
+
* retaining source uncertainty, pagination and producer-owned diagnostics. The
|
|
6
|
+
* brief default, `--compact` and `--fields` row projections share one lean
|
|
7
|
+
* envelope (GH-1642, GH-1674); `--full` and JSON keep the typed result.
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* Compact a standard brief, compact or fields list envelope without mutating
|
|
11
|
+
* its typed SDK result. Full, custom, partial and inconsistent receipts pass
|
|
12
|
+
* through unchanged. Unchecked pages retain their explicit source status,
|
|
13
|
+
* including empty pages. JSON hosts should retain the original result when full
|
|
14
|
+
* receipts are required.
|
|
6
15
|
*/
|
|
7
16
|
export declare function projectPmBriefListEnvelope(value:unknown):unknown;
|
|
8
17
|
/**
|
|
9
18
|
* Compact a standard search page without mutating its typed SDK result:
|
|
10
19
|
* drops `truncated` when it repeats `has_more`, a `filters.limit` echo of
|
|
11
|
-
* `applied_limit`, and the single default
|
|
12
|
-
*
|
|
13
|
-
*
|
|
20
|
+
* `applied_limit`, and the single default omission receipt in favour of
|
|
21
|
+
* `details: "--full"`. A `--fields` page also drops its projection and `fields`
|
|
22
|
+
* echo, `now`, and a `mode_source` the caller already knows (GH-1674). Custom,
|
|
23
|
+
* partial and inconsistent receipts pass through unchanged; JSON hosts should
|
|
24
|
+
* keep the original result.
|
|
14
25
|
*/
|
|
15
26
|
export declare function projectPmBriefSearchEnvelope(value:unknown):unknown;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="
|
|
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]="43d2915b-7301-5e96-89e0-51c8e817789e")}catch{}})();function isRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)}const ROW_PROJECTION_MODES=new Set(["brief","compact","fields"]);function isRowProjection(value){if(!isRecord(value))return!1;const fields=value.fields;return ROW_PROJECTION_MODES.has(value.mode)&&Object.keys(value).length===2&&Array.isArray(fields)&&fields.length>0&&fields.every(field=>typeof field=="string"&&field.length>0)}function rowsMatchProjection(items,projection){return items.every(row=>isRecord(row)&&Object.keys(row).length===projection.fields.length&&projection.fields.every(field=>Object.hasOwn(row,field)))}function retainedProjection(projection,rowCount){return projection.mode==="fields"&&rowCount===0?{projection}:{}}function hasStandardPagination(value,count){return typeof value.has_more=="boolean"&&value.truncated===value.has_more&&value.count===count&&typeof value.total=="number"&&Number.isSafeInteger(value.total)&&(value.has_more?value.total>count&&typeof value.next_cursor=="string"&&value.next_cursor.length>0:value.total===count&&value.next_cursor==null)}function hasCompactibleSource(value){return isRecord(value)&&(value.status==="complete"||value.status==="unchecked")&&value.unreadable_item_count===0&&value.unreadable_directory_count===0}function hasDefaultOmissions(value,groupName="full_item_fields"){if(!isRecord(value)||!Array.isArray(value.omitted_field_groups))return!1;const groups=value.omitted_field_groups,group=groups[0];return value.has_omissions===!0&&value.omitted_field_group_count===1&&Object.keys(value).length===3&&groups.length===1&&isRecord(group)&&Object.keys(group).length===2&&group.name===groupName&&group.restore_with==="--full"}function projectPmBriefListEnvelope(value){if(!isRecord(value)||!Array.isArray(value.items)||Object.hasOwn(value,"details")||!isRowProjection(value.projection)||!rowsMatchProjection(value.items,value.projection)||!hasCompactibleSource(value.completeness)||!hasStandardPagination(value,value.items.length)||!hasDefaultOmissions(value.omission_receipt))return value;const{total,has_more:hasMore,truncated:_truncated,next_cursor:nextCursor,completeness,projection,now:_now,omission_receipt:_omissions,sorting,filters,...rest}=value,completed=completeness.status==="complete"&&!hasMore&&Object.keys(completeness).length===3,{unreadable_item_count:_items,unreadable_directory_count:_directories,...source}=completeness;return{...rest,...completed?{}:{total,has_more:hasMore,completeness:source},...hasMore?{next_cursor:nextCursor}:{},...projectDefaultSorting(sorting),...compactEchoedFilters(filters,rest.applied_limit,projection),...retainedProjection(projection,value.items.length),details:"--full"}}function isDefaultSorting(value){return isRecord(value)&&value.sort==="default"&&value.order==="asc"&&Object.keys(value).every(key=>key==="sort"||key==="order"||key==="effective_keys")}function isSortKeyPair(value){return Array.isArray(value)&&value.length===2&&typeof value[0]=="string"&&(value[1]==="asc"||value[1]==="desc")}function projectDefaultSorting(value){if(!isDefaultSorting(value))return{sorting:value};const keys=value.effective_keys;return keys===void 0?{}:!Array.isArray(keys)||!keys.every(isSortKeyPair)?{sorting:value}:{sorting:{effective_keys:keys.map(([key,order])=>`${key} ${order}`).join(", ")}}}function echoesProjectionFields(value,projection){if(typeof value!="string"||projection===void 0)return!1;const requested=value.split(",").map(field=>field.trim()).filter(Boolean);return requested.length===projection.fields.length&&requested.every((field,index)=>field===projection.fields[index])}function compactEchoedFilters(filters,appliedLimit,projection){if(!isRecord(filters))return filters===void 0?{}:{filters};const remaining=Object.fromEntries(Object.entries(filters).filter(([key,value])=>!(key==="limit"&&String(value)===String(appliedLimit))&&!(key==="fields"&&echoesProjectionFields(value,projection))&&!(key==="runtime_filters"&&isRecord(value)&&Object.keys(value).length===0)));return Object.keys(remaining).length===0?{}:{filters:remaining}}function hasTerminalSearchPagination(value,count){return value.count===count&&!Object.hasOwn(value,"has_more")&&!Object.hasOwn(value,"truncated")&&value.next_cursor==null&&(value.total===void 0||value.total===count)}function standardSearchProjection(value){if(!Object.hasOwn(value,"projection"))return hasDefaultOmissions(value.omission_receipt,"projection_metadata")?{}:void 0;const projection=value.projection;return isRowProjection(projection)&&projection.mode==="fields"&&rowsMatchProjection(value.items,projection)&&typeof value.now=="string"&&hasDefaultOmissions(value.omission_receipt)?{projection}:void 0}function projectPmBriefSearchEnvelope(value){if(!isRecord(value)||typeof value.query!="string"||!Array.isArray(value.items)||Object.hasOwn(value,"details")||!(hasStandardPagination(value,value.items.length)||hasTerminalSearchPagination(value,value.items.length)))return value;const standard=standardSearchProjection(value);if(standard===void 0)return value;const{truncated:_truncated,omission_receipt:_omissions,filters,projection:_projection,now:_now,mode_source:modeSource,...rest}=value;return{...rest,...modeSource==="settings"||standard.projection===void 0&&modeSource!==void 0?{mode_source:modeSource}:{},...compactEchoedFilters(filters,rest.applied_limit,standard.projection),...standard.projection?retainedProjection(standard.projection,value.items.length):{},details:"--full"}}export{projectPmBriefListEnvelope,projectPmBriefSearchEnvelope};
|
|
2
2
|
//# sourceMappingURL=list-envelope.js.map
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{},n=new e.Error().stack;n&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[n]="3a66ccfd-51fb-5d4a-b9cd-257c49997d52")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested)throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0)throw new TypeError(`Unknown mode-paired output command: ${command}`);if(mode===contract.complete_mode)return createOutputOmissionReceipt([]);const groups=contract.omissions_by_mode[mode];if(groups===void 0)throw new TypeError(`Unknown ${command} output mode: ${mode}`);return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]),READ_ROW_KINDS=new Set(["collection","none"]),READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry=="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command=="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,!0)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,!1))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector=="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0],rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand=="string"?result.subcommand:"";if(subcommand.length===0)return;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand],sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection)||typeof result.projection.mode!="string"||result.projection.mode.trim().length===0)return;const declared=result.projection.declared_field_groups,included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.restore_with=="string"&&entry.restore_with.trim().length>0),includedNames=included.filter(entry=>typeof entry=="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length)return;const declaredNames=new Set(declaredGroups.map(group=>group.name));if(!(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))))return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section=="string")));return isRecord(result.summary)&&result.summary.scope==="matching_items"&&(receipt.summary_scope="matching_items"),receipt}function isGetFieldGroupIncluded(name,owner,result){return name==="dependency_provenance"?!1:Object.hasOwn(owner,name)||(name==="reminders"||name==="events")&&isRecord(result.schedule)&&Object.hasOwn(result.schedule,name)||["files","tests","docs"].includes(name)&&isRecord(result.linked)&&Array.isArray(result.linked[name])&&result.linked[name].length>0}function resolveGetReceipt(result){if(!isRecord(result.item))return;const item=result.item,itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"],resultGroups=["body","children","claim_state","linked","schedule"],materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result),ownerFor=name=>itemGroups.includes(name)||name==="body"||name==="dependency_provenance"?item:result,groups=["body",...itemGroups,...resultGroups.slice(1),...materialGroups?.has("dependency_provenance")?["dependency_provenance"]:[],...materialGroups?.has("blockers")||Object.hasOwn(result,"blockers")?["blockers"]:[]].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:name==="blockers"?"--full":name==="dependency_provenance"?"--fields dependencies":`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>isGetFieldGroupIncluded(name,ownerFor(name),result)?[name]:[])))}function resolveListOrSearchReceipt(result){if(isRecord(result.projection))return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode=="string")return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!(!isRecord(result.selected)||typeof result.selected.summary!="boolean"))return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-"))return resolveListOrSearchReceipt(result);if(rootCommand==="search")return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}]);if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result)}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result))return result;const receipt=resolveOutputOmissionReceipt(command,result),declaredRowContract=result.row_contract,rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result),disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;return isRecord(disclosedResult.omission_receipt)||receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
|
|
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]="a65d6520-0e6f-5627-a4dd-bd455c2db0fa")}catch{}})();import{EXIT_CODE}from"../core/shared/constants.js";import{PmCliError}from"../core/shared/errors.js";const MATERIAL_FIELD_GROUPS_BY_RESULT=new WeakMap;function registerOutputMaterialFieldGroups(result,fieldGroups){MATERIAL_FIELD_GROUPS_BY_RESULT.set(result,new Set(fieldGroups))}const PM_READ_ROW_JQ_SELECTOR='.row_contract.row_keys[] as $key | getpath($key | split(".")) | if type == "array" then .[] else if type == "object" then to_entries[] else empty end end',PM_READ_ROW_CONTRACTS={context:{row_keys:["high_level","low_level"],fields:"supported"},get:{row_keys:["children"],fields:"supported"},list:{row_keys:["items"],fields:"supported"},next:{row_keys:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],fields:"unsupported"},search:{row_keys:["items"],fields:"supported"},activity:{row_keys:["activity_digest","compact_activity","provenance_activity","activity"],fields:"unsupported"},history:{row_keys:["compact_history","provenance_history","history","diff"],fields:"unsupported"},deps:{row_keys:["graph.nodes","graph.edges","context.nodes","context.edges"],fields:"unsupported"},health:{row_keys:["checks"],fields:"unsupported"},aggregate:{row_keys:["groups"],fields:"unsupported"},duplicates:{row_keys:["clusters"],fields:"unsupported"},stats:{row_keys:["by_type","by_status"],fields:"unsupported"},comments:{row_keys:["comments"],fields:"unsupported"},notes:{row_keys:["notes"],fields:"unsupported"},learnings:{row_keys:["learnings"],fields:"unsupported"},files:{row_keys:["files"],fields:"unsupported"},docs:{row_keys:["docs"],fields:"unsupported"},validate:{row_keys:["checks","warnings"],fields:"unsupported"},contracts:{row_keys:["command_summaries","commands"],fields:"unsupported"}},PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS=[{command:"activity",complete_mode:"full",omissions_by_mode:{digest:[{name:"event_rows",restore_with:"--raw"}],compact:[{name:"provenance",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}},{command:"history",complete_mode:"full",omissions_by_mode:{compact:[{name:"raw_history",restore_with:"--full"}],provenance:[{name:"patch_and_hashes",restore_with:"--full"}]}}];function assertProjectionModeChoice(compactRequested,fullRequested,compactFlag){if(compactRequested&&fullRequested)throw new PmCliError(`${compactFlag} cannot be combined with --full`,EXIT_CODE.USAGE)}function createOutputOmissionReceipt(declaredGroups,includedGroupNames=new Set){const omittedFieldGroups=declaredGroups.filter(group=>!includedGroupNames.has(group.name)).map(group=>({...group}));return{has_omissions:omittedFieldGroups.length>0,omitted_field_group_count:omittedFieldGroups.length,omitted_field_groups:omittedFieldGroups}}function resolveModePairedOutputOmissionReceipt(command,mode){const contract=PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS.find(candidate=>candidate.command===command);if(contract===void 0)throw new TypeError(`Unknown mode-paired output command: ${command}`);if(mode===contract.complete_mode)return createOutputOmissionReceipt([]);const groups=contract.omissions_by_mode[mode];if(groups===void 0)throw new TypeError(`Unknown ${command} output mode: ${mode}`);return createOutputOmissionReceipt(groups)}const CONTEXT_FIELD_GROUPS=[{name:"hierarchy",restore_with:"--section hierarchy"},{name:"activity",restore_with:"--section activity"},{name:"progress",restore_with:"--section progress"},{name:"blockers",restore_with:"--section blockers"},{name:"recently_created",restore_with:"--section recently_created"},{name:"unparented",restore_with:"--section unparented"},{name:"files",restore_with:"--section files"},{name:"workload",restore_with:"--section workload"},{name:"staleness",restore_with:"--section staleness"},{name:"tests",restore_with:"--section tests"}];function isRecord(value){return typeof value=="object"&&value!==null&&!Array.isArray(value)}const READ_ROW_TOON_ENCODINGS=new Set([void 0,"tabular_when_uniform"]),READ_ROW_KINDS=new Set(["collection","none"]),READ_ROW_FIELD_MODES=new Set(["supported","unsupported"]);function isUniqueNonEmptyStringArray(value,allowEmpty){return Array.isArray(value)&&(allowEmpty||value.length>0)&&value.every(entry=>typeof entry=="string"&&entry.length>0)&&new Set(value).size===value.length}function isReadRowContract(value){return isRecord(value)&&typeof value.command=="string"&&value.command.trim().length>0&&READ_ROW_KINDS.has(value.row_kind)&&isUniqueNonEmptyStringArray(value.row_keys,!0)&&(value.continuation_row_keys===void 0||isUniqueNonEmptyStringArray(value.continuation_row_keys,!1))&&READ_ROW_FIELD_MODES.has(value.fields)&&READ_ROW_TOON_ENCODINGS.has(value.toon_encoding)&&(value.row_kind==="collection"?value.row_keys.length>0&&typeof value.jq_selector=="string"&&value.jq_selector.trim().length>0:value.row_keys.length===0&&value.jq_selector===void 0)}const GRAPH_ROW_KEYS={ancestors:["ids"],descendants:["ids"],predecessors:["ids"],successors:["ids"],paths:["paths"],impact:["affected"],audit:["findings"],communities:["communities"],redundancy:["redundant"],dominators:["bottlenecks"],slack:["rows"],centrality:["rows"],articulation:["articulation_points","bridges"],plan:["steps"]},READ_RESULT_SENTINEL_KEYS={context:["sections_included","high_level","low_level"],get:["item"],list:["items","projection"],next:["recommended","ready","decision_needed","gate_needed","containers","blocked","held_by_others"],search:["items","projection"],activity:["activity_digest","compact_activity","provenance_activity","activity"],history:["compact_history","provenance_history","history","diff"],deps:["tree","graph","projection"],health:["checks"],aggregate:["groups"],duplicates:["clusters"],stats:["totals","by_type","by_status"],comments:["comments"],notes:["notes"],learnings:["learnings"],files:["files"],docs:["docs"],validate:["checks","warnings"],contracts:["command_summaries","commands","selected"]};function resolveReadRowContract(command,result){const rawRootCommand=command.trim().toLowerCase().split(/\s+/u,1)[0],rootCommand=rawRootCommand?.startsWith("list-")?"list":rawRootCommand;if(rootCommand==="graph"){const subcommand=typeof result.subcommand=="string"?result.subcommand:"";if(subcommand.length===0)return;const rowKeys=GRAPH_ROW_KEYS[subcommand];if(rowKeys===void 0)return;const activeRowKeys=rowKeys.filter(key=>Array.isArray(result[key])||isRecord(result[key]));return{command:"graph",row_kind:activeRowKeys.length>0?"collection":"none",row_keys:activeRowKeys,fields:"unsupported",...activeRowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}}const declaration=PM_READ_ROW_CONTRACTS[rootCommand],sentinelKeys=READ_RESULT_SENTINEL_KEYS[rootCommand];return declaration===void 0||sentinelKeys===void 0||!sentinelKeys.some(key=>Object.hasOwn(result,key))?void 0:(()=>{const rowKeys=declaration.row_keys.filter(key=>{const value=key.split(".").reduce((current,segment)=>isRecord(current)?current[segment]:void 0,result);return Array.isArray(value)||isRecord(value)});return{command:rootCommand,row_kind:rowKeys.length>0?"collection":"none",row_keys:rowKeys,fields:declaration.fields,...rowKeys.length>0?{jq_selector:PM_READ_ROW_JQ_SELECTOR}:{},toon_encoding:"tabular_when_uniform"}})()}function resolveDeclaredProjectionReceipt(result){if(!isRecord(result.projection)||typeof result.projection.mode!="string"||result.projection.mode.trim().length===0)return;const declared=result.projection.declared_field_groups,included=result.projection.included_field_groups;if(!Array.isArray(declared)||!Array.isArray(included))return;const declaredGroups=declared.filter(entry=>isRecord(entry)&&typeof entry.name=="string"&&entry.name.trim().length>0&&typeof entry.restore_with=="string"&&entry.restore_with.trim().length>0),includedNames=included.filter(entry=>typeof entry=="string");if(declaredGroups.length!==declared.length||includedNames.length!==included.length)return;const declaredNames=new Set(declaredGroups.map(group=>group.name));if(!(declaredNames.size!==declaredGroups.length||new Set(includedNames).size!==includedNames.length||includedNames.some(name=>!declaredNames.has(name))))return createOutputOmissionReceipt(declaredGroups,new Set(includedNames))}function resolveContextReceipt(result){if(!Array.isArray(result.sections_included))return;const receipt=createOutputOmissionReceipt(CONTEXT_FIELD_GROUPS,new Set(result.sections_included.filter(section=>typeof section=="string")));return isRecord(result.summary)&&result.summary.scope==="matching_items"&&(receipt.summary_scope="matching_items"),receipt}function isGetFieldGroupIncluded(name,owner,result){if(name==="dependency_provenance")return!1;const nested=splitNestedGetGroup(name);if(nested!==void 0){const facet=result[nested.facet];return isRecord(facet)&&Object.hasOwn(facet,nested.member)}return Object.hasOwn(owner,name)||(name==="reminders"||name==="events")&&isRecord(result.schedule)&&Object.hasOwn(result.schedule,name)||["files","tests","docs"].includes(name)&&isRecord(result.linked)&&Array.isArray(result.linked[name])&&result.linked[name].length>0}function splitNestedGetGroup(name){const dot=name.indexOf(".");return dot===-1?void 0:{facet:name.slice(0,dot),member:name.slice(dot+1)}}function resolveGetReceipt(result){if(!isRecord(result.item))return;const item=result.item,itemGroups=["comments","notes","learnings","files","tests","docs","reminders","events"],resultGroups=["body","children","claim_state","linked","schedule"],materialGroups=MATERIAL_FIELD_GROUPS_BY_RESULT.get(result),ownerFor=name=>itemGroups.includes(name)||name==="body"||name==="dependency_provenance"?item:result,groups=["body",...itemGroups,...resultGroups.slice(1),...materialGroups?.has("dependency_provenance")?["dependency_provenance"]:[],...materialGroups?.has("blockers")||Object.hasOwn(result,"blockers")?["blockers"]:[],...[...materialGroups??[]].filter(name=>splitNestedGetGroup(name)!==void 0)].filter(name=>materialGroups===void 0||materialGroups.has(name)||Object.hasOwn(ownerFor(name),name)).map(name=>({name,restore_with:name==="blockers"?"--full":name==="dependency_provenance"?"--fields dependencies":`--fields ${name}`}));return createOutputOmissionReceipt(groups,new Set(groups.flatMap(({name})=>isGetFieldGroupIncluded(name,ownerFor(name),result)?[name]:[])))}function resolveListOrSearchReceipt(result){if(isRecord(result.projection))return createOutputOmissionReceipt([{name:"full_item_fields",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_item_fields"]:[]))}function resolveHealthReceipt(result){if(!isRecord(result.projection))return createOutputOmissionReceipt([]);if(typeof result.projection.mode=="string")return createOutputOmissionReceipt([{name:"full_check_details",restore_with:"--full"}],new Set(result.projection.mode==="full"?["full_check_details"]:[]))}function resolveContractsReceipt(result){if(!(!isRecord(result.selected)||typeof result.selected.summary!="boolean"))return createOutputOmissionReceipt([{name:"full_contract_catalog",restore_with:"--full"}],new Set(result.selected.summary?[]:["full_contract_catalog"]))}function resolveOutputOmissionReceipt(command,result){const declaredReceipt=resolveDeclaredProjectionReceipt(result);if(declaredReceipt!==void 0)return declaredReceipt;const[rootCommand]=command.split(/\s+/u,1);if(rootCommand==="context")return resolveContextReceipt(result);if(rootCommand==="get")return resolveGetReceipt(result);if(rootCommand==="list"||rootCommand.startsWith("list-"))return resolveListOrSearchReceipt(result);if(rootCommand==="search")return resolveListOrSearchReceipt(result)??createOutputOmissionReceipt([{name:"projection_metadata",restore_with:"--full"}]);if(rootCommand==="health")return resolveHealthReceipt(result);if(rootCommand==="contracts")return resolveContractsReceipt(result)}function attachOutputOmissionReceipt(command,result){if(command===void 0||!isRecord(result))return result;const receipt=resolveOutputOmissionReceipt(command,result),declaredRowContract=result.row_contract,rowContract=isReadRowContract(declaredRowContract)?declaredRowContract:resolveReadRowContract(command,result),disclosedResult=rowContract!==void 0?{...result,row_contract:rowContract}:Object.hasOwn(result,"row_contract")?Object.fromEntries(Object.entries(result).filter(([key])=>key!=="row_contract")):result;return isRecord(disclosedResult.omission_receipt)||receipt===void 0?disclosedResult:{...disclosedResult,omission_receipt:receipt}}export{PM_MODE_PAIRED_OUTPUT_PROJECTION_CONTRACTS,PM_READ_ROW_CONTRACTS,PM_READ_ROW_JQ_SELECTOR,assertProjectionModeChoice,attachOutputOmissionReceipt,createOutputOmissionReceipt,isReadRowContract,registerOutputMaterialFieldGroups,resolveModePairedOutputOmissionReceipt,resolveOutputOmissionReceipt,resolveReadRowContract};
|
|
2
2
|
//# sourceMappingURL=output-projection.js.map
|